@caspian2026/agent-sdk 0.0.2

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 (371) hide show
  1. package/dist/chunk-018smjq7.js +26 -0
  2. package/dist/chunk-055q0a2m.js +146 -0
  3. package/dist/chunk-07069jq1.js +30 -0
  4. package/dist/chunk-0731m51q.js +8 -0
  5. package/dist/chunk-0awwmrwr.js +46 -0
  6. package/dist/chunk-0htx82k2.js +64 -0
  7. package/dist/chunk-0jmt5sx1.js +104 -0
  8. package/dist/chunk-0kj8bq80.js +252 -0
  9. package/dist/chunk-0kxcq8h9.js +86 -0
  10. package/dist/chunk-0paqc2yw.js +15 -0
  11. package/dist/chunk-0vkfrmqm.js +690 -0
  12. package/dist/chunk-0xjaqda8.js +1124 -0
  13. package/dist/chunk-10qhq6f8.js +458 -0
  14. package/dist/chunk-15m49c67.js +121 -0
  15. package/dist/chunk-15sfg4bs.js +65 -0
  16. package/dist/chunk-162ewhvy.js +869 -0
  17. package/dist/chunk-177s15bv.js +120 -0
  18. package/dist/chunk-19e603rv.js +284 -0
  19. package/dist/chunk-1ax1znzj.js +537 -0
  20. package/dist/chunk-1c4j7qn2.js +319 -0
  21. package/dist/chunk-1gx78081.js +66 -0
  22. package/dist/chunk-1h2famwb.js +49 -0
  23. package/dist/chunk-1nk93fqz.js +357 -0
  24. package/dist/chunk-1xct96nd.js +2520 -0
  25. package/dist/chunk-1xvcvdef.js +90 -0
  26. package/dist/chunk-1yrcnrs7.js +261 -0
  27. package/dist/chunk-21bcvwr7.js +660 -0
  28. package/dist/chunk-2352ts05.js +667 -0
  29. package/dist/chunk-23jzrwsw.js +43 -0
  30. package/dist/chunk-26hg7303.js +62 -0
  31. package/dist/chunk-2f21meep.js +122 -0
  32. package/dist/chunk-2fwze72g.js +24 -0
  33. package/dist/chunk-2gzv8nrw.js +205 -0
  34. package/dist/chunk-2h05vtpv.js +83 -0
  35. package/dist/chunk-2h0y6m16.js +465 -0
  36. package/dist/chunk-2n7bbxm6.js +168 -0
  37. package/dist/chunk-2nv3d0he.js +108 -0
  38. package/dist/chunk-2vqrdwx9.js +1811 -0
  39. package/dist/chunk-3389cj3w.js +120 -0
  40. package/dist/chunk-35sgv3er.js +231 -0
  41. package/dist/chunk-3c25bcsw.js +17 -0
  42. package/dist/chunk-3e20cj49.js +443 -0
  43. package/dist/chunk-3mr5ryx4.js +122 -0
  44. package/dist/chunk-3nk79af8.js +8 -0
  45. package/dist/chunk-3qbdzsvm.js +120 -0
  46. package/dist/chunk-3yprydpw.js +213 -0
  47. package/dist/chunk-430yrtmk.js +492 -0
  48. package/dist/chunk-46hd1gyd.js +140 -0
  49. package/dist/chunk-46hdszda.js +63 -0
  50. package/dist/chunk-46n7byh8.js +102 -0
  51. package/dist/chunk-4cp6193g.js +9076 -0
  52. package/dist/chunk-4dn3n459.js +409 -0
  53. package/dist/chunk-4hv90qcz.js +8 -0
  54. package/dist/chunk-4jm600zv.js +13 -0
  55. package/dist/chunk-4nspekjp.js +69 -0
  56. package/dist/chunk-505mxxa9.js +19 -0
  57. package/dist/chunk-50bay5qy.js +224 -0
  58. package/dist/chunk-537qfvn5.js +345 -0
  59. package/dist/chunk-55raexh7.js +14358 -0
  60. package/dist/chunk-572vjq78.js +56 -0
  61. package/dist/chunk-5apfzkpy.js +87 -0
  62. package/dist/chunk-5ccdsxgy.js +74 -0
  63. package/dist/chunk-5dmhsqap.js +32 -0
  64. package/dist/chunk-5fs6nkjr.js +98 -0
  65. package/dist/chunk-5nchekqe.js +87 -0
  66. package/dist/chunk-5pp28k2r.js +120 -0
  67. package/dist/chunk-5rt4b8q9.js +116 -0
  68. package/dist/chunk-5rv9c8yd.js +1072 -0
  69. package/dist/chunk-5z28bqne.js +6748 -0
  70. package/dist/chunk-64c1avct.js +13 -0
  71. package/dist/chunk-66zry909.js +11 -0
  72. package/dist/chunk-682qgta2.js +102 -0
  73. package/dist/chunk-68ffk5qa.js +14 -0
  74. package/dist/chunk-68w91pzt.js +79 -0
  75. package/dist/chunk-69fgaak0.js +654 -0
  76. package/dist/chunk-69n11zng.js +436 -0
  77. package/dist/chunk-6dj5t602.js +341 -0
  78. package/dist/chunk-6gh20s05.js +146 -0
  79. package/dist/chunk-6maej1hh.js +502 -0
  80. package/dist/chunk-6nsd9606.js +790 -0
  81. package/dist/chunk-6p4cyhb3.js +16 -0
  82. package/dist/chunk-6t4a9cgj.js +877 -0
  83. package/dist/chunk-6t8yqfks.js +227 -0
  84. package/dist/chunk-6vthy0fj.js +213 -0
  85. package/dist/chunk-70cw4cg9.js +1026 -0
  86. package/dist/chunk-70eey1nh.js +164 -0
  87. package/dist/chunk-76j2e9vy.js +68 -0
  88. package/dist/chunk-7acgdm7x.js +93 -0
  89. package/dist/chunk-7aw745vx.js +40175 -0
  90. package/dist/chunk-7gvwg1v9.js +122 -0
  91. package/dist/chunk-7h2ybnf3.js +636 -0
  92. package/dist/chunk-7kcm5hn2.js +155 -0
  93. package/dist/chunk-7m2hp89m.js +73 -0
  94. package/dist/chunk-7mqab3z7.js +31 -0
  95. package/dist/chunk-7sgtxrsc.js +1059 -0
  96. package/dist/chunk-7wm5s02e.js +216 -0
  97. package/dist/chunk-7xyswgjh.js +8 -0
  98. package/dist/chunk-7yxvpj5j.js +1452 -0
  99. package/dist/chunk-80a8vabn.js +93 -0
  100. package/dist/chunk-83e71kz6.js +180 -0
  101. package/dist/chunk-83hfzbx3.js +10 -0
  102. package/dist/chunk-8g5pe1gr.js +37 -0
  103. package/dist/chunk-8g747a8x.js +26 -0
  104. package/dist/chunk-8hj8ms5q.js +111 -0
  105. package/dist/chunk-8mkwsdk1.js +61 -0
  106. package/dist/chunk-8n42zyfx.js +40 -0
  107. package/dist/chunk-8qhxyqj9.js +1155 -0
  108. package/dist/chunk-8y30k9pz.js +38 -0
  109. package/dist/chunk-960ze3jj.js +124 -0
  110. package/dist/chunk-97wgdsab.js +35 -0
  111. package/dist/chunk-9grztvcg.js +93 -0
  112. package/dist/chunk-9x5zgy22.js +12 -0
  113. package/dist/chunk-a8792r1c.js +620 -0
  114. package/dist/chunk-ahr1r7c6.js +4275 -0
  115. package/dist/chunk-ase86y73.js +15 -0
  116. package/dist/chunk-b0kf00ff.js +637 -0
  117. package/dist/chunk-b0qptb1k.js +640 -0
  118. package/dist/chunk-b1kcd3ss.js +27 -0
  119. package/dist/chunk-b2fd462a.js +54 -0
  120. package/dist/chunk-bdrjvs5k.js +157 -0
  121. package/dist/chunk-beg7bdyz.js +90 -0
  122. package/dist/chunk-bg4x9ex0.js +21 -0
  123. package/dist/chunk-bktfq0ns.js +95 -0
  124. package/dist/chunk-bmbq6nt1.js +145 -0
  125. package/dist/chunk-bvf2z3g6.js +1003 -0
  126. package/dist/chunk-bxcfz5gy.js +56 -0
  127. package/dist/chunk-c11swzas.js +5368 -0
  128. package/dist/chunk-c37j5zxe.js +57 -0
  129. package/dist/chunk-c5mz5vw2.js +117 -0
  130. package/dist/chunk-c6sjhj89.js +1284 -0
  131. package/dist/chunk-c7jwbe76.js +29030 -0
  132. package/dist/chunk-cc2tg4q8.js +311 -0
  133. package/dist/chunk-cdhmrbj4.js +6353 -0
  134. package/dist/chunk-cdz5yb0r.js +57 -0
  135. package/dist/chunk-cfv996bs.js +22 -0
  136. package/dist/chunk-cgfdkzhb.js +12 -0
  137. package/dist/chunk-chakj069.js +310 -0
  138. package/dist/chunk-chsyvavm.js +3435 -0
  139. package/dist/chunk-cnsj3vq2.js +35 -0
  140. package/dist/chunk-ctdg0qxh.js +1386 -0
  141. package/dist/chunk-cxq7gc42.js +386 -0
  142. package/dist/chunk-d1pyf9as.js +8586 -0
  143. package/dist/chunk-d4kwjqjy.js +308 -0
  144. package/dist/chunk-d4mdda98.js +94 -0
  145. package/dist/chunk-d7886r6a.js +13870 -0
  146. package/dist/chunk-d7f1pzkq.js +95 -0
  147. package/dist/chunk-ddsjkqs4.js +39 -0
  148. package/dist/chunk-dm3n2qgd.js +24 -0
  149. package/dist/chunk-e2mv8ts8.js +115 -0
  150. package/dist/chunk-e4bhfc6d.js +2720 -0
  151. package/dist/chunk-e4p1jbs4.js +58 -0
  152. package/dist/chunk-e7h4qxgw.js +21 -0
  153. package/dist/chunk-e8p3fy6v.js +202 -0
  154. package/dist/chunk-e97mp86b.js +111 -0
  155. package/dist/chunk-ebqwkhyf.js +145 -0
  156. package/dist/chunk-eenq3avg.js +69 -0
  157. package/dist/chunk-efgjfast.js +61 -0
  158. package/dist/chunk-ehtwnxpg.js +1591 -0
  159. package/dist/chunk-en8wkxh7.js +173 -0
  160. package/dist/chunk-enkdxqas.js +33 -0
  161. package/dist/chunk-eqp1rfft.js +17 -0
  162. package/dist/chunk-ercvcek8.js +266 -0
  163. package/dist/chunk-etgh9xvt.js +369 -0
  164. package/dist/chunk-ev3qkf76.js +106 -0
  165. package/dist/chunk-evp5pb9x.js +3567 -0
  166. package/dist/chunk-ewadzrm8.js +103 -0
  167. package/dist/chunk-exah13mz.js +94 -0
  168. package/dist/chunk-f0rzvqmq.js +87 -0
  169. package/dist/chunk-f1m9pect.js +258 -0
  170. package/dist/chunk-fajg8x36.js +8158 -0
  171. package/dist/chunk-fbv4apne.js +51 -0
  172. package/dist/chunk-fbvw6wq9.js +116 -0
  173. package/dist/chunk-feyzykye.js +10 -0
  174. package/dist/chunk-fn1vvj8k.js +894 -0
  175. package/dist/chunk-fshfxw2q.js +183 -0
  176. package/dist/chunk-fyc5fepv.js +10 -0
  177. package/dist/chunk-g9f19ttm.js +15 -0
  178. package/dist/chunk-gcpfxk0c.js +644 -0
  179. package/dist/chunk-gdg6411p.js +106 -0
  180. package/dist/chunk-gkyzz8er.js +849 -0
  181. package/dist/chunk-gxahdggv.js +71 -0
  182. package/dist/chunk-h6fsks9j.js +220 -0
  183. package/dist/chunk-h9n54swm.js +27 -0
  184. package/dist/chunk-hakdhagh.js +16606 -0
  185. package/dist/chunk-hchy0hq6.js +159 -0
  186. package/dist/chunk-hh3k5s1s.js +180 -0
  187. package/dist/chunk-hqqkj5pg.js +202 -0
  188. package/dist/chunk-htpehq9t.js +251 -0
  189. package/dist/chunk-hwfknpxv.js +39 -0
  190. package/dist/chunk-hwn8vetn.js +394 -0
  191. package/dist/chunk-hx3j6n92.js +178 -0
  192. package/dist/chunk-hyb749hd.js +194 -0
  193. package/dist/chunk-hzgnejb1.js +90 -0
  194. package/dist/chunk-hzknr99c.js +477 -0
  195. package/dist/chunk-j3zhb8vv.js +152 -0
  196. package/dist/chunk-j5bth84e.js +97 -0
  197. package/dist/chunk-j64ga6ta.js +8035 -0
  198. package/dist/chunk-jaaxk89e.js +113 -0
  199. package/dist/chunk-jd32zbps.js +15 -0
  200. package/dist/chunk-jfja8q7w.js +91 -0
  201. package/dist/chunk-jgjqa49s.js +27 -0
  202. package/dist/chunk-jgpmpgx6.js +19 -0
  203. package/dist/chunk-jgwd85hp.js +91 -0
  204. package/dist/chunk-jk69qtzx.js +277 -0
  205. package/dist/chunk-jr1xm1dd.js +147 -0
  206. package/dist/chunk-jss0azv7.js +2337 -0
  207. package/dist/chunk-jxpmkae9.js +108 -0
  208. package/dist/chunk-jy9rxxqe.js +102 -0
  209. package/dist/chunk-jyw3np47.js +264 -0
  210. package/dist/chunk-jzthz1bx.js +15 -0
  211. package/dist/chunk-k0p9w03v.js +4957 -0
  212. package/dist/chunk-k2rybwww.js +92 -0
  213. package/dist/chunk-k3939ggz.js +168 -0
  214. package/dist/chunk-k591cwbg.js +345 -0
  215. package/dist/chunk-k5ez1h65.js +108 -0
  216. package/dist/chunk-k8vp0atq.js +2331 -0
  217. package/dist/chunk-kajf3jgq.js +694 -0
  218. package/dist/chunk-kbm69rtz.js +276 -0
  219. package/dist/chunk-kjh11txh.js +419 -0
  220. package/dist/chunk-kqggbte3.js +326 -0
  221. package/dist/chunk-kr6qfwq0.js +95 -0
  222. package/dist/chunk-kvfg8eeg.js +150 -0
  223. package/dist/chunk-kwekc97v.js +18 -0
  224. package/dist/chunk-m1cehfta.js +861 -0
  225. package/dist/chunk-m87bhhqv.js +61 -0
  226. package/dist/chunk-mg7pbk0r.js +151 -0
  227. package/dist/chunk-mpbfkp8j.js +418 -0
  228. package/dist/chunk-mpk1sjyk.js +117 -0
  229. package/dist/chunk-msecaxyj.js +74 -0
  230. package/dist/chunk-mswx2nma.js +103 -0
  231. package/dist/chunk-mw1kpeg9.js +6895 -0
  232. package/dist/chunk-mxr2s6d1.js +89 -0
  233. package/dist/chunk-my40g5hp.js +560 -0
  234. package/dist/chunk-n0kmh4ra.js +338 -0
  235. package/dist/chunk-n18q5yqs.js +397 -0
  236. package/dist/chunk-n7pnyq43.js +131 -0
  237. package/dist/chunk-naybw0p0.js +32 -0
  238. package/dist/chunk-nb6abcch.js +83 -0
  239. package/dist/chunk-ne5r3k03.js +350 -0
  240. package/dist/chunk-nebezy1d.js +997 -0
  241. package/dist/chunk-netzwgv1.js +154 -0
  242. package/dist/chunk-nhapyawz.js +32994 -0
  243. package/dist/chunk-npnvheft.js +156 -0
  244. package/dist/chunk-nrtksr2p.js +51 -0
  245. package/dist/chunk-nw9t5pq9.js +132 -0
  246. package/dist/chunk-nxgsnh2y.js +735 -0
  247. package/dist/chunk-p11xp4xp.js +266 -0
  248. package/dist/chunk-p1hwrf72.js +74 -0
  249. package/dist/chunk-p1zj9mg9.js +567 -0
  250. package/dist/chunk-p39a677r.js +115 -0
  251. package/dist/chunk-p7vkh4wx.js +15 -0
  252. package/dist/chunk-p8na2wwp.js +14 -0
  253. package/dist/chunk-pcb7fbyg.js +259 -0
  254. package/dist/chunk-pckwmrzd.js +409 -0
  255. package/dist/chunk-ped973jn.js +111 -0
  256. package/dist/chunk-phd1qfpc.js +5971 -0
  257. package/dist/chunk-pkkngdv0.js +524 -0
  258. package/dist/chunk-ppwjyveh.js +8 -0
  259. package/dist/chunk-pqvr8jq7.js +324 -0
  260. package/dist/chunk-prcah3ys.js +106 -0
  261. package/dist/chunk-ps49ymvj.js +43 -0
  262. package/dist/chunk-pwwa7s62.js +11 -0
  263. package/dist/chunk-pxdzy0jh.js +134 -0
  264. package/dist/chunk-q3jr5t07.js +62 -0
  265. package/dist/chunk-q6cfkntd.js +675 -0
  266. package/dist/chunk-q6m26rc8.js +88 -0
  267. package/dist/chunk-q6xs51jj.js +332 -0
  268. package/dist/chunk-q7jnesv8.js +74 -0
  269. package/dist/chunk-q7zpf4r2.js +440 -0
  270. package/dist/chunk-q8c88vjm.js +24 -0
  271. package/dist/chunk-qajrkk97.js +298 -0
  272. package/dist/chunk-qatfdxvd.js +34 -0
  273. package/dist/chunk-qb6k2afy.js +153 -0
  274. package/dist/chunk-qfk94vcn.js +329 -0
  275. package/dist/chunk-qj2e1apf.js +471 -0
  276. package/dist/chunk-qj2mk79w.js +111 -0
  277. package/dist/chunk-qk7dfae6.js +267 -0
  278. package/dist/chunk-qnfx3qtx.js +617 -0
  279. package/dist/chunk-qp2qdcda.js +100 -0
  280. package/dist/chunk-qq0phwn8.js +458 -0
  281. package/dist/chunk-qwqjesx7.js +258 -0
  282. package/dist/chunk-qygmcg7w.js +60 -0
  283. package/dist/chunk-qz2x630m.js +49145 -0
  284. package/dist/chunk-qzj4e8fn.js +357 -0
  285. package/dist/chunk-ratvcbmn.js +255 -0
  286. package/dist/chunk-rkg741k3.js +37 -0
  287. package/dist/chunk-rn0v1hk8.js +34 -0
  288. package/dist/chunk-rsq0h0rz.js +91 -0
  289. package/dist/chunk-rvnb2gn6.js +1053 -0
  290. package/dist/chunk-rx278zpa.js +75 -0
  291. package/dist/chunk-s3hsqf80.js +473 -0
  292. package/dist/chunk-s4cb0bcb.js +655 -0
  293. package/dist/chunk-s8kj6ajy.js +32 -0
  294. package/dist/chunk-sd36yzx8.js +954 -0
  295. package/dist/chunk-sfcpjh4r.js +98 -0
  296. package/dist/chunk-spybh2dy.js +175 -0
  297. package/dist/chunk-sw9ax3ym.js +92 -0
  298. package/dist/chunk-szj5wvdy.js +28 -0
  299. package/dist/chunk-t29a6zb5.js +45 -0
  300. package/dist/chunk-t9p85zff.js +24 -0
  301. package/dist/chunk-tc1aazk4.js +131 -0
  302. package/dist/chunk-tdbz9gbm.js +1030 -0
  303. package/dist/chunk-tjcfpk38.js +208 -0
  304. package/dist/chunk-tp2jxmcx.js +8427 -0
  305. package/dist/chunk-tqmtkm0k.js +92 -0
  306. package/dist/chunk-tvgvt220.js +22820 -0
  307. package/dist/chunk-v0qraze5.js +291 -0
  308. package/dist/chunk-v1kzp02e.js +785 -0
  309. package/dist/chunk-v78fj8by.js +145 -0
  310. package/dist/chunk-v8g3kad0.js +101 -0
  311. package/dist/chunk-v9smspw2.js +4301 -0
  312. package/dist/chunk-vawgyev5.js +157 -0
  313. package/dist/chunk-vb3x3cxe.js +375 -0
  314. package/dist/chunk-vf612n57.js +472 -0
  315. package/dist/chunk-vjn8mbcw.js +198 -0
  316. package/dist/chunk-vmbfv1y5.js +295 -0
  317. package/dist/chunk-vrf54kmt.js +321 -0
  318. package/dist/chunk-vyjeh50y.js +2149 -0
  319. package/dist/chunk-vzgkedm9.js +159745 -0
  320. package/dist/chunk-w004kfw0.js +245 -0
  321. package/dist/chunk-w0yhbmxn.js +132 -0
  322. package/dist/chunk-w4yn8cq7.js +123 -0
  323. package/dist/chunk-waqwgprq.js +1164 -0
  324. package/dist/chunk-wayfjcwt.js +447 -0
  325. package/dist/chunk-wby6yd4m.js +91 -0
  326. package/dist/chunk-wha6v7za.js +705 -0
  327. package/dist/chunk-wjcq2vkf.js +641 -0
  328. package/dist/chunk-wtjt9qyk.js +2670 -0
  329. package/dist/chunk-x2pvw7xw.js +42 -0
  330. package/dist/chunk-x6r4v44b.js +8 -0
  331. package/dist/chunk-x8d2ehd7.js +19 -0
  332. package/dist/chunk-xd6kmmb1.js +95 -0
  333. package/dist/chunk-xp61y5ba.js +125 -0
  334. package/dist/chunk-xv3era3s.js +8 -0
  335. package/dist/chunk-xxw9a0bq.js +58 -0
  336. package/dist/chunk-xzhaa7gd.js +112 -0
  337. package/dist/chunk-y1784krc.js +19 -0
  338. package/dist/chunk-y4ca9kqz.js +3830 -0
  339. package/dist/chunk-yff68ex1.js +113 -0
  340. package/dist/chunk-yg4vgpxs.js +436 -0
  341. package/dist/chunk-yk62vxj2.js +2964 -0
  342. package/dist/chunk-ym5r3jnk.js +2007 -0
  343. package/dist/chunk-ysanv95x.js +225 -0
  344. package/dist/chunk-yvtzznds.js +63 -0
  345. package/dist/chunk-yyex5gsf.js +269 -0
  346. package/dist/chunk-yyf72f78.js +456 -0
  347. package/dist/chunk-z19sd3bt.js +1648 -0
  348. package/dist/chunk-z2dp53wn.js +17 -0
  349. package/dist/chunk-z9n0183s.js +39 -0
  350. package/dist/chunk-zb8f6h5g.js +9174 -0
  351. package/dist/chunk-zctfbr1v.js +594 -0
  352. package/dist/chunk-zesnmkg3.js +2840 -0
  353. package/dist/chunk-zf47r1b7.js +94 -0
  354. package/dist/chunk-zghtdbat.js +253 -0
  355. package/dist/chunk-zpmwvd09.js +275 -0
  356. package/dist/chunk-zqncgyf6.js +127 -0
  357. package/dist/chunk-zr6mz36s.js +281 -0
  358. package/dist/chunk-zshzdw1n.js +141 -0
  359. package/dist/chunk-zx5kw7z4.js +40 -0
  360. package/dist/chunk-zzm33q8x.js +8 -0
  361. package/dist/cli.js +91 -0
  362. package/dist/download-ripgrep.js +24821 -0
  363. package/dist/vendor/audio-capture/arm64-darwin/audio-capture.node +0 -0
  364. package/dist/vendor/audio-capture/arm64-linux/audio-capture.node +0 -0
  365. package/dist/vendor/audio-capture/arm64-win32/audio-capture.node +0 -0
  366. package/dist/vendor/audio-capture/x64-darwin/audio-capture.node +0 -0
  367. package/dist/vendor/audio-capture/x64-linux/audio-capture.node +0 -0
  368. package/dist/vendor/audio-capture/x64-win32/audio-capture.node +0 -0
  369. package/dist/vendor/ripgrep/x64-win32/rg.exe +0 -0
  370. package/package.json +122 -0
  371. package/scripts/postinstall.cjs +319 -0
@@ -0,0 +1,2964 @@
1
+ // @bun
2
+ import {
3
+ notifySessionStateChanged
4
+ } from "./chunk-8mkwsdk1.js";
5
+ import {
6
+ init_slashCommandParsing,
7
+ parseSlashCommand
8
+ } from "./chunk-rn0v1hk8.js";
9
+ import {
10
+ AccountInfoSchema,
11
+ AgentDefinitionSchema,
12
+ AgentInfoSchema,
13
+ DEFAULT_CRON_JITTER_CONFIG,
14
+ FastModeStateSchema,
15
+ HookEventSchema,
16
+ HookInputSchema,
17
+ McpServerConfigForProcessTransportSchema,
18
+ McpServerStatusSchema,
19
+ ModelInfoSchema,
20
+ PermissionModeSchema,
21
+ PermissionUpdateSchema,
22
+ SDKMessageSchema,
23
+ SDKPostTurnSummaryMessageSchema,
24
+ SDKStreamlinedTextMessageSchema,
25
+ SDKStreamlinedToolUseSummaryMessageSchema,
26
+ SDKUserMessageSchema,
27
+ Select,
28
+ SlashCommandSchema,
29
+ Spinner,
30
+ Stream,
31
+ addMarketplaceSource,
32
+ applyPermissionUpdates,
33
+ createAttachmentMessage,
34
+ createCommandInputMessage,
35
+ createImageMetadataText,
36
+ createSystemMessage,
37
+ createUserMessage,
38
+ cronToHuman,
39
+ executePermissionRequestHooks,
40
+ executeUserPromptSubmitHooks,
41
+ extractTag,
42
+ fileHistoryCanRestore,
43
+ fileHistoryEnabled,
44
+ fileHistoryGetDiffStats,
45
+ findCommand,
46
+ findMissedTasks,
47
+ getAttachmentMessages,
48
+ getCommandName,
49
+ getContentText,
50
+ getCronFilePath,
51
+ getDeclaredMarketplaces,
52
+ getUserPromptSubmitHookBlockingMessage,
53
+ hasCronTasksSync,
54
+ hasPermissionsToUseTool,
55
+ hookJSONOutputSchema,
56
+ init_AppState,
57
+ init_PermissionUpdate,
58
+ init_PermissionUpdateSchema,
59
+ init_Spinner,
60
+ init_attachments,
61
+ init_commandLifecycle,
62
+ init_commands1 as init_commands,
63
+ init_coreSchemas,
64
+ init_cron,
65
+ init_cronTasks,
66
+ init_events,
67
+ init_fileHistory,
68
+ init_generators,
69
+ init_genericProcessUtils,
70
+ init_hooks,
71
+ init_hooks1 as init_hooks2,
72
+ init_imageResizer,
73
+ init_imageStore,
74
+ init_marketplaceManager,
75
+ init_messages1 as init_messages,
76
+ init_permissions,
77
+ init_queryProfiler,
78
+ init_select,
79
+ init_sessionTracing,
80
+ init_stream,
81
+ init_textInputTypes,
82
+ init_useTerminalSize,
83
+ isBridgeSafeCommand,
84
+ isEmptyMessageText,
85
+ isProcessRunning,
86
+ isSyntheticMessage,
87
+ isToolUseResultMessage,
88
+ isValidImagePaste,
89
+ jitteredNextCronRunMs,
90
+ loadKnownMarketplacesConfig,
91
+ logOTelEvent,
92
+ markCronTasksFired,
93
+ maybeResizeAndDownsampleImageBlock,
94
+ notifyCommandLifecycle,
95
+ oneShotJitteredNextCronRunMs,
96
+ permissionUpdateSchema,
97
+ persistPermissionUpdates,
98
+ queryCheckpoint,
99
+ readCronTasks,
100
+ redactIfDisabled,
101
+ removeCronTasks,
102
+ startInteractionSpan,
103
+ storeImages,
104
+ toArray,
105
+ useAppState
106
+ } from "./chunk-vzgkedm9.js";
107
+ import {
108
+ init_useExitOnCtrlCDWithKeybindings,
109
+ useExitOnCtrlCDWithKeybindings
110
+ } from "./chunk-kbm69rtz.js";
111
+ import {
112
+ init_useKeybinding
113
+ } from "./chunk-68ffk5qa.js";
114
+ import {
115
+ getFeatureValue_CACHED_WITH_REFRESH,
116
+ init_file,
117
+ init_growthbook,
118
+ init_isEqual,
119
+ init_schemas,
120
+ isEqual_default,
121
+ isLocalMarketplaceSource,
122
+ pathExists
123
+ } from "./chunk-tp2jxmcx.js";
124
+ import {
125
+ init_json,
126
+ safeParseJSON
127
+ } from "./chunk-z19sd3bt.js";
128
+ import {
129
+ count,
130
+ init_array
131
+ } from "./chunk-6nsd9606.js";
132
+ import {
133
+ init_lazySchema,
134
+ lazySchema
135
+ } from "./chunk-64c1avct.js";
136
+ import {
137
+ init_v4,
138
+ v4_default
139
+ } from "./chunk-8g747a8x.js";
140
+ import {
141
+ exports_external
142
+ } from "./chunk-d7886r6a.js";
143
+ import {
144
+ formatRelativeTimeAgo,
145
+ init_format,
146
+ truncate
147
+ } from "./chunk-yyf72f78.js";
148
+ import {
149
+ Divider,
150
+ ThemedBox_default,
151
+ ThemedText,
152
+ init_src,
153
+ useKeybinding,
154
+ useKeybindings,
155
+ useTerminalSize
156
+ } from "./chunk-c7jwbe76.js";
157
+ import {
158
+ require_jsx_dev_runtime,
159
+ require_react
160
+ } from "./chunk-7sgtxrsc.js";
161
+ import {
162
+ init_analytics,
163
+ logEvent
164
+ } from "./chunk-x8d2ehd7.js";
165
+ import {
166
+ findCanonicalGitRoot,
167
+ init_diagLogs,
168
+ init_git,
169
+ logForDiagnosticsNoPII
170
+ } from "./chunk-tdbz9gbm.js";
171
+ import {
172
+ BASH_STDERR_TAG,
173
+ BASH_STDOUT_TAG,
174
+ COMMAND_MESSAGE_TAG,
175
+ LOCAL_COMMAND_STDERR_TAG,
176
+ LOCAL_COMMAND_STDOUT_TAG,
177
+ TASK_NOTIFICATION_TAG,
178
+ TEAMMATE_MESSAGE_TAG,
179
+ TICK_TAG,
180
+ init_displayTags,
181
+ init_log,
182
+ init_xml,
183
+ logError,
184
+ stripDisplayTags
185
+ } from "./chunk-1nk93fqz.js";
186
+ import {
187
+ figures_default,
188
+ init_figures
189
+ } from "./chunk-qajrkk97.js";
190
+ import {
191
+ AbortError,
192
+ errorMessage,
193
+ getErrnoCode,
194
+ init_cleanupRegistry,
195
+ init_debug,
196
+ init_errors,
197
+ init_slowOperations,
198
+ jsonParse,
199
+ jsonStringify,
200
+ logForDebugging,
201
+ registerCleanup
202
+ } from "./chunk-phd1qfpc.js";
203
+ import {
204
+ init_process,
205
+ writeToStdout
206
+ } from "./chunk-fbv4apne.js";
207
+ import {
208
+ createSignal,
209
+ getOriginalCwd,
210
+ getProjectRoot,
211
+ getScheduledTasksEnabled,
212
+ getSessionCronTasks,
213
+ getSessionId,
214
+ init_signal,
215
+ init_state,
216
+ removeSessionCronTasks,
217
+ setPromptId,
218
+ setScheduledTasksEnabled
219
+ } from "./chunk-k8vp0atq.js";
220
+ import {
221
+ __esm,
222
+ __export,
223
+ __require,
224
+ __toESM
225
+ } from "./chunk-qp2qdcda.js";
226
+
227
+ // src/components/MessageSelector.tsx
228
+ var exports_MessageSelector = {};
229
+ __export(exports_MessageSelector, {
230
+ selectableUserMessagesFilter: () => selectableUserMessagesFilter,
231
+ messagesAfterAreOnlySynthetic: () => messagesAfterAreOnlySynthetic,
232
+ MessageSelector: () => MessageSelector
233
+ });
234
+ import { randomUUID } from "crypto";
235
+ import * as path from "path";
236
+ function isTextBlock(block) {
237
+ return block.type === "text";
238
+ }
239
+ function isSummarizeOption(option) {
240
+ return option === "summarize" || option === "summarize_up_to";
241
+ }
242
+ function MessageSelector({
243
+ messages,
244
+ onPreRestore,
245
+ onRestoreMessage,
246
+ onRestoreCode,
247
+ onSummarize,
248
+ onClose,
249
+ preselectedMessage
250
+ }) {
251
+ const fileHistory = useAppState((s) => s.fileHistory);
252
+ const [error, setError] = import_react.useState(undefined);
253
+ const isFileHistoryEnabled = fileHistoryEnabled();
254
+ const currentUUID = import_react.useMemo(randomUUID, []);
255
+ const messageOptions = import_react.useMemo(() => [
256
+ ...messages.filter(selectableUserMessagesFilter),
257
+ {
258
+ ...createUserMessage({
259
+ content: ""
260
+ }),
261
+ uuid: currentUUID
262
+ }
263
+ ], [messages, currentUUID]);
264
+ const [selectedIndex, setSelectedIndex] = import_react.useState(messageOptions.length - 1);
265
+ const firstVisibleIndex = Math.max(0, Math.min(selectedIndex - Math.floor(MAX_VISIBLE_MESSAGES / 2), messageOptions.length - MAX_VISIBLE_MESSAGES));
266
+ const hasMessagesToSelect = messageOptions.length > 1;
267
+ const [messageToRestore, setMessageToRestore] = import_react.useState(preselectedMessage);
268
+ const [diffStatsForRestore, setDiffStatsForRestore] = import_react.useState(undefined);
269
+ import_react.useEffect(() => {
270
+ if (!preselectedMessage || !isFileHistoryEnabled)
271
+ return;
272
+ let cancelled = false;
273
+ fileHistoryGetDiffStats(fileHistory, preselectedMessage.uuid).then((stats) => {
274
+ if (!cancelled)
275
+ setDiffStatsForRestore(stats);
276
+ });
277
+ return () => {
278
+ cancelled = true;
279
+ };
280
+ }, [preselectedMessage, isFileHistoryEnabled, fileHistory]);
281
+ const [isRestoring, setIsRestoring] = import_react.useState(false);
282
+ const [restoringOption, setRestoringOption] = import_react.useState(null);
283
+ const [selectedRestoreOption, setSelectedRestoreOption] = import_react.useState("both");
284
+ const [summarizeFromFeedback, setSummarizeFromFeedback] = import_react.useState("");
285
+ const [summarizeUpToFeedback, setSummarizeUpToFeedback] = import_react.useState("");
286
+ function getRestoreOptions(canRestoreCode2) {
287
+ const baseOptions = canRestoreCode2 ? [
288
+ { value: "both", label: "Restore code and conversation" },
289
+ { value: "conversation", label: "Restore conversation" },
290
+ { value: "code", label: "Restore code" }
291
+ ] : [{ value: "conversation", label: "Restore conversation" }];
292
+ const summarizeInputProps = {
293
+ type: "input",
294
+ placeholder: "add context (optional)",
295
+ initialValue: "",
296
+ allowEmptySubmitToCancel: true,
297
+ showLabelWithValue: true,
298
+ labelValueSeparator: ": "
299
+ };
300
+ baseOptions.push({
301
+ value: "summarize",
302
+ label: "Summarize from here",
303
+ ...summarizeInputProps,
304
+ onChange: setSummarizeFromFeedback
305
+ });
306
+ if (process.env.USER_TYPE === "ant") {
307
+ baseOptions.push({
308
+ value: "summarize_up_to",
309
+ label: "Summarize up to here",
310
+ ...summarizeInputProps,
311
+ onChange: setSummarizeUpToFeedback
312
+ });
313
+ }
314
+ baseOptions.push({ value: "nevermind", label: "Never mind" });
315
+ return baseOptions;
316
+ }
317
+ import_react.useEffect(() => {
318
+ logEvent("tengu_message_selector_opened", {});
319
+ }, []);
320
+ async function restoreConversationDirectly(message) {
321
+ onPreRestore();
322
+ setIsRestoring(true);
323
+ try {
324
+ await onRestoreMessage(message);
325
+ setIsRestoring(false);
326
+ onClose();
327
+ } catch (error2) {
328
+ logError(error2);
329
+ setIsRestoring(false);
330
+ setError(`Failed to restore the conversation:
331
+ ${error2}`);
332
+ }
333
+ }
334
+ async function handleSelect(message) {
335
+ const index = messages.indexOf(message);
336
+ const indexFromEnd = messages.length - 1 - index;
337
+ logEvent("tengu_message_selector_selected", {
338
+ index_from_end: indexFromEnd,
339
+ message_type: message.type,
340
+ is_current_prompt: false
341
+ });
342
+ if (!messages.includes(message)) {
343
+ onClose();
344
+ return;
345
+ }
346
+ if (!isFileHistoryEnabled) {
347
+ await restoreConversationDirectly(message);
348
+ return;
349
+ }
350
+ const diffStats = await fileHistoryGetDiffStats(fileHistory, message.uuid);
351
+ setMessageToRestore(message);
352
+ setDiffStatsForRestore(diffStats);
353
+ }
354
+ async function onSelectRestoreOption(option) {
355
+ logEvent("tengu_message_selector_restore_option_selected", {
356
+ option
357
+ });
358
+ if (!messageToRestore) {
359
+ setError("Message not found.");
360
+ return;
361
+ }
362
+ if (option === "nevermind") {
363
+ if (preselectedMessage)
364
+ onClose();
365
+ else
366
+ setMessageToRestore(undefined);
367
+ return;
368
+ }
369
+ if (isSummarizeOption(option)) {
370
+ onPreRestore();
371
+ setIsRestoring(true);
372
+ setRestoringOption(option);
373
+ setError(undefined);
374
+ try {
375
+ const direction = option === "summarize_up_to" ? "up_to" : "from";
376
+ const feedback = (direction === "up_to" ? summarizeUpToFeedback : summarizeFromFeedback).trim() || undefined;
377
+ await onSummarize(messageToRestore, feedback, direction);
378
+ setIsRestoring(false);
379
+ setRestoringOption(null);
380
+ setMessageToRestore(undefined);
381
+ onClose();
382
+ } catch (error2) {
383
+ logError(error2);
384
+ setIsRestoring(false);
385
+ setRestoringOption(null);
386
+ setMessageToRestore(undefined);
387
+ setError(`Failed to summarize:
388
+ ${error2}`);
389
+ }
390
+ return;
391
+ }
392
+ onPreRestore();
393
+ setIsRestoring(true);
394
+ setError(undefined);
395
+ let codeError = null;
396
+ let conversationError = null;
397
+ if (option === "code" || option === "both") {
398
+ try {
399
+ await onRestoreCode(messageToRestore);
400
+ } catch (error2) {
401
+ codeError = error2;
402
+ logError(codeError);
403
+ }
404
+ }
405
+ if (option === "conversation" || option === "both") {
406
+ try {
407
+ await onRestoreMessage(messageToRestore);
408
+ } catch (error2) {
409
+ conversationError = error2;
410
+ logError(conversationError);
411
+ }
412
+ }
413
+ setIsRestoring(false);
414
+ setMessageToRestore(undefined);
415
+ if (conversationError && codeError) {
416
+ setError(`Failed to restore the conversation and code:
417
+ ${conversationError}
418
+ ${codeError}`);
419
+ } else if (conversationError) {
420
+ setError(`Failed to restore the conversation:
421
+ ${conversationError}`);
422
+ } else if (codeError) {
423
+ setError(`Failed to restore the code:
424
+ ${codeError}`);
425
+ } else {
426
+ onClose();
427
+ }
428
+ }
429
+ const exitState = useExitOnCtrlCDWithKeybindings();
430
+ const handleEscape = import_react.useCallback(() => {
431
+ if (messageToRestore && !preselectedMessage) {
432
+ setMessageToRestore(undefined);
433
+ return;
434
+ }
435
+ logEvent("tengu_message_selector_cancelled", {});
436
+ onClose();
437
+ }, [onClose, messageToRestore, preselectedMessage]);
438
+ const moveUp = import_react.useCallback(() => setSelectedIndex((prev) => Math.max(0, prev - 1)), []);
439
+ const moveDown = import_react.useCallback(() => setSelectedIndex((prev) => Math.min(messageOptions.length - 1, prev + 1)), [messageOptions.length]);
440
+ const jumpToTop = import_react.useCallback(() => setSelectedIndex(0), []);
441
+ const jumpToBottom = import_react.useCallback(() => setSelectedIndex(messageOptions.length - 1), [messageOptions.length]);
442
+ const handleSelectCurrent = import_react.useCallback(() => {
443
+ const selected = messageOptions[selectedIndex];
444
+ if (selected) {
445
+ handleSelect(selected);
446
+ }
447
+ }, [messageOptions, selectedIndex, handleSelect]);
448
+ useKeybinding("confirm:no", handleEscape, {
449
+ context: "Confirmation",
450
+ isActive: !messageToRestore
451
+ });
452
+ useKeybindings({
453
+ "messageSelector:up": moveUp,
454
+ "messageSelector:down": moveDown,
455
+ "messageSelector:top": jumpToTop,
456
+ "messageSelector:bottom": jumpToBottom,
457
+ "messageSelector:select": handleSelectCurrent
458
+ }, {
459
+ context: "MessageSelector",
460
+ isActive: !isRestoring && !error && !messageToRestore && hasMessagesToSelect
461
+ });
462
+ const [fileHistoryMetadata, setFileHistoryMetadata] = import_react.useState({});
463
+ import_react.useEffect(() => {
464
+ async function loadFileHistoryMetadata() {
465
+ if (!isFileHistoryEnabled) {
466
+ return;
467
+ }
468
+ Promise.all(messageOptions.map(async (userMessage, itemIndex) => {
469
+ if (userMessage.uuid !== currentUUID) {
470
+ const canRestore = fileHistoryCanRestore(fileHistory, userMessage.uuid);
471
+ const nextUserMessage = messageOptions.at(itemIndex + 1);
472
+ const diffStats = canRestore ? computeDiffStatsBetweenMessages(messages, userMessage.uuid, nextUserMessage?.uuid !== currentUUID ? nextUserMessage?.uuid : undefined) : undefined;
473
+ if (diffStats !== undefined) {
474
+ setFileHistoryMetadata((prev) => ({
475
+ ...prev,
476
+ [itemIndex]: diffStats
477
+ }));
478
+ } else {
479
+ setFileHistoryMetadata((prev) => ({
480
+ ...prev,
481
+ [itemIndex]: undefined
482
+ }));
483
+ }
484
+ }
485
+ }));
486
+ }
487
+ loadFileHistoryMetadata();
488
+ }, [messageOptions, messages, currentUUID, fileHistory, isFileHistoryEnabled]);
489
+ const canRestoreCode = isFileHistoryEnabled && diffStatsForRestore?.filesChanged && diffStatsForRestore.filesChanged.length > 0;
490
+ const showPickList = !error && !messageToRestore && !preselectedMessage && hasMessagesToSelect;
491
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
492
+ flexDirection: "column",
493
+ width: "100%",
494
+ children: [
495
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Divider, {
496
+ color: "suggestion"
497
+ }, undefined, false, undefined, this),
498
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
499
+ flexDirection: "column",
500
+ marginX: 1,
501
+ gap: 1,
502
+ children: [
503
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
504
+ bold: true,
505
+ color: "suggestion",
506
+ children: "Rewind"
507
+ }, undefined, false, undefined, this),
508
+ error && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
509
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
510
+ color: "error",
511
+ children: [
512
+ "Error: ",
513
+ error
514
+ ]
515
+ }, undefined, true, undefined, this)
516
+ }, undefined, false, undefined, this),
517
+ !hasMessagesToSelect && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
518
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
519
+ children: "Nothing to rewind to yet."
520
+ }, undefined, false, undefined, this)
521
+ }, undefined, false, undefined, this),
522
+ !error && messageToRestore && hasMessagesToSelect && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
523
+ children: [
524
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
525
+ children: [
526
+ "Confirm you want to restore",
527
+ " ",
528
+ !diffStatsForRestore && "the conversation ",
529
+ "to the point before you sent this message:"
530
+ ]
531
+ }, undefined, true, undefined, this),
532
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
533
+ flexDirection: "column",
534
+ paddingLeft: 1,
535
+ borderStyle: "single",
536
+ borderRight: false,
537
+ borderTop: false,
538
+ borderBottom: false,
539
+ borderLeft: true,
540
+ borderLeftDimColor: true,
541
+ children: [
542
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(UserMessageOption, {
543
+ userMessage: messageToRestore,
544
+ color: "text",
545
+ isCurrent: false
546
+ }, undefined, false, undefined, this),
547
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
548
+ dimColor: true,
549
+ children: [
550
+ "(",
551
+ formatRelativeTimeAgo(new Date(messageToRestore.timestamp)),
552
+ ")"
553
+ ]
554
+ }, undefined, true, undefined, this)
555
+ ]
556
+ }, undefined, true, undefined, this),
557
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(RestoreOptionDescription, {
558
+ selectedRestoreOption,
559
+ canRestoreCode: !!canRestoreCode,
560
+ diffStatsForRestore
561
+ }, undefined, false, undefined, this),
562
+ isRestoring && isSummarizeOption(restoringOption) ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
563
+ flexDirection: "row",
564
+ gap: 1,
565
+ children: [
566
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Spinner, {}, undefined, false, undefined, this),
567
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
568
+ children: "Summarizing\u2026"
569
+ }, undefined, false, undefined, this)
570
+ ]
571
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(Select, {
572
+ isDisabled: isRestoring,
573
+ options: getRestoreOptions(!!canRestoreCode),
574
+ defaultFocusValue: canRestoreCode ? "both" : "conversation",
575
+ onFocus: (value) => setSelectedRestoreOption(value),
576
+ onChange: (value) => onSelectRestoreOption(value),
577
+ onCancel: () => preselectedMessage ? onClose() : setMessageToRestore(undefined)
578
+ }, undefined, false, undefined, this),
579
+ canRestoreCode && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
580
+ marginBottom: 1,
581
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
582
+ dimColor: true,
583
+ children: [
584
+ figures_default.warning,
585
+ " Rewinding does not affect files edited manually or via bash."
586
+ ]
587
+ }, undefined, true, undefined, this)
588
+ }, undefined, false, undefined, this)
589
+ ]
590
+ }, undefined, true, undefined, this),
591
+ showPickList && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
592
+ children: [
593
+ isFileHistoryEnabled ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
594
+ children: "Restore the code and/or conversation to the point before\u2026"
595
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
596
+ children: "Restore and fork the conversation to the point before\u2026"
597
+ }, undefined, false, undefined, this),
598
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
599
+ width: "100%",
600
+ flexDirection: "column",
601
+ children: messageOptions.slice(firstVisibleIndex, firstVisibleIndex + MAX_VISIBLE_MESSAGES).map((msg, visibleOptionIndex) => {
602
+ const optionIndex = firstVisibleIndex + visibleOptionIndex;
603
+ const isSelected = optionIndex === selectedIndex;
604
+ const isCurrent = msg.uuid === currentUUID;
605
+ const metadataLoaded = optionIndex in fileHistoryMetadata;
606
+ const metadata = fileHistoryMetadata[optionIndex];
607
+ const numFilesChanged = metadata?.filesChanged && metadata.filesChanged.length;
608
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
609
+ height: isFileHistoryEnabled ? 3 : 2,
610
+ overflow: "hidden",
611
+ width: "100%",
612
+ flexDirection: "row",
613
+ children: [
614
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
615
+ width: 2,
616
+ minWidth: 2,
617
+ children: isSelected ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
618
+ color: "permission",
619
+ bold: true,
620
+ children: [
621
+ figures_default.pointer,
622
+ " "
623
+ ]
624
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
625
+ children: " "
626
+ }, undefined, false, undefined, this)
627
+ }, undefined, false, undefined, this),
628
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
629
+ flexDirection: "column",
630
+ children: [
631
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
632
+ flexShrink: 1,
633
+ height: 1,
634
+ overflow: "hidden",
635
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(UserMessageOption, {
636
+ userMessage: msg,
637
+ color: isSelected ? "suggestion" : undefined,
638
+ isCurrent,
639
+ paddingRight: 10
640
+ }, undefined, false, undefined, this)
641
+ }, undefined, false, undefined, this),
642
+ isFileHistoryEnabled && metadataLoaded && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
643
+ height: 1,
644
+ flexDirection: "row",
645
+ children: metadata ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
646
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
647
+ dimColor: !isSelected,
648
+ color: "inactive",
649
+ children: numFilesChanged ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
650
+ children: [
651
+ numFilesChanged === 1 && metadata.filesChanged[0] ? `${path.basename(metadata.filesChanged[0])} ` : `${numFilesChanged} files changed `,
652
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(DiffStatsText, {
653
+ diffStats: metadata
654
+ }, undefined, false, undefined, this)
655
+ ]
656
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
657
+ children: "No code changes"
658
+ }, undefined, false, undefined, this)
659
+ }, undefined, false, undefined, this)
660
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
661
+ dimColor: true,
662
+ color: "warning",
663
+ children: [
664
+ figures_default.warning,
665
+ " No code restore"
666
+ ]
667
+ }, undefined, true, undefined, this)
668
+ }, undefined, false, undefined, this)
669
+ ]
670
+ }, undefined, true, undefined, this)
671
+ ]
672
+ }, msg.uuid, true, undefined, this);
673
+ })
674
+ }, undefined, false, undefined, this)
675
+ ]
676
+ }, undefined, true, undefined, this),
677
+ !messageToRestore && /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
678
+ dimColor: true,
679
+ italic: true,
680
+ children: exitState.pending ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
681
+ children: [
682
+ "Press ",
683
+ exitState.keyName,
684
+ " again to exit"
685
+ ]
686
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
687
+ children: [
688
+ !error && hasMessagesToSelect && "Enter to continue \xB7 ",
689
+ "Esc to exit"
690
+ ]
691
+ }, undefined, true, undefined, this)
692
+ }, undefined, false, undefined, this)
693
+ ]
694
+ }, undefined, true, undefined, this)
695
+ ]
696
+ }, undefined, true, undefined, this);
697
+ }
698
+ function getRestoreOptionConversationText(option) {
699
+ switch (option) {
700
+ case "summarize":
701
+ return "Messages after this point will be summarized.";
702
+ case "summarize_up_to":
703
+ return "Preceding messages will be summarized. This and subsequent messages will remain unchanged \u2014 you will stay at the end of the conversation.";
704
+ case "both":
705
+ case "conversation":
706
+ return "The conversation will be forked.";
707
+ case "code":
708
+ case "nevermind":
709
+ return "The conversation will be unchanged.";
710
+ }
711
+ }
712
+ function RestoreOptionDescription({
713
+ selectedRestoreOption,
714
+ canRestoreCode,
715
+ diffStatsForRestore
716
+ }) {
717
+ const showCodeRestore = canRestoreCode && (selectedRestoreOption === "both" || selectedRestoreOption === "code");
718
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
719
+ flexDirection: "column",
720
+ children: [
721
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
722
+ dimColor: true,
723
+ children: getRestoreOptionConversationText(selectedRestoreOption)
724
+ }, undefined, false, undefined, this),
725
+ !isSummarizeOption(selectedRestoreOption) && (showCodeRestore ? /* @__PURE__ */ jsx_dev_runtime.jsxDEV(RestoreCodeConfirmation, {
726
+ diffStatsForRestore
727
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
728
+ dimColor: true,
729
+ children: "The code will be unchanged."
730
+ }, undefined, false, undefined, this))
731
+ ]
732
+ }, undefined, true, undefined, this);
733
+ }
734
+ function RestoreCodeConfirmation({
735
+ diffStatsForRestore
736
+ }) {
737
+ if (diffStatsForRestore === undefined) {
738
+ return;
739
+ }
740
+ if (!diffStatsForRestore.filesChanged || !diffStatsForRestore.filesChanged[0]) {
741
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
742
+ dimColor: true,
743
+ children: "The code has not changed (nothing will be restored)."
744
+ }, undefined, false, undefined, this);
745
+ }
746
+ const numFilesChanged = diffStatsForRestore.filesChanged.length;
747
+ let fileLabel = "";
748
+ if (numFilesChanged === 1) {
749
+ fileLabel = path.basename(diffStatsForRestore.filesChanged[0] || "");
750
+ } else if (numFilesChanged === 2) {
751
+ const file1 = path.basename(diffStatsForRestore.filesChanged[0] || "");
752
+ const file2 = path.basename(diffStatsForRestore.filesChanged[1] || "");
753
+ fileLabel = `${file1} and ${file2}`;
754
+ } else {
755
+ const file1 = path.basename(diffStatsForRestore.filesChanged[0] || "");
756
+ fileLabel = `${file1} and ${diffStatsForRestore.filesChanged.length - 1} other files`;
757
+ }
758
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
759
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
760
+ dimColor: true,
761
+ children: [
762
+ "The code will be restored",
763
+ " ",
764
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(DiffStatsText, {
765
+ diffStats: diffStatsForRestore
766
+ }, undefined, false, undefined, this),
767
+ " in ",
768
+ fileLabel,
769
+ "."
770
+ ]
771
+ }, undefined, true, undefined, this)
772
+ }, undefined, false, undefined, this);
773
+ }
774
+ function DiffStatsText({
775
+ diffStats
776
+ }) {
777
+ if (!diffStats || !diffStats.filesChanged) {
778
+ return;
779
+ }
780
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(jsx_dev_runtime.Fragment, {
781
+ children: [
782
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
783
+ color: "diffAddedWord",
784
+ children: [
785
+ "+",
786
+ diffStats.insertions,
787
+ " "
788
+ ]
789
+ }, undefined, true, undefined, this),
790
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
791
+ color: "diffRemovedWord",
792
+ children: [
793
+ "-",
794
+ diffStats.deletions
795
+ ]
796
+ }, undefined, true, undefined, this)
797
+ ]
798
+ }, undefined, true, undefined, this);
799
+ }
800
+ function UserMessageOption({
801
+ userMessage,
802
+ color,
803
+ dimColor,
804
+ isCurrent,
805
+ paddingRight
806
+ }) {
807
+ const { columns } = useTerminalSize();
808
+ if (isCurrent) {
809
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
810
+ width: "100%",
811
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
812
+ italic: true,
813
+ color,
814
+ dimColor,
815
+ children: "(current)"
816
+ }, undefined, false, undefined, this)
817
+ }, undefined, false, undefined, this);
818
+ }
819
+ const content = userMessage.message.content;
820
+ const lastBlock = typeof content === "string" ? null : content[content.length - 1];
821
+ const rawMessageText = typeof content === "string" ? content.trim() : lastBlock && isTextBlock(lastBlock) ? lastBlock.text.trim() : "(no prompt)";
822
+ const messageText = stripDisplayTags(rawMessageText);
823
+ if (isEmptyMessageText(messageText)) {
824
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
825
+ flexDirection: "row",
826
+ width: "100%",
827
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
828
+ italic: true,
829
+ color,
830
+ dimColor,
831
+ children: "((empty message))"
832
+ }, undefined, false, undefined, this)
833
+ }, undefined, false, undefined, this);
834
+ }
835
+ if (messageText.includes("<bash-input>")) {
836
+ const input = extractTag(messageText, "bash-input");
837
+ if (input) {
838
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
839
+ flexDirection: "row",
840
+ width: "100%",
841
+ children: [
842
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
843
+ color: "bashBorder",
844
+ children: "!"
845
+ }, undefined, false, undefined, this),
846
+ /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
847
+ color,
848
+ dimColor,
849
+ children: [
850
+ " ",
851
+ input
852
+ ]
853
+ }, undefined, true, undefined, this)
854
+ ]
855
+ }, undefined, true, undefined, this);
856
+ }
857
+ }
858
+ if (messageText.includes(`<${COMMAND_MESSAGE_TAG}>`)) {
859
+ const commandMessage = extractTag(messageText, COMMAND_MESSAGE_TAG);
860
+ const args = extractTag(messageText, "command-args");
861
+ const isSkillFormat = extractTag(messageText, "skill-format") === "true";
862
+ if (commandMessage) {
863
+ if (isSkillFormat) {
864
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
865
+ flexDirection: "row",
866
+ width: "100%",
867
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
868
+ color,
869
+ dimColor,
870
+ children: [
871
+ "Skill(",
872
+ commandMessage,
873
+ ")"
874
+ ]
875
+ }, undefined, true, undefined, this)
876
+ }, undefined, false, undefined, this);
877
+ } else {
878
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
879
+ flexDirection: "row",
880
+ width: "100%",
881
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
882
+ color,
883
+ dimColor,
884
+ children: [
885
+ "/",
886
+ commandMessage,
887
+ " ",
888
+ args
889
+ ]
890
+ }, undefined, true, undefined, this)
891
+ }, undefined, false, undefined, this);
892
+ }
893
+ }
894
+ }
895
+ return /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedBox_default, {
896
+ flexDirection: "row",
897
+ width: "100%",
898
+ children: /* @__PURE__ */ jsx_dev_runtime.jsxDEV(ThemedText, {
899
+ color,
900
+ dimColor,
901
+ children: paddingRight ? truncate(messageText, columns - paddingRight, true) : messageText.slice(0, 500).split(`
902
+ `).slice(0, 4).join(`
903
+ `)
904
+ }, undefined, false, undefined, this)
905
+ }, undefined, false, undefined, this);
906
+ }
907
+ function computeDiffStatsBetweenMessages(messages, fromMessageId, toMessageId) {
908
+ const startIndex = messages.findIndex((msg) => msg.uuid === fromMessageId);
909
+ if (startIndex === -1) {
910
+ return;
911
+ }
912
+ let endIndex = toMessageId ? messages.findIndex((msg) => msg.uuid === toMessageId) : messages.length;
913
+ if (endIndex === -1) {
914
+ endIndex = messages.length;
915
+ }
916
+ const filesChanged = [];
917
+ let insertions = 0;
918
+ let deletions = 0;
919
+ for (let i = startIndex + 1;i < endIndex; i++) {
920
+ const msg = messages[i];
921
+ if (!msg || !isToolUseResultMessage(msg)) {
922
+ continue;
923
+ }
924
+ const result = msg.toolUseResult;
925
+ if (!result || !result.filePath || !result.structuredPatch) {
926
+ continue;
927
+ }
928
+ if (!filesChanged.includes(result.filePath)) {
929
+ filesChanged.push(result.filePath);
930
+ }
931
+ try {
932
+ if ("type" in result && result.type === "create") {
933
+ insertions += result.content.split(/\r?\n/).length;
934
+ } else {
935
+ for (const hunk of result.structuredPatch) {
936
+ const additions = count(hunk.lines, (line) => line.startsWith("+"));
937
+ const removals = count(hunk.lines, (line) => line.startsWith("-"));
938
+ insertions += additions;
939
+ deletions += removals;
940
+ }
941
+ }
942
+ } catch {
943
+ continue;
944
+ }
945
+ }
946
+ return {
947
+ filesChanged,
948
+ insertions,
949
+ deletions
950
+ };
951
+ }
952
+ function selectableUserMessagesFilter(message) {
953
+ if (message.type !== "user") {
954
+ return false;
955
+ }
956
+ if (Array.isArray(message.message.content) && message.message.content[0]?.type === "tool_result") {
957
+ return false;
958
+ }
959
+ if (isSyntheticMessage(message)) {
960
+ return false;
961
+ }
962
+ if (message.isMeta) {
963
+ return false;
964
+ }
965
+ if (message.isCompactSummary || message.isVisibleInTranscriptOnly) {
966
+ return false;
967
+ }
968
+ const content = message.message.content;
969
+ const lastBlock = typeof content === "string" ? null : content[content.length - 1];
970
+ const messageText = typeof content === "string" ? content.trim() : lastBlock && isTextBlock(lastBlock) ? lastBlock.text.trim() : "";
971
+ if (messageText.indexOf(`<${LOCAL_COMMAND_STDOUT_TAG}>`) !== -1 || messageText.indexOf(`<${LOCAL_COMMAND_STDERR_TAG}>`) !== -1 || messageText.indexOf(`<${BASH_STDOUT_TAG}>`) !== -1 || messageText.indexOf(`<${BASH_STDERR_TAG}>`) !== -1 || messageText.indexOf(`<${TASK_NOTIFICATION_TAG}>`) !== -1 || messageText.indexOf(`<${TICK_TAG}>`) !== -1 || messageText.indexOf(`<${TEAMMATE_MESSAGE_TAG}`) !== -1) {
972
+ return false;
973
+ }
974
+ return true;
975
+ }
976
+ function messagesAfterAreOnlySynthetic(messages, fromIndex) {
977
+ for (let i = fromIndex + 1;i < messages.length; i++) {
978
+ const msg = messages[i];
979
+ if (!msg)
980
+ continue;
981
+ if (isSyntheticMessage(msg))
982
+ continue;
983
+ if (isToolUseResultMessage(msg))
984
+ continue;
985
+ if (msg.type === "progress")
986
+ continue;
987
+ if (msg.type === "system")
988
+ continue;
989
+ if (msg.type === "attachment")
990
+ continue;
991
+ if (msg.type === "user" && msg.isMeta)
992
+ continue;
993
+ if (msg.type === "assistant") {
994
+ const content = msg.message.content;
995
+ if (Array.isArray(content)) {
996
+ const hasMeaningfulContent = content.some((block) => block.type === "text" && block.text.trim() || block.type === "tool_use");
997
+ if (hasMeaningfulContent)
998
+ return false;
999
+ }
1000
+ continue;
1001
+ }
1002
+ if (msg.type === "user") {
1003
+ return false;
1004
+ }
1005
+ }
1006
+ return true;
1007
+ }
1008
+ var import_react, jsx_dev_runtime, MAX_VISIBLE_MESSAGES = 7;
1009
+ var init_MessageSelector = __esm(() => {
1010
+ init_figures();
1011
+ init_analytics();
1012
+ init_AppState();
1013
+ init_fileHistory();
1014
+ init_log();
1015
+ init_useExitOnCtrlCDWithKeybindings();
1016
+ init_src();
1017
+ init_useKeybinding();
1018
+ init_displayTags();
1019
+ init_messages();
1020
+ init_select();
1021
+ init_Spinner();
1022
+ init_useTerminalSize();
1023
+ init_xml();
1024
+ init_array();
1025
+ init_format();
1026
+ import_react = __toESM(require_react(), 1);
1027
+ jsx_dev_runtime = __toESM(require_jsx_dev_runtime(), 1);
1028
+ });
1029
+
1030
+ // src/utils/cronJitterConfig.ts
1031
+ var exports_cronJitterConfig = {};
1032
+ __export(exports_cronJitterConfig, {
1033
+ getCronJitterConfig: () => getCronJitterConfig
1034
+ });
1035
+ function getCronJitterConfig() {
1036
+ const raw = getFeatureValue_CACHED_WITH_REFRESH("tengu_kairos_cron_config", DEFAULT_CRON_JITTER_CONFIG, JITTER_CONFIG_REFRESH_MS);
1037
+ const parsed = cronJitterConfigSchema().safeParse(raw);
1038
+ return parsed.success ? parsed.data : DEFAULT_CRON_JITTER_CONFIG;
1039
+ }
1040
+ var JITTER_CONFIG_REFRESH_MS, HALF_HOUR_MS, THIRTY_DAYS_MS, cronJitterConfigSchema;
1041
+ var init_cronJitterConfig = __esm(() => {
1042
+ init_v4();
1043
+ init_growthbook();
1044
+ init_cronTasks();
1045
+ init_lazySchema();
1046
+ JITTER_CONFIG_REFRESH_MS = 60 * 1000;
1047
+ HALF_HOUR_MS = 30 * 60 * 1000;
1048
+ THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
1049
+ cronJitterConfigSchema = lazySchema(() => exports_external.object({
1050
+ recurringFrac: exports_external.number().min(0).max(1),
1051
+ recurringCapMs: exports_external.number().int().min(0).max(HALF_HOUR_MS),
1052
+ oneShotMaxMs: exports_external.number().int().min(0).max(HALF_HOUR_MS),
1053
+ oneShotFloorMs: exports_external.number().int().min(0).max(HALF_HOUR_MS),
1054
+ oneShotMinuteMod: exports_external.number().int().min(1).max(60),
1055
+ recurringMaxAgeMs: exports_external.number().int().min(0).max(THIRTY_DAYS_MS).default(DEFAULT_CRON_JITTER_CONFIG.recurringMaxAgeMs)
1056
+ }).refine((c) => c.oneShotFloorMs <= c.oneShotMaxMs));
1057
+ });
1058
+
1059
+ // src/utils/cronTasksLock.ts
1060
+ import { mkdir, readFile, unlink, writeFile } from "fs/promises";
1061
+ import { dirname, join } from "path";
1062
+ function getLockPath(dir) {
1063
+ return join(dir ?? getProjectRoot(), LOCK_FILE_REL);
1064
+ }
1065
+ async function readLock(dir) {
1066
+ let raw;
1067
+ try {
1068
+ raw = await readFile(getLockPath(dir), "utf8");
1069
+ } catch {
1070
+ return;
1071
+ }
1072
+ const result = schedulerLockSchema().safeParse(safeParseJSON(raw, false));
1073
+ return result.success ? result.data : undefined;
1074
+ }
1075
+ async function tryCreateExclusive(lock, dir) {
1076
+ const path2 = getLockPath(dir);
1077
+ const body = jsonStringify(lock);
1078
+ try {
1079
+ await writeFile(path2, body, { flag: "wx" });
1080
+ return true;
1081
+ } catch (e) {
1082
+ const code = getErrnoCode(e);
1083
+ if (code === "EEXIST")
1084
+ return false;
1085
+ if (code === "ENOENT") {
1086
+ await mkdir(dirname(path2), { recursive: true });
1087
+ try {
1088
+ await writeFile(path2, body, { flag: "wx" });
1089
+ return true;
1090
+ } catch (retryErr) {
1091
+ if (getErrnoCode(retryErr) === "EEXIST")
1092
+ return false;
1093
+ throw retryErr;
1094
+ }
1095
+ }
1096
+ throw e;
1097
+ }
1098
+ }
1099
+ function registerLockCleanup(opts) {
1100
+ unregisterCleanup?.();
1101
+ unregisterCleanup = registerCleanup(async () => {
1102
+ await releaseSchedulerLock(opts);
1103
+ });
1104
+ }
1105
+ async function tryAcquireSchedulerLock(opts) {
1106
+ const dir = opts?.dir;
1107
+ const sessionId = opts?.lockIdentity ?? getSessionId();
1108
+ const lock = {
1109
+ sessionId,
1110
+ pid: process.pid,
1111
+ acquiredAt: Date.now()
1112
+ };
1113
+ if (await tryCreateExclusive(lock, dir)) {
1114
+ lastBlockedBy = undefined;
1115
+ registerLockCleanup(opts);
1116
+ logForDebugging(`[ScheduledTasks] acquired scheduler lock (PID ${process.pid})`);
1117
+ return true;
1118
+ }
1119
+ const existing = await readLock(dir);
1120
+ if (existing?.sessionId === sessionId) {
1121
+ if (existing.pid !== process.pid) {
1122
+ await writeFile(getLockPath(dir), jsonStringify(lock));
1123
+ registerLockCleanup(opts);
1124
+ }
1125
+ return true;
1126
+ }
1127
+ if (existing && isProcessRunning(existing.pid)) {
1128
+ if (lastBlockedBy !== existing.sessionId) {
1129
+ lastBlockedBy = existing.sessionId;
1130
+ logForDebugging(`[ScheduledTasks] scheduler lock held by session ${existing.sessionId} (PID ${existing.pid})`);
1131
+ }
1132
+ return false;
1133
+ }
1134
+ if (existing) {
1135
+ logForDebugging(`[ScheduledTasks] recovering stale scheduler lock from PID ${existing.pid}`);
1136
+ }
1137
+ await unlink(getLockPath(dir)).catch(() => {});
1138
+ if (await tryCreateExclusive(lock, dir)) {
1139
+ lastBlockedBy = undefined;
1140
+ registerLockCleanup(opts);
1141
+ return true;
1142
+ }
1143
+ return false;
1144
+ }
1145
+ async function releaseSchedulerLock(opts) {
1146
+ unregisterCleanup?.();
1147
+ unregisterCleanup = undefined;
1148
+ lastBlockedBy = undefined;
1149
+ const dir = opts?.dir;
1150
+ const sessionId = opts?.lockIdentity ?? getSessionId();
1151
+ const existing = await readLock(dir);
1152
+ if (!existing || existing.sessionId !== sessionId)
1153
+ return;
1154
+ try {
1155
+ await unlink(getLockPath(dir));
1156
+ logForDebugging("[ScheduledTasks] released scheduler lock");
1157
+ } catch {}
1158
+ }
1159
+ var LOCK_FILE_REL, schedulerLockSchema, unregisterCleanup, lastBlockedBy;
1160
+ var init_cronTasksLock = __esm(() => {
1161
+ init_v4();
1162
+ init_state();
1163
+ init_cleanupRegistry();
1164
+ init_debug();
1165
+ init_errors();
1166
+ init_genericProcessUtils();
1167
+ init_json();
1168
+ init_lazySchema();
1169
+ init_slowOperations();
1170
+ LOCK_FILE_REL = join(".claude", "scheduled_tasks.lock");
1171
+ schedulerLockSchema = lazySchema(() => exports_external.object({
1172
+ sessionId: exports_external.string(),
1173
+ pid: exports_external.number(),
1174
+ acquiredAt: exports_external.number()
1175
+ }));
1176
+ });
1177
+
1178
+ // src/utils/cronScheduler.ts
1179
+ var exports_cronScheduler = {};
1180
+ __export(exports_cronScheduler, {
1181
+ isRecurringTaskAged: () => isRecurringTaskAged,
1182
+ createCronScheduler: () => createCronScheduler,
1183
+ buildMissedTaskNotification: () => buildMissedTaskNotification
1184
+ });
1185
+ function isRecurringTaskAged(t, nowMs, maxAgeMs) {
1186
+ if (maxAgeMs === 0)
1187
+ return false;
1188
+ return Boolean(t.recurring && !t.permanent && nowMs - t.createdAt >= maxAgeMs);
1189
+ }
1190
+ function createCronScheduler(options) {
1191
+ const {
1192
+ onFire,
1193
+ isLoading,
1194
+ assistantMode = false,
1195
+ onFireTask,
1196
+ onMissed,
1197
+ dir,
1198
+ lockIdentity,
1199
+ getJitterConfig,
1200
+ isKilled,
1201
+ filter
1202
+ } = options;
1203
+ const lockOpts = dir || lockIdentity ? { dir, lockIdentity } : undefined;
1204
+ let tasks = [];
1205
+ const nextFireAt = new Map;
1206
+ const missedAsked = new Set;
1207
+ const inFlight = new Set;
1208
+ let enablePoll = null;
1209
+ let checkTimer = null;
1210
+ let lockProbeTimer = null;
1211
+ let watcher = null;
1212
+ let stopped = false;
1213
+ let isOwner = false;
1214
+ async function load(initial) {
1215
+ const next = await readCronTasks(dir);
1216
+ if (stopped)
1217
+ return;
1218
+ tasks = next;
1219
+ if (!initial)
1220
+ return;
1221
+ const now = Date.now();
1222
+ const missed = findMissedTasks(next, now).filter((t) => !t.recurring && !missedAsked.has(t.id) && (!filter || filter(t)));
1223
+ if (missed.length > 0) {
1224
+ for (const t of missed) {
1225
+ missedAsked.add(t.id);
1226
+ nextFireAt.set(t.id, Infinity);
1227
+ }
1228
+ logEvent("tengu_scheduled_task_missed", {
1229
+ count: missed.length,
1230
+ taskIds: missed.map((t) => t.id).join(",")
1231
+ });
1232
+ if (onMissed) {
1233
+ onMissed(missed);
1234
+ } else {
1235
+ onFire(buildMissedTaskNotification(missed));
1236
+ }
1237
+ removeCronTasks(missed.map((t) => t.id), dir).catch((e) => logForDebugging(`[ScheduledTasks] failed to remove missed tasks: ${e}`));
1238
+ logForDebugging(`[ScheduledTasks] surfaced ${missed.length} missed one-shot task(s)`);
1239
+ }
1240
+ }
1241
+ function check() {
1242
+ if (isKilled?.())
1243
+ return;
1244
+ if (isLoading() && !assistantMode)
1245
+ return;
1246
+ const now = Date.now();
1247
+ const seen = new Set;
1248
+ const firedFileRecurring = [];
1249
+ const jitterCfg = getJitterConfig?.() ?? DEFAULT_CRON_JITTER_CONFIG;
1250
+ function process2(t, isSession) {
1251
+ if (filter && !filter(t))
1252
+ return;
1253
+ seen.add(t.id);
1254
+ if (inFlight.has(t.id))
1255
+ return;
1256
+ let next = nextFireAt.get(t.id);
1257
+ if (next === undefined) {
1258
+ next = t.recurring ? jitteredNextCronRunMs(t.cron, t.lastFiredAt ?? t.createdAt, t.id, jitterCfg) ?? Infinity : oneShotJitteredNextCronRunMs(t.cron, t.createdAt, t.id, jitterCfg) ?? Infinity;
1259
+ nextFireAt.set(t.id, next);
1260
+ logForDebugging(`[ScheduledTasks] scheduled ${t.id} for ${next === Infinity ? "never" : new Date(next).toISOString()}`);
1261
+ }
1262
+ if (now < next)
1263
+ return;
1264
+ logForDebugging(`[ScheduledTasks] firing ${t.id}${t.recurring ? " (recurring)" : ""}`);
1265
+ logEvent("tengu_scheduled_task_fire", {
1266
+ recurring: t.recurring ?? false,
1267
+ taskId: t.id
1268
+ });
1269
+ if (onFireTask) {
1270
+ onFireTask(t);
1271
+ } else {
1272
+ onFire(t.prompt);
1273
+ }
1274
+ const aged = isRecurringTaskAged(t, now, jitterCfg.recurringMaxAgeMs);
1275
+ if (aged) {
1276
+ const ageHours = Math.floor((now - t.createdAt) / 1000 / 60 / 60);
1277
+ logForDebugging(`[ScheduledTasks] recurring task ${t.id} aged out (${ageHours}h since creation), deleting after final fire`);
1278
+ logEvent("tengu_scheduled_task_expired", {
1279
+ taskId: t.id,
1280
+ ageHours
1281
+ });
1282
+ }
1283
+ if (t.recurring && !aged) {
1284
+ const newNext = jitteredNextCronRunMs(t.cron, now, t.id, jitterCfg) ?? Infinity;
1285
+ nextFireAt.set(t.id, newNext);
1286
+ if (!isSession)
1287
+ firedFileRecurring.push(t.id);
1288
+ } else if (isSession) {
1289
+ removeSessionCronTasks([t.id]);
1290
+ nextFireAt.delete(t.id);
1291
+ } else {
1292
+ inFlight.add(t.id);
1293
+ removeCronTasks([t.id], dir).catch((e) => logForDebugging(`[ScheduledTasks] failed to remove task ${t.id}: ${e}`)).finally(() => inFlight.delete(t.id));
1294
+ nextFireAt.delete(t.id);
1295
+ }
1296
+ }
1297
+ if (isOwner) {
1298
+ for (const t of tasks)
1299
+ process2(t, false);
1300
+ if (firedFileRecurring.length > 0) {
1301
+ for (const id of firedFileRecurring)
1302
+ inFlight.add(id);
1303
+ markCronTasksFired(firedFileRecurring, now, dir).catch((e) => logForDebugging(`[ScheduledTasks] failed to persist lastFiredAt: ${e}`)).finally(() => {
1304
+ for (const id of firedFileRecurring)
1305
+ inFlight.delete(id);
1306
+ });
1307
+ }
1308
+ }
1309
+ if (dir === undefined) {
1310
+ for (const t of getSessionCronTasks())
1311
+ process2(t, true);
1312
+ }
1313
+ if (seen.size === 0) {
1314
+ nextFireAt.clear();
1315
+ return;
1316
+ }
1317
+ for (const id of nextFireAt.keys()) {
1318
+ if (!seen.has(id))
1319
+ nextFireAt.delete(id);
1320
+ }
1321
+ }
1322
+ async function enable() {
1323
+ if (stopped)
1324
+ return;
1325
+ if (enablePoll) {
1326
+ clearInterval(enablePoll);
1327
+ enablePoll = null;
1328
+ }
1329
+ const { default: chokidar } = await import("./chunk-eqp1rfft.js");
1330
+ if (stopped)
1331
+ return;
1332
+ isOwner = await tryAcquireSchedulerLock(lockOpts).catch(() => false);
1333
+ if (stopped) {
1334
+ if (isOwner) {
1335
+ isOwner = false;
1336
+ releaseSchedulerLock(lockOpts);
1337
+ }
1338
+ return;
1339
+ }
1340
+ if (!isOwner) {
1341
+ lockProbeTimer = setInterval(() => {
1342
+ tryAcquireSchedulerLock(lockOpts).then((owned) => {
1343
+ if (stopped) {
1344
+ if (owned)
1345
+ releaseSchedulerLock(lockOpts);
1346
+ return;
1347
+ }
1348
+ if (owned) {
1349
+ isOwner = true;
1350
+ if (lockProbeTimer) {
1351
+ clearInterval(lockProbeTimer);
1352
+ lockProbeTimer = null;
1353
+ }
1354
+ }
1355
+ }).catch((e) => logForDebugging(String(e), { level: "error" }));
1356
+ }, LOCK_PROBE_INTERVAL_MS);
1357
+ lockProbeTimer.unref?.();
1358
+ }
1359
+ load(true);
1360
+ const path2 = getCronFilePath(dir);
1361
+ watcher = chokidar.watch(path2, {
1362
+ persistent: false,
1363
+ ignoreInitial: true,
1364
+ awaitWriteFinish: { stabilityThreshold: FILE_STABILITY_MS },
1365
+ ignorePermissionErrors: true
1366
+ });
1367
+ watcher.on("add", () => void load(false));
1368
+ watcher.on("change", () => void load(false));
1369
+ watcher.on("unlink", () => {
1370
+ if (!stopped) {
1371
+ tasks = [];
1372
+ nextFireAt.clear();
1373
+ }
1374
+ });
1375
+ checkTimer = setInterval(check, CHECK_INTERVAL_MS);
1376
+ checkTimer.unref?.();
1377
+ }
1378
+ return {
1379
+ start() {
1380
+ stopped = false;
1381
+ if (dir !== undefined) {
1382
+ logForDebugging(`[ScheduledTasks] scheduler start() \u2014 dir=${dir}, hasTasks=${hasCronTasksSync(dir)}`);
1383
+ enable();
1384
+ return;
1385
+ }
1386
+ logForDebugging(`[ScheduledTasks] scheduler start() \u2014 enabled=${getScheduledTasksEnabled()}, hasTasks=${hasCronTasksSync()}`);
1387
+ if (!getScheduledTasksEnabled() && (assistantMode || hasCronTasksSync())) {
1388
+ setScheduledTasksEnabled(true);
1389
+ }
1390
+ if (getScheduledTasksEnabled()) {
1391
+ enable();
1392
+ return;
1393
+ }
1394
+ enablePoll = setInterval((en) => {
1395
+ if (getScheduledTasksEnabled())
1396
+ en();
1397
+ }, CHECK_INTERVAL_MS, enable);
1398
+ enablePoll.unref?.();
1399
+ },
1400
+ stop() {
1401
+ stopped = true;
1402
+ if (enablePoll) {
1403
+ clearInterval(enablePoll);
1404
+ enablePoll = null;
1405
+ }
1406
+ if (checkTimer) {
1407
+ clearInterval(checkTimer);
1408
+ checkTimer = null;
1409
+ }
1410
+ if (lockProbeTimer) {
1411
+ clearInterval(lockProbeTimer);
1412
+ lockProbeTimer = null;
1413
+ }
1414
+ watcher?.close();
1415
+ watcher = null;
1416
+ if (isOwner) {
1417
+ isOwner = false;
1418
+ releaseSchedulerLock(lockOpts);
1419
+ }
1420
+ },
1421
+ getNextFireTime() {
1422
+ let min = Infinity;
1423
+ for (const t of nextFireAt.values()) {
1424
+ if (t < min)
1425
+ min = t;
1426
+ }
1427
+ return min === Infinity ? null : min;
1428
+ }
1429
+ };
1430
+ }
1431
+ function buildMissedTaskNotification(missed) {
1432
+ const plural = missed.length > 1;
1433
+ const header = `The following one-shot scheduled task${plural ? "s were" : " was"} missed while Claude was not running. ${plural ? "They have" : "It has"} already been removed from .claude/scheduled_tasks.json.
1434
+
1435
+ Do NOT execute ${plural ? "these prompts" : "this prompt"} yet. First use the AskUserQuestion tool to ask whether to run ${plural ? "each one" : "it"} now. Only execute if the user confirms.`;
1436
+ const blocks = missed.map((t) => {
1437
+ const meta = `[${cronToHuman(t.cron)}, created ${new Date(t.createdAt).toLocaleString()}]`;
1438
+ const longestRun = (t.prompt.match(/`+/g) ?? []).reduce((max, run) => Math.max(max, run.length), 0);
1439
+ const fence = "`".repeat(Math.max(3, longestRun + 1));
1440
+ return `${meta}
1441
+ ${fence}
1442
+ ${t.prompt}
1443
+ ${fence}`;
1444
+ });
1445
+ return `${header}
1446
+
1447
+ ${blocks.join(`
1448
+
1449
+ `)}`;
1450
+ }
1451
+ var CHECK_INTERVAL_MS = 1000, FILE_STABILITY_MS = 300, LOCK_PROBE_INTERVAL_MS = 5000;
1452
+ var init_cronScheduler = __esm(() => {
1453
+ init_state();
1454
+ init_analytics();
1455
+ init_cron();
1456
+ init_cronTasks();
1457
+ init_cronTasksLock();
1458
+ init_debug();
1459
+ });
1460
+
1461
+ // src/utils/permissions/PermissionPromptToolResultSchema.ts
1462
+ init_v4();
1463
+ init_debug();
1464
+ init_lazySchema();
1465
+ init_PermissionUpdate();
1466
+ init_PermissionUpdateSchema();
1467
+ var inputSchema = lazySchema(() => v4_default.object({
1468
+ tool_name: v4_default.string().describe("The name of the tool requesting permission"),
1469
+ input: v4_default.record(v4_default.string(), v4_default.unknown()).describe("The input for the tool"),
1470
+ tool_use_id: v4_default.string().optional().describe("The unique tool use request ID")
1471
+ }));
1472
+ var decisionClassificationField = lazySchema(() => v4_default.enum(["user_temporary", "user_permanent", "user_reject"]).optional().catch(undefined));
1473
+ var PermissionAllowResultSchema = lazySchema(() => v4_default.object({
1474
+ behavior: v4_default.literal("allow"),
1475
+ updatedInput: v4_default.record(v4_default.string(), v4_default.unknown()),
1476
+ updatedPermissions: v4_default.array(permissionUpdateSchema()).optional().catch((ctx) => {
1477
+ logForDebugging(`Malformed updatedPermissions from SDK host ignored: ${ctx.error.issues[0]?.message ?? "unknown"}`, { level: "warn" });
1478
+ return;
1479
+ }),
1480
+ toolUseID: v4_default.string().optional(),
1481
+ decisionClassification: decisionClassificationField()
1482
+ }));
1483
+ var PermissionDenyResultSchema = lazySchema(() => v4_default.object({
1484
+ behavior: v4_default.literal("deny"),
1485
+ message: v4_default.string(),
1486
+ interrupt: v4_default.boolean().optional(),
1487
+ toolUseID: v4_default.string().optional(),
1488
+ decisionClassification: decisionClassificationField()
1489
+ }));
1490
+ var outputSchema = lazySchema(() => v4_default.union([PermissionAllowResultSchema(), PermissionDenyResultSchema()]));
1491
+ function permissionPromptToolResultToPermissionDecision(result, tool, input, toolUseContext) {
1492
+ const decisionReason = {
1493
+ type: "permissionPromptTool",
1494
+ permissionPromptToolName: tool.name,
1495
+ toolResult: result
1496
+ };
1497
+ if (result.behavior === "allow") {
1498
+ const updatedPermissions = result.updatedPermissions;
1499
+ if (updatedPermissions) {
1500
+ toolUseContext.setAppState((prev) => ({
1501
+ ...prev,
1502
+ toolPermissionContext: applyPermissionUpdates(prev.toolPermissionContext, updatedPermissions)
1503
+ }));
1504
+ persistPermissionUpdates(updatedPermissions);
1505
+ }
1506
+ const updatedInput = Object.keys(result.updatedInput).length > 0 ? result.updatedInput : input;
1507
+ return {
1508
+ ...result,
1509
+ updatedInput,
1510
+ decisionReason
1511
+ };
1512
+ } else if (result.behavior === "deny" && result.interrupt) {
1513
+ logForDebugging(`SDK permission prompt deny+interrupt: tool=${tool.name} message=${result.message}`);
1514
+ toolUseContext.abortController.abort();
1515
+ }
1516
+ return {
1517
+ ...result,
1518
+ decisionReason
1519
+ };
1520
+ }
1521
+
1522
+ // src/cli/structuredIO.ts
1523
+ import { randomUUID as randomUUID2 } from "crypto";
1524
+
1525
+ // src/entrypoints/sdk/controlSchemas.ts
1526
+ init_v4();
1527
+ init_lazySchema();
1528
+ init_coreSchemas();
1529
+ var JSONRPCMessagePlaceholder = lazySchema(() => exports_external.unknown());
1530
+ var SDKHookCallbackMatcherSchema = lazySchema(() => exports_external.object({
1531
+ matcher: exports_external.string().optional(),
1532
+ hookCallbackIds: exports_external.array(exports_external.string()),
1533
+ timeout: exports_external.number().optional()
1534
+ }).describe("Configuration for matching and routing hook callbacks."));
1535
+ var SDKControlInitializeRequestSchema = lazySchema(() => exports_external.object({
1536
+ subtype: exports_external.literal("initialize"),
1537
+ hooks: exports_external.record(HookEventSchema(), exports_external.array(SDKHookCallbackMatcherSchema())).optional(),
1538
+ sdkMcpServers: exports_external.array(exports_external.string()).optional(),
1539
+ jsonSchema: exports_external.record(exports_external.string(), exports_external.unknown()).optional(),
1540
+ systemPrompt: exports_external.string().optional(),
1541
+ appendSystemPrompt: exports_external.string().optional(),
1542
+ agents: exports_external.record(exports_external.string(), AgentDefinitionSchema()).optional(),
1543
+ promptSuggestions: exports_external.boolean().optional(),
1544
+ agentProgressSummaries: exports_external.boolean().optional()
1545
+ }).describe("Initializes the SDK session with hooks, MCP servers, and agent configuration."));
1546
+ var SDKControlInitializeResponseSchema = lazySchema(() => exports_external.object({
1547
+ commands: exports_external.array(SlashCommandSchema()),
1548
+ agents: exports_external.array(AgentInfoSchema()),
1549
+ output_style: exports_external.string(),
1550
+ available_output_styles: exports_external.array(exports_external.string()),
1551
+ models: exports_external.array(ModelInfoSchema()),
1552
+ account: AccountInfoSchema(),
1553
+ pid: exports_external.number().optional().describe("@internal CLI process PID for tmux socket isolation"),
1554
+ fast_mode_state: FastModeStateSchema().optional()
1555
+ }).describe("Response from session initialization with available commands, models, and account info."));
1556
+ var SDKControlInterruptRequestSchema = lazySchema(() => exports_external.object({
1557
+ subtype: exports_external.literal("interrupt")
1558
+ }).describe("Interrupts the currently running conversation turn."));
1559
+ var SDKControlPermissionRequestSchema = lazySchema(() => exports_external.object({
1560
+ subtype: exports_external.literal("can_use_tool"),
1561
+ tool_name: exports_external.string(),
1562
+ input: exports_external.record(exports_external.string(), exports_external.unknown()),
1563
+ permission_suggestions: exports_external.array(PermissionUpdateSchema()).optional(),
1564
+ blocked_path: exports_external.string().optional(),
1565
+ decision_reason: exports_external.string().optional(),
1566
+ title: exports_external.string().optional(),
1567
+ display_name: exports_external.string().optional(),
1568
+ tool_use_id: exports_external.string(),
1569
+ agent_id: exports_external.string().optional(),
1570
+ description: exports_external.string().optional()
1571
+ }).describe("Requests permission to use a tool with the given input."));
1572
+ var SDKControlSetPermissionModeRequestSchema = lazySchema(() => exports_external.object({
1573
+ subtype: exports_external.literal("set_permission_mode"),
1574
+ mode: PermissionModeSchema(),
1575
+ ultraplan: exports_external.boolean().optional().describe("@internal CCR ultraplan session marker.")
1576
+ }).describe("Sets the permission mode for tool execution handling."));
1577
+ var SDKControlSetModelRequestSchema = lazySchema(() => exports_external.object({
1578
+ subtype: exports_external.literal("set_model"),
1579
+ model: exports_external.string().optional()
1580
+ }).describe("Sets the model to use for subsequent conversation turns."));
1581
+ var SDKControlSetMaxThinkingTokensRequestSchema = lazySchema(() => exports_external.object({
1582
+ subtype: exports_external.literal("set_max_thinking_tokens"),
1583
+ max_thinking_tokens: exports_external.number().nullable()
1584
+ }).describe("Sets the maximum number of thinking tokens for extended thinking."));
1585
+ var SDKControlMcpStatusRequestSchema = lazySchema(() => exports_external.object({
1586
+ subtype: exports_external.literal("mcp_status")
1587
+ }).describe("Requests the current status of all MCP server connections."));
1588
+ var SDKControlMcpStatusResponseSchema = lazySchema(() => exports_external.object({
1589
+ mcpServers: exports_external.array(McpServerStatusSchema())
1590
+ }).describe("Response containing the current status of all MCP server connections."));
1591
+ var SDKControlGetContextUsageRequestSchema = lazySchema(() => exports_external.object({
1592
+ subtype: exports_external.literal("get_context_usage")
1593
+ }).describe("Requests a breakdown of current context window usage by category."));
1594
+ var ContextCategorySchema = lazySchema(() => exports_external.object({
1595
+ name: exports_external.string(),
1596
+ tokens: exports_external.number(),
1597
+ color: exports_external.string(),
1598
+ isDeferred: exports_external.boolean().optional()
1599
+ }));
1600
+ var ContextGridSquareSchema = lazySchema(() => exports_external.object({
1601
+ color: exports_external.string(),
1602
+ isFilled: exports_external.boolean(),
1603
+ categoryName: exports_external.string(),
1604
+ tokens: exports_external.number(),
1605
+ percentage: exports_external.number(),
1606
+ squareFullness: exports_external.number()
1607
+ }));
1608
+ var SDKControlGetContextUsageResponseSchema = lazySchema(() => exports_external.object({
1609
+ categories: exports_external.array(ContextCategorySchema()),
1610
+ totalTokens: exports_external.number(),
1611
+ maxTokens: exports_external.number(),
1612
+ rawMaxTokens: exports_external.number(),
1613
+ percentage: exports_external.number(),
1614
+ gridRows: exports_external.array(exports_external.array(ContextGridSquareSchema())),
1615
+ model: exports_external.string(),
1616
+ memoryFiles: exports_external.array(exports_external.object({
1617
+ path: exports_external.string(),
1618
+ type: exports_external.string(),
1619
+ tokens: exports_external.number()
1620
+ })),
1621
+ mcpTools: exports_external.array(exports_external.object({
1622
+ name: exports_external.string(),
1623
+ serverName: exports_external.string(),
1624
+ tokens: exports_external.number(),
1625
+ isLoaded: exports_external.boolean().optional()
1626
+ })),
1627
+ deferredBuiltinTools: exports_external.array(exports_external.object({
1628
+ name: exports_external.string(),
1629
+ tokens: exports_external.number(),
1630
+ isLoaded: exports_external.boolean()
1631
+ })).optional(),
1632
+ systemTools: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() })).optional(),
1633
+ systemPromptSections: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() })).optional(),
1634
+ agents: exports_external.array(exports_external.object({
1635
+ agentType: exports_external.string(),
1636
+ source: exports_external.string(),
1637
+ tokens: exports_external.number()
1638
+ })),
1639
+ slashCommands: exports_external.object({
1640
+ totalCommands: exports_external.number(),
1641
+ includedCommands: exports_external.number(),
1642
+ tokens: exports_external.number()
1643
+ }).optional(),
1644
+ skills: exports_external.object({
1645
+ totalSkills: exports_external.number(),
1646
+ includedSkills: exports_external.number(),
1647
+ tokens: exports_external.number(),
1648
+ skillFrontmatter: exports_external.array(exports_external.object({
1649
+ name: exports_external.string(),
1650
+ source: exports_external.string(),
1651
+ tokens: exports_external.number()
1652
+ }))
1653
+ }).optional(),
1654
+ autoCompactThreshold: exports_external.number().optional(),
1655
+ isAutoCompactEnabled: exports_external.boolean(),
1656
+ messageBreakdown: exports_external.object({
1657
+ toolCallTokens: exports_external.number(),
1658
+ toolResultTokens: exports_external.number(),
1659
+ attachmentTokens: exports_external.number(),
1660
+ assistantMessageTokens: exports_external.number(),
1661
+ userMessageTokens: exports_external.number(),
1662
+ toolCallsByType: exports_external.array(exports_external.object({
1663
+ name: exports_external.string(),
1664
+ callTokens: exports_external.number(),
1665
+ resultTokens: exports_external.number()
1666
+ })),
1667
+ attachmentsByType: exports_external.array(exports_external.object({ name: exports_external.string(), tokens: exports_external.number() }))
1668
+ }).optional(),
1669
+ apiUsage: exports_external.object({
1670
+ input_tokens: exports_external.number(),
1671
+ output_tokens: exports_external.number(),
1672
+ cache_creation_input_tokens: exports_external.number(),
1673
+ cache_read_input_tokens: exports_external.number()
1674
+ }).nullable()
1675
+ }).describe("Breakdown of current context window usage by category (system prompt, tools, messages, etc.)."));
1676
+ var SDKControlRewindFilesRequestSchema = lazySchema(() => exports_external.object({
1677
+ subtype: exports_external.literal("rewind_files"),
1678
+ user_message_id: exports_external.string(),
1679
+ dry_run: exports_external.boolean().optional()
1680
+ }).describe("Rewinds file changes made since a specific user message."));
1681
+ var SDKControlRewindFilesResponseSchema = lazySchema(() => exports_external.object({
1682
+ canRewind: exports_external.boolean(),
1683
+ error: exports_external.string().optional(),
1684
+ filesChanged: exports_external.array(exports_external.string()).optional(),
1685
+ insertions: exports_external.number().optional(),
1686
+ deletions: exports_external.number().optional()
1687
+ }).describe("Result of a rewindFiles operation."));
1688
+ var SDKControlCancelAsyncMessageRequestSchema = lazySchema(() => exports_external.object({
1689
+ subtype: exports_external.literal("cancel_async_message"),
1690
+ message_uuid: exports_external.string()
1691
+ }).describe("Drops a pending async user message from the command queue by uuid. No-op if already dequeued for execution."));
1692
+ var SDKControlCancelAsyncMessageResponseSchema = lazySchema(() => exports_external.object({
1693
+ cancelled: exports_external.boolean()
1694
+ }).describe("Result of a cancel_async_message operation. cancelled=false means the message was not in the queue (already dequeued or never enqueued)."));
1695
+ var SDKControlSeedReadStateRequestSchema = lazySchema(() => exports_external.object({
1696
+ subtype: exports_external.literal("seed_read_state"),
1697
+ path: exports_external.string(),
1698
+ mtime: exports_external.number()
1699
+ }).describe("Seeds the readFileState cache with a path+mtime entry. Use when a prior Read was removed from context (e.g. by snip) so Edit validation would fail despite the client having observed the Read. The mtime lets the CLI detect if the file changed since the seeded Read \u2014 same staleness check as the normal path."));
1700
+ var SDKHookCallbackRequestSchema = lazySchema(() => exports_external.object({
1701
+ subtype: exports_external.literal("hook_callback"),
1702
+ callback_id: exports_external.string(),
1703
+ input: HookInputSchema(),
1704
+ tool_use_id: exports_external.string().optional()
1705
+ }).describe("Delivers a hook callback with its input data."));
1706
+ var SDKControlMcpMessageRequestSchema = lazySchema(() => exports_external.object({
1707
+ subtype: exports_external.literal("mcp_message"),
1708
+ server_name: exports_external.string(),
1709
+ message: JSONRPCMessagePlaceholder()
1710
+ }).describe("Sends a JSON-RPC message to a specific MCP server."));
1711
+ var SDKControlMcpSetServersRequestSchema = lazySchema(() => exports_external.object({
1712
+ subtype: exports_external.literal("mcp_set_servers"),
1713
+ servers: exports_external.record(exports_external.string(), McpServerConfigForProcessTransportSchema())
1714
+ }).describe("Replaces the set of dynamically managed MCP servers."));
1715
+ var SDKControlMcpSetServersResponseSchema = lazySchema(() => exports_external.object({
1716
+ added: exports_external.array(exports_external.string()),
1717
+ removed: exports_external.array(exports_external.string()),
1718
+ errors: exports_external.record(exports_external.string(), exports_external.string())
1719
+ }).describe("Result of replacing the set of dynamically managed MCP servers."));
1720
+ var SDKControlReloadPluginsRequestSchema = lazySchema(() => exports_external.object({
1721
+ subtype: exports_external.literal("reload_plugins")
1722
+ }).describe("Reloads plugins from disk and returns the refreshed session components."));
1723
+ var SDKControlReloadPluginsResponseSchema = lazySchema(() => exports_external.object({
1724
+ commands: exports_external.array(SlashCommandSchema()),
1725
+ agents: exports_external.array(AgentInfoSchema()),
1726
+ plugins: exports_external.array(exports_external.object({
1727
+ name: exports_external.string(),
1728
+ path: exports_external.string(),
1729
+ source: exports_external.string().optional()
1730
+ })),
1731
+ mcpServers: exports_external.array(McpServerStatusSchema()),
1732
+ error_count: exports_external.number()
1733
+ }).describe("Refreshed commands, agents, plugins, and MCP server status after reload."));
1734
+ var SDKControlMcpReconnectRequestSchema = lazySchema(() => exports_external.object({
1735
+ subtype: exports_external.literal("mcp_reconnect"),
1736
+ serverName: exports_external.string()
1737
+ }).describe("Reconnects a disconnected or failed MCP server."));
1738
+ var SDKControlMcpToggleRequestSchema = lazySchema(() => exports_external.object({
1739
+ subtype: exports_external.literal("mcp_toggle"),
1740
+ serverName: exports_external.string(),
1741
+ enabled: exports_external.boolean()
1742
+ }).describe("Enables or disables an MCP server."));
1743
+ var SDKControlStopTaskRequestSchema = lazySchema(() => exports_external.object({
1744
+ subtype: exports_external.literal("stop_task"),
1745
+ task_id: exports_external.string()
1746
+ }).describe("Stops a running task."));
1747
+ var SDKControlApplyFlagSettingsRequestSchema = lazySchema(() => exports_external.object({
1748
+ subtype: exports_external.literal("apply_flag_settings"),
1749
+ settings: exports_external.record(exports_external.string(), exports_external.unknown())
1750
+ }).describe("Merges the provided settings into the flag settings layer, updating the active configuration."));
1751
+ var SDKControlGetSettingsRequestSchema = lazySchema(() => exports_external.object({
1752
+ subtype: exports_external.literal("get_settings")
1753
+ }).describe("Returns the effective merged settings and the raw per-source settings."));
1754
+ var SDKControlGetSettingsResponseSchema = lazySchema(() => exports_external.object({
1755
+ effective: exports_external.record(exports_external.string(), exports_external.unknown()),
1756
+ sources: exports_external.array(exports_external.object({
1757
+ source: exports_external.enum([
1758
+ "userSettings",
1759
+ "projectSettings",
1760
+ "localSettings",
1761
+ "flagSettings",
1762
+ "policySettings"
1763
+ ]),
1764
+ settings: exports_external.record(exports_external.string(), exports_external.unknown())
1765
+ })).describe("Ordered low-to-high priority \u2014 later entries override earlier ones."),
1766
+ applied: exports_external.object({
1767
+ model: exports_external.string(),
1768
+ effort: exports_external.enum(["low", "medium", "high", "max"]).nullable()
1769
+ }).optional().describe("Runtime-resolved values after env overrides, session state, and model-specific defaults are applied. Unlike `effective` (disk merge), these reflect what will actually be sent to the API.")
1770
+ }).describe("Effective merged settings plus raw per-source settings in merge order."));
1771
+ var SDKControlElicitationRequestSchema = lazySchema(() => exports_external.object({
1772
+ subtype: exports_external.literal("elicitation"),
1773
+ mcp_server_name: exports_external.string(),
1774
+ message: exports_external.string(),
1775
+ mode: exports_external.enum(["form", "url"]).optional(),
1776
+ url: exports_external.string().optional(),
1777
+ elicitation_id: exports_external.string().optional(),
1778
+ requested_schema: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
1779
+ }).describe("Requests the SDK consumer to handle an MCP elicitation (user input request)."));
1780
+ var SDKControlElicitationResponseSchema = lazySchema(() => exports_external.object({
1781
+ action: exports_external.enum(["accept", "decline", "cancel"]),
1782
+ content: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
1783
+ }).describe("Response from the SDK consumer for an elicitation request."));
1784
+ var SDKControlRequestInnerSchema = lazySchema(() => exports_external.union([
1785
+ SDKControlInterruptRequestSchema(),
1786
+ SDKControlPermissionRequestSchema(),
1787
+ SDKControlInitializeRequestSchema(),
1788
+ SDKControlSetPermissionModeRequestSchema(),
1789
+ SDKControlSetModelRequestSchema(),
1790
+ SDKControlSetMaxThinkingTokensRequestSchema(),
1791
+ SDKControlMcpStatusRequestSchema(),
1792
+ SDKControlGetContextUsageRequestSchema(),
1793
+ SDKHookCallbackRequestSchema(),
1794
+ SDKControlMcpMessageRequestSchema(),
1795
+ SDKControlRewindFilesRequestSchema(),
1796
+ SDKControlCancelAsyncMessageRequestSchema(),
1797
+ SDKControlSeedReadStateRequestSchema(),
1798
+ SDKControlMcpSetServersRequestSchema(),
1799
+ SDKControlReloadPluginsRequestSchema(),
1800
+ SDKControlMcpReconnectRequestSchema(),
1801
+ SDKControlMcpToggleRequestSchema(),
1802
+ SDKControlStopTaskRequestSchema(),
1803
+ SDKControlApplyFlagSettingsRequestSchema(),
1804
+ SDKControlGetSettingsRequestSchema(),
1805
+ SDKControlElicitationRequestSchema()
1806
+ ]));
1807
+ var SDKControlRequestSchema = lazySchema(() => exports_external.object({
1808
+ type: exports_external.literal("control_request"),
1809
+ request_id: exports_external.string(),
1810
+ request: SDKControlRequestInnerSchema()
1811
+ }));
1812
+ var ControlResponseSchema = lazySchema(() => exports_external.object({
1813
+ subtype: exports_external.literal("success"),
1814
+ request_id: exports_external.string(),
1815
+ response: exports_external.record(exports_external.string(), exports_external.unknown()).optional()
1816
+ }));
1817
+ var ControlErrorResponseSchema = lazySchema(() => exports_external.object({
1818
+ subtype: exports_external.literal("error"),
1819
+ request_id: exports_external.string(),
1820
+ error: exports_external.string(),
1821
+ pending_permission_requests: exports_external.array(exports_external.lazy(() => SDKControlRequestSchema())).optional()
1822
+ }));
1823
+ var SDKControlResponseSchema = lazySchema(() => exports_external.object({
1824
+ type: exports_external.literal("control_response"),
1825
+ response: exports_external.union([ControlResponseSchema(), ControlErrorResponseSchema()])
1826
+ }));
1827
+ var SDKControlCancelRequestSchema = lazySchema(() => exports_external.object({
1828
+ type: exports_external.literal("control_cancel_request"),
1829
+ request_id: exports_external.string()
1830
+ }).describe("Cancels a currently open control request."));
1831
+ var SDKKeepAliveMessageSchema = lazySchema(() => exports_external.object({
1832
+ type: exports_external.literal("keep_alive")
1833
+ }).describe("Keep-alive message to maintain WebSocket connection."));
1834
+ var SDKUpdateEnvironmentVariablesMessageSchema = lazySchema(() => exports_external.object({
1835
+ type: exports_external.literal("update_environment_variables"),
1836
+ variables: exports_external.record(exports_external.string(), exports_external.string())
1837
+ }).describe("Updates environment variables at runtime."));
1838
+ var StdoutMessageSchema = lazySchema(() => exports_external.union([
1839
+ SDKMessageSchema(),
1840
+ SDKStreamlinedTextMessageSchema(),
1841
+ SDKStreamlinedToolUseSummaryMessageSchema(),
1842
+ SDKPostTurnSummaryMessageSchema(),
1843
+ SDKControlResponseSchema(),
1844
+ SDKControlRequestSchema(),
1845
+ SDKControlCancelRequestSchema(),
1846
+ SDKKeepAliveMessageSchema()
1847
+ ]));
1848
+ var StdinMessageSchema = lazySchema(() => exports_external.union([
1849
+ SDKUserMessageSchema(),
1850
+ SDKControlRequestSchema(),
1851
+ SDKControlResponseSchema(),
1852
+ SDKKeepAliveMessageSchema(),
1853
+ SDKUpdateEnvironmentVariablesMessageSchema()
1854
+ ]));
1855
+
1856
+ // src/cli/structuredIO.ts
1857
+ init_hooks();
1858
+ init_debug();
1859
+ init_diagLogs();
1860
+ init_errors();
1861
+ init_permissions();
1862
+ init_process();
1863
+ init_slowOperations();
1864
+ init_v4();
1865
+ init_commandLifecycle();
1866
+
1867
+ // src/utils/controlMessageCompat.ts
1868
+ function normalizeControlMessageKeys(obj) {
1869
+ if (obj === null || typeof obj !== "object")
1870
+ return obj;
1871
+ const record = obj;
1872
+ if ("requestId" in record && !("request_id" in record)) {
1873
+ record.request_id = record.requestId;
1874
+ delete record.requestId;
1875
+ }
1876
+ if ("response" in record && record.response !== null && typeof record.response === "object") {
1877
+ const response = record.response;
1878
+ if ("requestId" in response && !("request_id" in response)) {
1879
+ response.request_id = response.requestId;
1880
+ delete response.requestId;
1881
+ }
1882
+ }
1883
+ return obj;
1884
+ }
1885
+
1886
+ // src/cli/structuredIO.ts
1887
+ init_hooks2();
1888
+ init_PermissionUpdate();
1889
+ init_slowOperations();
1890
+ init_stream();
1891
+
1892
+ // src/cli/ndjsonSafeStringify.ts
1893
+ init_slowOperations();
1894
+ var JS_LINE_TERMINATORS = /\u2028|\u2029/g;
1895
+ function escapeJsLineTerminators(json) {
1896
+ return json.replace(JS_LINE_TERMINATORS, (c) => c === "\u2028" ? "\\u2028" : "\\u2029");
1897
+ }
1898
+ function ndjsonSafeStringify(value) {
1899
+ return escapeJsLineTerminators(jsonStringify(value));
1900
+ }
1901
+
1902
+ // src/cli/structuredIO.ts
1903
+ var SANDBOX_NETWORK_ACCESS_TOOL_NAME = "SandboxNetworkAccess";
1904
+ function serializeDecisionReason(reason) {
1905
+ if (!reason) {
1906
+ return;
1907
+ }
1908
+ if (false) {}
1909
+ switch (reason.type) {
1910
+ case "rule":
1911
+ case "mode":
1912
+ case "subcommandResults":
1913
+ case "permissionPromptTool":
1914
+ return;
1915
+ case "hook":
1916
+ case "asyncAgent":
1917
+ case "sandboxOverride":
1918
+ case "workingDir":
1919
+ case "safetyCheck":
1920
+ case "other":
1921
+ return reason.reason;
1922
+ }
1923
+ }
1924
+ function buildRequiresActionDetails(tool, input, toolUseID, requestId) {
1925
+ let description;
1926
+ try {
1927
+ description = tool.getActivityDescription?.(input) ?? tool.getToolUseSummary?.(input) ?? tool.userFacingName(input);
1928
+ } catch {
1929
+ description = tool.name;
1930
+ }
1931
+ return {
1932
+ tool_name: tool.name,
1933
+ action_description: description,
1934
+ tool_use_id: toolUseID,
1935
+ request_id: requestId,
1936
+ input
1937
+ };
1938
+ }
1939
+ var MAX_RESOLVED_TOOL_USE_IDS = 1000;
1940
+
1941
+ class StructuredIO {
1942
+ input;
1943
+ replayUserMessages;
1944
+ structuredInput;
1945
+ pendingRequests = new Map;
1946
+ restoredWorkerState = Promise.resolve(null);
1947
+ inputClosed = false;
1948
+ unexpectedResponseCallback;
1949
+ resolvedToolUseIds = new Set;
1950
+ prependedLines = [];
1951
+ onControlRequestSent;
1952
+ onControlRequestResolved;
1953
+ outbound = new Stream;
1954
+ constructor(input, replayUserMessages) {
1955
+ this.input = input;
1956
+ this.replayUserMessages = replayUserMessages;
1957
+ this.input = input;
1958
+ this.structuredInput = this.read();
1959
+ }
1960
+ trackResolvedToolUseId(request) {
1961
+ const inner = request.request;
1962
+ if (inner.subtype === "can_use_tool") {
1963
+ this.resolvedToolUseIds.add(inner.tool_use_id);
1964
+ if (this.resolvedToolUseIds.size > MAX_RESOLVED_TOOL_USE_IDS) {
1965
+ const first = this.resolvedToolUseIds.values().next().value;
1966
+ if (first !== undefined) {
1967
+ this.resolvedToolUseIds.delete(first);
1968
+ }
1969
+ }
1970
+ }
1971
+ }
1972
+ flushInternalEvents() {
1973
+ return Promise.resolve();
1974
+ }
1975
+ get internalEventsPending() {
1976
+ return 0;
1977
+ }
1978
+ prependUserMessage(content) {
1979
+ this.prependedLines.push(jsonStringify({
1980
+ type: "user",
1981
+ content,
1982
+ uuid: "",
1983
+ session_id: "",
1984
+ message: { role: "user", content },
1985
+ parent_tool_use_id: null
1986
+ }) + `
1987
+ `);
1988
+ }
1989
+ async* read() {
1990
+ let content = "";
1991
+ const splitAndProcess = async function* () {
1992
+ for (;; ) {
1993
+ if (this.prependedLines.length > 0) {
1994
+ content = this.prependedLines.join("") + content;
1995
+ this.prependedLines = [];
1996
+ }
1997
+ const newline = content.indexOf(`
1998
+ `);
1999
+ if (newline === -1)
2000
+ break;
2001
+ const line = content.slice(0, newline);
2002
+ content = content.slice(newline + 1);
2003
+ const message = await this.processLine(line);
2004
+ if (message) {
2005
+ logForDiagnosticsNoPII("info", "cli_stdin_message_parsed", {
2006
+ type: message.type
2007
+ });
2008
+ yield message;
2009
+ }
2010
+ }
2011
+ }.bind(this);
2012
+ yield* splitAndProcess();
2013
+ for await (const block of this.input) {
2014
+ content += block;
2015
+ yield* splitAndProcess();
2016
+ }
2017
+ if (content) {
2018
+ const message = await this.processLine(content);
2019
+ if (message) {
2020
+ yield message;
2021
+ }
2022
+ }
2023
+ this.inputClosed = true;
2024
+ for (const request of this.pendingRequests.values()) {
2025
+ request.reject(new Error("Tool permission stream closed before response received"));
2026
+ }
2027
+ }
2028
+ getPendingPermissionRequests() {
2029
+ return Array.from(this.pendingRequests.values()).map((entry) => entry.request).filter((pr) => pr.request.subtype === "can_use_tool");
2030
+ }
2031
+ setUnexpectedResponseCallback(callback) {
2032
+ this.unexpectedResponseCallback = callback;
2033
+ }
2034
+ injectControlResponse(response) {
2035
+ const responseInner = response.response;
2036
+ const requestId = responseInner?.request_id;
2037
+ if (!requestId)
2038
+ return;
2039
+ const request = this.pendingRequests.get(requestId);
2040
+ if (!request)
2041
+ return;
2042
+ this.trackResolvedToolUseId(request.request);
2043
+ this.pendingRequests.delete(requestId);
2044
+ this.write({
2045
+ type: "control_cancel_request",
2046
+ request_id: requestId
2047
+ });
2048
+ if (responseInner.subtype === "error") {
2049
+ request.reject(new Error(responseInner.error));
2050
+ } else {
2051
+ const result = responseInner.response;
2052
+ if (request.schema) {
2053
+ try {
2054
+ request.resolve(request.schema.parse(result));
2055
+ } catch (error) {
2056
+ request.reject(error);
2057
+ }
2058
+ } else {
2059
+ request.resolve({});
2060
+ }
2061
+ }
2062
+ }
2063
+ setOnControlRequestSent(callback) {
2064
+ this.onControlRequestSent = callback;
2065
+ }
2066
+ setOnControlRequestResolved(callback) {
2067
+ this.onControlRequestResolved = callback;
2068
+ }
2069
+ async processLine(line) {
2070
+ if (!line) {
2071
+ return;
2072
+ }
2073
+ try {
2074
+ const message = normalizeControlMessageKeys(jsonParse(line));
2075
+ if (message.type === "keep_alive") {
2076
+ return;
2077
+ }
2078
+ if (message.type === "update_environment_variables") {
2079
+ const variables = message.variables;
2080
+ const keys = Object.keys(variables);
2081
+ for (const [key, value] of Object.entries(variables)) {
2082
+ process.env[key] = value;
2083
+ }
2084
+ logForDebugging(`[structuredIO] applied update_environment_variables: ${keys.join(", ")}`);
2085
+ return;
2086
+ }
2087
+ if (message.type === "control_response") {
2088
+ const uuid = "uuid" in message && typeof message.uuid === "string" ? message.uuid : undefined;
2089
+ if (uuid) {
2090
+ notifyCommandLifecycle(uuid, "completed");
2091
+ }
2092
+ const request = this.pendingRequests.get(message.response.request_id);
2093
+ if (!request) {
2094
+ const responsePayload = message.response.subtype === "success" ? message.response.response : undefined;
2095
+ const toolUseID = responsePayload?.toolUseID;
2096
+ if (typeof toolUseID === "string" && this.resolvedToolUseIds.has(toolUseID)) {
2097
+ logForDebugging(`Ignoring duplicate control_response for already-resolved toolUseID=${toolUseID} request_id=${message.response.request_id}`);
2098
+ return;
2099
+ }
2100
+ if (this.unexpectedResponseCallback) {
2101
+ await this.unexpectedResponseCallback(message);
2102
+ }
2103
+ return;
2104
+ }
2105
+ this.trackResolvedToolUseId(request.request);
2106
+ this.pendingRequests.delete(message.response.request_id);
2107
+ if (request.request.request.subtype === "can_use_tool" && this.onControlRequestResolved) {
2108
+ this.onControlRequestResolved(message.response.request_id);
2109
+ }
2110
+ if (message.response.subtype === "error") {
2111
+ request.reject(new Error(message.response.error));
2112
+ return;
2113
+ }
2114
+ const result = message.response.response;
2115
+ if (request.schema) {
2116
+ try {
2117
+ request.resolve(request.schema.parse(result));
2118
+ } catch (error) {
2119
+ request.reject(error);
2120
+ }
2121
+ } else {
2122
+ request.resolve({});
2123
+ }
2124
+ if (this.replayUserMessages) {
2125
+ return message;
2126
+ }
2127
+ return;
2128
+ }
2129
+ if (message.type !== "user" && message.type !== "control_request" && message.type !== "assistant" && message.type !== "system") {
2130
+ logForDebugging(`Ignoring unknown message type: ${message.type}`, {
2131
+ level: "warn"
2132
+ });
2133
+ return;
2134
+ }
2135
+ if (message.type === "control_request") {
2136
+ if (!message.request) {
2137
+ exitWithMessage(`Error: Missing request on control_request`);
2138
+ }
2139
+ return message;
2140
+ }
2141
+ if (message.type === "assistant" || message.type === "system") {
2142
+ return message;
2143
+ }
2144
+ if (message.message.role !== "user") {
2145
+ exitWithMessage(`Error: Expected message role 'user', got '${message.message.role}'`);
2146
+ }
2147
+ return message;
2148
+ } catch (error) {
2149
+ console.error(`Error parsing streaming input line: ${line}: ${error}`);
2150
+ process.exit(1);
2151
+ }
2152
+ }
2153
+ async write(message) {
2154
+ writeToStdout(ndjsonSafeStringify(message) + `
2155
+ `);
2156
+ }
2157
+ async sendRequest(request, schema, signal, requestId = randomUUID2()) {
2158
+ const message = {
2159
+ type: "control_request",
2160
+ request_id: requestId,
2161
+ request
2162
+ };
2163
+ if (this.inputClosed) {
2164
+ throw new Error("Stream closed");
2165
+ }
2166
+ if (signal?.aborted) {
2167
+ throw new Error("Request aborted");
2168
+ }
2169
+ this.outbound.enqueue(message);
2170
+ if (request.subtype === "can_use_tool" && this.onControlRequestSent) {
2171
+ this.onControlRequestSent(message);
2172
+ }
2173
+ const aborted = () => {
2174
+ this.outbound.enqueue({
2175
+ type: "control_cancel_request",
2176
+ request_id: requestId
2177
+ });
2178
+ const request2 = this.pendingRequests.get(requestId);
2179
+ if (request2) {
2180
+ this.trackResolvedToolUseId(request2.request);
2181
+ request2.reject(new AbortError);
2182
+ }
2183
+ };
2184
+ if (signal) {
2185
+ signal.addEventListener("abort", aborted, {
2186
+ once: true
2187
+ });
2188
+ }
2189
+ try {
2190
+ return await new Promise((resolve, reject) => {
2191
+ this.pendingRequests.set(requestId, {
2192
+ request: {
2193
+ type: "control_request",
2194
+ request_id: requestId,
2195
+ request
2196
+ },
2197
+ resolve: (result) => {
2198
+ resolve(result);
2199
+ },
2200
+ reject,
2201
+ schema
2202
+ });
2203
+ });
2204
+ } finally {
2205
+ if (signal) {
2206
+ signal.removeEventListener("abort", aborted);
2207
+ }
2208
+ this.pendingRequests.delete(requestId);
2209
+ }
2210
+ }
2211
+ createCanUseTool(onPermissionPrompt) {
2212
+ return async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => {
2213
+ const mainPermissionResult = forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseID);
2214
+ if (mainPermissionResult.behavior === "allow" || mainPermissionResult.behavior === "deny") {
2215
+ return mainPermissionResult;
2216
+ }
2217
+ const hookAbortController = new AbortController;
2218
+ const parentSignal = toolUseContext.abortController.signal;
2219
+ const onParentAbort = () => hookAbortController.abort();
2220
+ parentSignal.addEventListener("abort", onParentAbort, { once: true });
2221
+ try {
2222
+ const hookPromise = executePermissionRequestHooksForSDK(tool.name, toolUseID, input, toolUseContext, mainPermissionResult.suggestions).then((decision) => ({ source: "hook", decision }));
2223
+ const requestId = randomUUID2();
2224
+ onPermissionPrompt?.(buildRequiresActionDetails(tool, input, toolUseID, requestId));
2225
+ const sdkPromise = this.sendRequest({
2226
+ subtype: "can_use_tool",
2227
+ tool_name: tool.name,
2228
+ input,
2229
+ permission_suggestions: mainPermissionResult.suggestions,
2230
+ blocked_path: mainPermissionResult.blockedPath,
2231
+ decision_reason: serializeDecisionReason(mainPermissionResult.decisionReason),
2232
+ tool_use_id: toolUseID,
2233
+ agent_id: toolUseContext.agentId
2234
+ }, outputSchema(), hookAbortController.signal, requestId).then((result) => ({ source: "sdk", result }));
2235
+ const winner = await Promise.race([hookPromise, sdkPromise]);
2236
+ if (winner.source === "hook") {
2237
+ if (winner.decision) {
2238
+ sdkPromise.catch(() => {});
2239
+ hookAbortController.abort();
2240
+ return winner.decision;
2241
+ }
2242
+ const sdkResult = await sdkPromise;
2243
+ return permissionPromptToolResultToPermissionDecision(sdkResult.result, tool, input, toolUseContext);
2244
+ }
2245
+ return permissionPromptToolResultToPermissionDecision(winner.result, tool, input, toolUseContext);
2246
+ } catch (error) {
2247
+ return permissionPromptToolResultToPermissionDecision({
2248
+ behavior: "deny",
2249
+ message: `Tool permission request failed: ${error}`,
2250
+ toolUseID
2251
+ }, tool, input, toolUseContext);
2252
+ } finally {
2253
+ if (this.getPendingPermissionRequests().length === 0) {
2254
+ notifySessionStateChanged("running");
2255
+ }
2256
+ parentSignal.removeEventListener("abort", onParentAbort);
2257
+ }
2258
+ };
2259
+ }
2260
+ createHookCallback(callbackId, timeout) {
2261
+ return {
2262
+ type: "callback",
2263
+ timeout,
2264
+ callback: async (input, toolUseID, abort) => {
2265
+ try {
2266
+ const result = await this.sendRequest({
2267
+ subtype: "hook_callback",
2268
+ callback_id: callbackId,
2269
+ input,
2270
+ tool_use_id: toolUseID || undefined
2271
+ }, hookJSONOutputSchema(), abort);
2272
+ return result;
2273
+ } catch (error) {
2274
+ console.error(`Error in hook callback ${callbackId}:`, error);
2275
+ return {};
2276
+ }
2277
+ }
2278
+ };
2279
+ }
2280
+ async handleElicitation(serverName, message, requestedSchema, signal, mode, url, elicitationId) {
2281
+ try {
2282
+ const result = await this.sendRequest({
2283
+ subtype: "elicitation",
2284
+ mcp_server_name: serverName,
2285
+ message,
2286
+ mode,
2287
+ url,
2288
+ elicitation_id: elicitationId,
2289
+ requested_schema: requestedSchema
2290
+ }, SDKControlElicitationResponseSchema(), signal);
2291
+ return result;
2292
+ } catch {
2293
+ return { action: "cancel" };
2294
+ }
2295
+ }
2296
+ createSandboxAskCallback() {
2297
+ return async (hostPattern) => {
2298
+ try {
2299
+ const result = await this.sendRequest({
2300
+ subtype: "can_use_tool",
2301
+ tool_name: SANDBOX_NETWORK_ACCESS_TOOL_NAME,
2302
+ input: { host: hostPattern.host },
2303
+ tool_use_id: randomUUID2(),
2304
+ description: `Allow network connection to ${hostPattern.host}?`
2305
+ }, outputSchema());
2306
+ return result.behavior === "allow";
2307
+ } catch {
2308
+ return false;
2309
+ }
2310
+ };
2311
+ }
2312
+ async sendMcpMessage(serverName, message) {
2313
+ const response = await this.sendRequest({
2314
+ subtype: "mcp_message",
2315
+ server_name: serverName,
2316
+ message
2317
+ }, exports_external.object({
2318
+ mcp_response: exports_external.any()
2319
+ }));
2320
+ return response.mcp_response;
2321
+ }
2322
+ }
2323
+ function exitWithMessage(message) {
2324
+ console.error(message);
2325
+ process.exit(1);
2326
+ }
2327
+ async function executePermissionRequestHooksForSDK(toolName, toolUseID, input, toolUseContext, suggestions) {
2328
+ const appState = toolUseContext.getAppState();
2329
+ const permissionMode = appState.toolPermissionContext.mode;
2330
+ const hookGenerator = executePermissionRequestHooks(toolName, toolUseID, input, toolUseContext, permissionMode, suggestions, toolUseContext.abortController.signal);
2331
+ for await (const hookResult of hookGenerator) {
2332
+ if (hookResult.permissionRequestResult && (hookResult.permissionRequestResult.behavior === "allow" || hookResult.permissionRequestResult.behavior === "deny")) {
2333
+ const decision = hookResult.permissionRequestResult;
2334
+ if (decision.behavior === "allow") {
2335
+ const finalInput = decision.updatedInput || input;
2336
+ const permissionUpdates = decision.updatedPermissions ?? [];
2337
+ if (permissionUpdates.length > 0) {
2338
+ persistPermissionUpdates(permissionUpdates);
2339
+ const currentAppState = toolUseContext.getAppState();
2340
+ const updatedContext = applyPermissionUpdates(currentAppState.toolPermissionContext, permissionUpdates);
2341
+ toolUseContext.setAppState((prev) => {
2342
+ if (prev.toolPermissionContext === updatedContext)
2343
+ return prev;
2344
+ return { ...prev, toolPermissionContext: updatedContext };
2345
+ });
2346
+ }
2347
+ return {
2348
+ behavior: "allow",
2349
+ updatedInput: finalInput,
2350
+ userModified: false,
2351
+ decisionReason: {
2352
+ type: "hook",
2353
+ hookName: "PermissionRequest"
2354
+ }
2355
+ };
2356
+ } else {
2357
+ return {
2358
+ behavior: "deny",
2359
+ message: decision.message || "Permission denied by PermissionRequest hook",
2360
+ decisionReason: {
2361
+ type: "hook",
2362
+ hookName: "PermissionRequest"
2363
+ }
2364
+ };
2365
+ }
2366
+ }
2367
+ }
2368
+ return;
2369
+ }
2370
+
2371
+ // src/utils/awsAuthStatusManager.ts
2372
+ init_signal();
2373
+
2374
+ class AwsAuthStatusManager {
2375
+ static instance = null;
2376
+ status = {
2377
+ isAuthenticating: false,
2378
+ output: []
2379
+ };
2380
+ changed = createSignal();
2381
+ static getInstance() {
2382
+ if (!AwsAuthStatusManager.instance) {
2383
+ AwsAuthStatusManager.instance = new AwsAuthStatusManager;
2384
+ }
2385
+ return AwsAuthStatusManager.instance;
2386
+ }
2387
+ getStatus() {
2388
+ return {
2389
+ ...this.status,
2390
+ output: [...this.status.output]
2391
+ };
2392
+ }
2393
+ startAuthentication() {
2394
+ this.status = {
2395
+ isAuthenticating: true,
2396
+ output: []
2397
+ };
2398
+ this.changed.emit(this.getStatus());
2399
+ }
2400
+ addOutput(line) {
2401
+ this.status.output.push(line);
2402
+ this.changed.emit(this.getStatus());
2403
+ }
2404
+ setError(error) {
2405
+ this.status.error = error;
2406
+ this.changed.emit(this.getStatus());
2407
+ }
2408
+ endAuthentication(success) {
2409
+ if (success) {
2410
+ this.status = {
2411
+ isAuthenticating: false,
2412
+ output: []
2413
+ };
2414
+ } else {
2415
+ this.status.isAuthenticating = false;
2416
+ }
2417
+ this.changed.emit(this.getStatus());
2418
+ }
2419
+ subscribe = this.changed.subscribe;
2420
+ static reset() {
2421
+ if (AwsAuthStatusManager.instance) {
2422
+ AwsAuthStatusManager.instance.changed.clear();
2423
+ AwsAuthStatusManager.instance = null;
2424
+ }
2425
+ }
2426
+ }
2427
+
2428
+ // src/utils/ultraplan/keyword.ts
2429
+ var OPEN_TO_CLOSE = {
2430
+ "`": "`",
2431
+ '"': '"',
2432
+ "<": ">",
2433
+ "{": "}",
2434
+ "[": "]",
2435
+ "(": ")",
2436
+ "'": "'"
2437
+ };
2438
+ function findKeywordTriggerPositions(text, keyword) {
2439
+ const re = new RegExp(keyword, "i");
2440
+ if (!re.test(text))
2441
+ return [];
2442
+ if (text.startsWith("/"))
2443
+ return [];
2444
+ const quotedRanges = [];
2445
+ let openQuote = null;
2446
+ let openAt = 0;
2447
+ const isWord = (ch) => !!ch && /[\p{L}\p{N}_]/u.test(ch);
2448
+ for (let i = 0;i < text.length; i++) {
2449
+ const ch = text[i];
2450
+ if (openQuote) {
2451
+ if (openQuote === "[" && ch === "[") {
2452
+ openAt = i;
2453
+ continue;
2454
+ }
2455
+ if (ch !== OPEN_TO_CLOSE[openQuote])
2456
+ continue;
2457
+ if (openQuote === "'" && isWord(text[i + 1]))
2458
+ continue;
2459
+ quotedRanges.push({ start: openAt, end: i + 1 });
2460
+ openQuote = null;
2461
+ } else if (ch === "<" && i + 1 < text.length && /[a-zA-Z/]/.test(text[i + 1]) || ch === "'" && !isWord(text[i - 1]) || ch !== "<" && ch !== "'" && ch in OPEN_TO_CLOSE) {
2462
+ openQuote = ch;
2463
+ openAt = i;
2464
+ }
2465
+ }
2466
+ const positions = [];
2467
+ const wordRe = new RegExp(`\\b${keyword}\\b`, "gi");
2468
+ const matches = text.matchAll(wordRe);
2469
+ for (const match of matches) {
2470
+ if (match.index === undefined)
2471
+ continue;
2472
+ const start = match.index;
2473
+ const end = start + match[0].length;
2474
+ if (quotedRanges.some((r) => start >= r.start && start < r.end))
2475
+ continue;
2476
+ const before = text[start - 1];
2477
+ const after = text[end];
2478
+ if (before === "/" || before === "\\" || before === "-")
2479
+ continue;
2480
+ if (after === "/" || after === "\\" || after === "-" || after === "?")
2481
+ continue;
2482
+ if (after === "." && isWord(text[end + 1]))
2483
+ continue;
2484
+ positions.push({ word: match[0], start, end });
2485
+ }
2486
+ return positions;
2487
+ }
2488
+ function findUltraplanTriggerPositions(text) {
2489
+ return findKeywordTriggerPositions(text, "ultraplan");
2490
+ }
2491
+ function findUltrareviewTriggerPositions(text) {
2492
+ return findKeywordTriggerPositions(text, "ultrareview");
2493
+ }
2494
+ function hasUltraplanKeyword(text) {
2495
+ return findUltraplanTriggerPositions(text).length > 0;
2496
+ }
2497
+ function replaceUltraplanKeyword(text) {
2498
+ const [trigger] = findUltraplanTriggerPositions(text);
2499
+ if (!trigger)
2500
+ return text;
2501
+ const before = text.slice(0, trigger.start);
2502
+ const after = text.slice(trigger.end);
2503
+ if (!(before + after).trim())
2504
+ return "";
2505
+ return before + trigger.word.slice("ultra".length) + after;
2506
+ }
2507
+
2508
+ // src/utils/processUserInput/processUserInput.ts
2509
+ init_analytics();
2510
+ init_messages();
2511
+ init_commands();
2512
+ init_textInputTypes();
2513
+ init_attachments();
2514
+ init_generators();
2515
+ init_hooks2();
2516
+ init_imageResizer();
2517
+ init_imageStore();
2518
+ init_messages();
2519
+ init_queryProfiler();
2520
+ init_slashCommandParsing();
2521
+ import { randomUUID as randomUUID4 } from "crypto";
2522
+
2523
+ // src/utils/processUserInput/processTextPrompt.ts
2524
+ init_state();
2525
+ init_analytics();
2526
+ init_messages();
2527
+ init_events();
2528
+ init_sessionTracing();
2529
+ import { randomUUID as randomUUID3 } from "crypto";
2530
+
2531
+ // src/utils/userPromptKeywords.ts
2532
+ function matchesNegativeKeyword(input) {
2533
+ const lowerInput = input.toLowerCase();
2534
+ const negativePattern = /\b(wtf|wth|ffs|omfg|shit(ty|tiest)?|dumbass|horrible|awful|piss(ed|ing)? off|piece of (shit|crap|junk)|what the (fuck|hell)|fucking? (broken|useless|terrible|awful|horrible)|fuck you|screw (this|you)|so frustrating|this sucks|damn it)\b/;
2535
+ return negativePattern.test(lowerInput);
2536
+ }
2537
+ function matchesKeepGoingKeyword(input) {
2538
+ const lowerInput = input.toLowerCase().trim();
2539
+ if (lowerInput === "continue") {
2540
+ return true;
2541
+ }
2542
+ const keepGoingPattern = /\b(keep going|go on)\b/;
2543
+ return keepGoingPattern.test(lowerInput);
2544
+ }
2545
+
2546
+ // src/utils/processUserInput/processTextPrompt.ts
2547
+ function processTextPrompt(input, imageContentBlocks, imagePasteIds, attachmentMessages, uuid, permissionMode, isMeta) {
2548
+ const promptId = randomUUID3();
2549
+ setPromptId(promptId);
2550
+ const userPromptText = typeof input === "string" ? input : input.find((block) => block.type === "text")?.text || "";
2551
+ startInteractionSpan(userPromptText);
2552
+ const otelPromptText = typeof input === "string" ? input : input.findLast((block) => block.type === "text")?.text || "";
2553
+ if (otelPromptText) {
2554
+ logOTelEvent("user_prompt", {
2555
+ prompt_length: String(otelPromptText.length),
2556
+ prompt: redactIfDisabled(otelPromptText),
2557
+ "prompt.id": promptId
2558
+ });
2559
+ }
2560
+ const isNegative = matchesNegativeKeyword(userPromptText);
2561
+ const isKeepGoing = matchesKeepGoingKeyword(userPromptText);
2562
+ logEvent("tengu_input_prompt", {
2563
+ is_negative: isNegative,
2564
+ is_keep_going: isKeepGoing
2565
+ });
2566
+ if (imageContentBlocks.length > 0) {
2567
+ const textContent = typeof input === "string" ? input.trim() ? [{ type: "text", text: input }] : [] : input;
2568
+ const userMessage2 = createUserMessage({
2569
+ content: [...textContent, ...imageContentBlocks],
2570
+ uuid,
2571
+ imagePasteIds: imagePasteIds.length > 0 ? imagePasteIds : undefined,
2572
+ permissionMode,
2573
+ isMeta: isMeta || undefined
2574
+ });
2575
+ return {
2576
+ messages: [userMessage2, ...attachmentMessages],
2577
+ shouldQuery: true
2578
+ };
2579
+ }
2580
+ const userMessage = createUserMessage({
2581
+ content: input,
2582
+ uuid,
2583
+ permissionMode,
2584
+ isMeta: isMeta || undefined
2585
+ });
2586
+ return {
2587
+ messages: [userMessage, ...attachmentMessages],
2588
+ shouldQuery: true
2589
+ };
2590
+ }
2591
+
2592
+ // src/utils/processUserInput/processUserInput.ts
2593
+ async function processUserInput({
2594
+ input,
2595
+ preExpansionInput,
2596
+ mode,
2597
+ setToolJSX,
2598
+ context,
2599
+ pastedContents,
2600
+ ideSelection,
2601
+ messages,
2602
+ setUserInputOnProcessing,
2603
+ uuid,
2604
+ isAlreadyProcessing,
2605
+ querySource,
2606
+ canUseTool,
2607
+ skipSlashCommands,
2608
+ bridgeOrigin,
2609
+ isMeta,
2610
+ skipAttachments
2611
+ }) {
2612
+ const inputString = typeof input === "string" ? input : null;
2613
+ if (mode === "prompt" && inputString !== null && !isMeta) {
2614
+ setUserInputOnProcessing?.(inputString);
2615
+ }
2616
+ queryCheckpoint("query_process_user_input_base_start");
2617
+ const appState = context.getAppState();
2618
+ const result = await processUserInputBase(input, mode, setToolJSX, context, pastedContents, ideSelection, messages, uuid, isAlreadyProcessing, querySource, canUseTool, appState.toolPermissionContext.mode, skipSlashCommands, bridgeOrigin, isMeta, skipAttachments, preExpansionInput);
2619
+ queryCheckpoint("query_process_user_input_base_end");
2620
+ if (!result.shouldQuery) {
2621
+ return result;
2622
+ }
2623
+ queryCheckpoint("query_hooks_start");
2624
+ const inputMessage = getContentText(input) || "";
2625
+ for await (const hookResult of executeUserPromptSubmitHooks(inputMessage, appState.toolPermissionContext.mode, context, context.requestPrompt)) {
2626
+ if (hookResult.message?.type === "progress") {
2627
+ continue;
2628
+ }
2629
+ if (hookResult.blockingError) {
2630
+ const blockingMessage = getUserPromptSubmitHookBlockingMessage(hookResult.blockingError);
2631
+ return {
2632
+ messages: [
2633
+ createSystemMessage(`${blockingMessage}
2634
+
2635
+ Original prompt: ${input}`, "warning")
2636
+ ],
2637
+ shouldQuery: false,
2638
+ allowedTools: result.allowedTools
2639
+ };
2640
+ }
2641
+ if (hookResult.preventContinuation) {
2642
+ const message = hookResult.stopReason ? `Operation stopped by hook: ${hookResult.stopReason}` : "Operation stopped by hook";
2643
+ result.messages.push(createUserMessage({
2644
+ content: message
2645
+ }));
2646
+ result.shouldQuery = false;
2647
+ return result;
2648
+ }
2649
+ if (hookResult.additionalContexts && hookResult.additionalContexts.length > 0) {
2650
+ result.messages.push(createAttachmentMessage({
2651
+ type: "hook_additional_context",
2652
+ content: hookResult.additionalContexts.map(applyTruncation),
2653
+ hookName: "UserPromptSubmit",
2654
+ toolUseID: `hook-${randomUUID4()}`,
2655
+ hookEvent: "UserPromptSubmit"
2656
+ }));
2657
+ }
2658
+ if (hookResult.message) {
2659
+ switch (hookResult.message.attachment.type) {
2660
+ case "hook_success":
2661
+ if (!hookResult.message.attachment.content) {
2662
+ break;
2663
+ }
2664
+ result.messages.push({
2665
+ ...hookResult.message,
2666
+ attachment: {
2667
+ ...hookResult.message.attachment,
2668
+ content: applyTruncation(hookResult.message.attachment.content)
2669
+ }
2670
+ });
2671
+ break;
2672
+ default:
2673
+ result.messages.push(hookResult.message);
2674
+ break;
2675
+ }
2676
+ }
2677
+ }
2678
+ queryCheckpoint("query_hooks_end");
2679
+ return result;
2680
+ }
2681
+ var MAX_HOOK_OUTPUT_LENGTH = 1e4;
2682
+ function applyTruncation(content) {
2683
+ if (content.length > MAX_HOOK_OUTPUT_LENGTH) {
2684
+ return `${content.substring(0, MAX_HOOK_OUTPUT_LENGTH)}\u2026 [output truncated - exceeded ${MAX_HOOK_OUTPUT_LENGTH} characters]`;
2685
+ }
2686
+ return content;
2687
+ }
2688
+ async function processUserInputBase(input, mode, setToolJSX, context, pastedContents, ideSelection, messages, uuid, isAlreadyProcessing, querySource, canUseTool, permissionMode, skipSlashCommands, bridgeOrigin, isMeta, skipAttachments, preExpansionInput) {
2689
+ let inputString = null;
2690
+ let precedingInputBlocks = [];
2691
+ const imageMetadataTexts = [];
2692
+ let normalizedInput = input;
2693
+ if (typeof input === "string") {
2694
+ inputString = input;
2695
+ } else if (input.length > 0) {
2696
+ queryCheckpoint("query_image_processing_start");
2697
+ const processedBlocks = [];
2698
+ for (const block of input) {
2699
+ if (block.type === "image") {
2700
+ const resized = await maybeResizeAndDownsampleImageBlock(block);
2701
+ if (resized.dimensions) {
2702
+ const metadataText = createImageMetadataText(resized.dimensions);
2703
+ if (metadataText) {
2704
+ imageMetadataTexts.push(metadataText);
2705
+ }
2706
+ }
2707
+ processedBlocks.push(resized.block);
2708
+ } else {
2709
+ processedBlocks.push(block);
2710
+ }
2711
+ }
2712
+ normalizedInput = processedBlocks;
2713
+ queryCheckpoint("query_image_processing_end");
2714
+ const lastBlock = processedBlocks[processedBlocks.length - 1];
2715
+ if (lastBlock?.type === "text") {
2716
+ inputString = lastBlock.text;
2717
+ precedingInputBlocks = processedBlocks.slice(0, -1);
2718
+ } else {
2719
+ precedingInputBlocks = processedBlocks;
2720
+ }
2721
+ }
2722
+ if (inputString === null && mode !== "prompt") {
2723
+ throw new Error(`Mode: ${mode} requires a string input.`);
2724
+ }
2725
+ const imageContents = pastedContents ? Object.values(pastedContents).filter(isValidImagePaste) : [];
2726
+ const imagePasteIds = imageContents.map((img) => img.id);
2727
+ const storedImagePaths = pastedContents ? await storeImages(pastedContents) : new Map;
2728
+ queryCheckpoint("query_pasted_image_processing_start");
2729
+ const imageProcessingResults = await Promise.all(imageContents.map(async (pastedImage) => {
2730
+ const imageBlock = {
2731
+ type: "image",
2732
+ source: {
2733
+ type: "base64",
2734
+ media_type: pastedImage.mediaType || "image/png",
2735
+ data: pastedImage.content
2736
+ }
2737
+ };
2738
+ logEvent("tengu_pasted_image_resize_attempt", {
2739
+ original_size_bytes: pastedImage.content.length
2740
+ });
2741
+ const resized = await maybeResizeAndDownsampleImageBlock(imageBlock);
2742
+ return {
2743
+ resized,
2744
+ originalDimensions: pastedImage.dimensions,
2745
+ sourcePath: pastedImage.sourcePath ?? storedImagePaths.get(pastedImage.id)
2746
+ };
2747
+ }));
2748
+ const imageContentBlocks = [];
2749
+ for (const {
2750
+ resized,
2751
+ originalDimensions,
2752
+ sourcePath
2753
+ } of imageProcessingResults) {
2754
+ if (resized.dimensions) {
2755
+ const metadataText = createImageMetadataText(resized.dimensions, sourcePath);
2756
+ if (metadataText) {
2757
+ imageMetadataTexts.push(metadataText);
2758
+ }
2759
+ } else if (originalDimensions) {
2760
+ const metadataText = createImageMetadataText(originalDimensions, sourcePath);
2761
+ if (metadataText) {
2762
+ imageMetadataTexts.push(metadataText);
2763
+ }
2764
+ } else if (sourcePath) {
2765
+ imageMetadataTexts.push(`[Image source: ${sourcePath}]`);
2766
+ }
2767
+ imageContentBlocks.push(resized.block);
2768
+ }
2769
+ queryCheckpoint("query_pasted_image_processing_end");
2770
+ let effectiveSkipSlash = skipSlashCommands;
2771
+ if (bridgeOrigin && inputString !== null && inputString.startsWith("/")) {
2772
+ const parsed = parseSlashCommand(inputString);
2773
+ const cmd = parsed ? findCommand(parsed.commandName, context.options.commands) : undefined;
2774
+ if (cmd) {
2775
+ if (isBridgeSafeCommand(cmd)) {
2776
+ effectiveSkipSlash = false;
2777
+ } else {
2778
+ const msg = `/${getCommandName(cmd)} isn't available over Remote Control.`;
2779
+ return {
2780
+ messages: [
2781
+ createUserMessage({ content: inputString, uuid }),
2782
+ createCommandInputMessage(`<local-command-stdout>${msg}</local-command-stdout>`)
2783
+ ],
2784
+ shouldQuery: false,
2785
+ resultText: msg
2786
+ };
2787
+ }
2788
+ }
2789
+ }
2790
+ if (mode === "prompt" && !context.options.isNonInteractiveSession && inputString !== null && !effectiveSkipSlash && !inputString.startsWith("/") && !context.getAppState().ultraplanSessionUrl && !context.getAppState().ultraplanLaunching && hasUltraplanKeyword(preExpansionInput ?? inputString)) {
2791
+ logEvent("tengu_ultraplan_keyword", {});
2792
+ const rewritten = replaceUltraplanKeyword(inputString).trim();
2793
+ const { processSlashCommand } = await import("./chunk-162ewhvy.js");
2794
+ const slashResult = await processSlashCommand(`/ultraplan ${rewritten}`, precedingInputBlocks, imageContentBlocks, [], context, setToolJSX, uuid, isAlreadyProcessing, canUseTool);
2795
+ return addImageMetadataMessage(slashResult, imageMetadataTexts);
2796
+ }
2797
+ const shouldExtractAttachments = !skipAttachments && inputString !== null && (mode !== "prompt" || effectiveSkipSlash || !inputString.startsWith("/"));
2798
+ queryCheckpoint("query_attachment_loading_start");
2799
+ const attachmentMessages = shouldExtractAttachments ? await toArray(getAttachmentMessages(inputString, context, ideSelection ?? null, [], messages, querySource)) : [];
2800
+ queryCheckpoint("query_attachment_loading_end");
2801
+ if (inputString !== null && mode === "bash") {
2802
+ const { processBashCommand } = await import("./chunk-19e603rv.js");
2803
+ return addImageMetadataMessage(await processBashCommand(inputString, precedingInputBlocks, attachmentMessages, context, setToolJSX), imageMetadataTexts);
2804
+ }
2805
+ if (inputString !== null && !effectiveSkipSlash && inputString.startsWith("/")) {
2806
+ const { processSlashCommand } = await import("./chunk-162ewhvy.js");
2807
+ const slashResult = await processSlashCommand(inputString, precedingInputBlocks, imageContentBlocks, attachmentMessages, context, setToolJSX, uuid, isAlreadyProcessing, canUseTool);
2808
+ return addImageMetadataMessage(slashResult, imageMetadataTexts);
2809
+ }
2810
+ if (inputString !== null && mode === "prompt") {
2811
+ const trimmedInput = inputString.trim();
2812
+ const agentMention = attachmentMessages.find((m) => m.attachment.type === "agent_mention");
2813
+ if (agentMention) {
2814
+ const agentMentionString = `@agent-${agentMention.attachment.agentType}`;
2815
+ const isSubagentOnly = trimmedInput === agentMentionString;
2816
+ const isPrefix = trimmedInput.startsWith(agentMentionString) && !isSubagentOnly;
2817
+ logEvent("tengu_subagent_at_mention", {
2818
+ is_subagent_only: isSubagentOnly,
2819
+ is_prefix: isPrefix
2820
+ });
2821
+ }
2822
+ }
2823
+ return addImageMetadataMessage(processTextPrompt(normalizedInput, imageContentBlocks, imagePasteIds, attachmentMessages, uuid, permissionMode, isMeta), imageMetadataTexts);
2824
+ }
2825
+ function addImageMetadataMessage(result, imageMetadataTexts) {
2826
+ if (imageMetadataTexts.length > 0) {
2827
+ result.messages.push(createUserMessage({
2828
+ content: imageMetadataTexts.map((text) => ({ type: "text", text })),
2829
+ isMeta: true
2830
+ }));
2831
+ }
2832
+ return result;
2833
+ }
2834
+
2835
+ // src/utils/plugins/reconciler.ts
2836
+ init_isEqual();
2837
+ init_state();
2838
+ init_debug();
2839
+ init_errors();
2840
+ init_file();
2841
+ init_git();
2842
+ init_log();
2843
+ init_marketplaceManager();
2844
+ init_schemas();
2845
+ import { isAbsolute, resolve } from "path";
2846
+ function diffMarketplaces(declared, materialized, opts) {
2847
+ const missing = [];
2848
+ const sourceChanged = [];
2849
+ const upToDate = [];
2850
+ for (const [name, intent] of Object.entries(declared)) {
2851
+ const state = materialized[name];
2852
+ const normalizedIntent = normalizeSource(intent.source, opts?.projectRoot);
2853
+ if (!state) {
2854
+ missing.push(name);
2855
+ } else if (intent.sourceIsFallback) {
2856
+ upToDate.push(name);
2857
+ } else if (!isEqual_default(normalizedIntent, state.source)) {
2858
+ sourceChanged.push({
2859
+ name,
2860
+ declaredSource: normalizedIntent,
2861
+ materializedSource: state.source
2862
+ });
2863
+ } else {
2864
+ upToDate.push(name);
2865
+ }
2866
+ }
2867
+ return { missing, sourceChanged, upToDate };
2868
+ }
2869
+ async function reconcileMarketplaces(opts) {
2870
+ const declared = getDeclaredMarketplaces();
2871
+ if (Object.keys(declared).length === 0) {
2872
+ return { installed: [], updated: [], failed: [], upToDate: [], skipped: [] };
2873
+ }
2874
+ let materialized;
2875
+ try {
2876
+ materialized = await loadKnownMarketplacesConfig();
2877
+ } catch (e) {
2878
+ logError(e);
2879
+ materialized = {};
2880
+ }
2881
+ const diff = diffMarketplaces(declared, materialized, {
2882
+ projectRoot: getOriginalCwd()
2883
+ });
2884
+ const work = [
2885
+ ...diff.missing.map((name) => ({
2886
+ name,
2887
+ source: normalizeSource(declared[name].source),
2888
+ action: "install"
2889
+ })),
2890
+ ...diff.sourceChanged.map(({ name, declaredSource }) => ({
2891
+ name,
2892
+ source: declaredSource,
2893
+ action: "update"
2894
+ }))
2895
+ ];
2896
+ const skipped = [];
2897
+ const toProcess = [];
2898
+ for (const item of work) {
2899
+ if (opts?.skip?.(item.name, item.source)) {
2900
+ skipped.push(item.name);
2901
+ continue;
2902
+ }
2903
+ if (item.action === "update" && isLocalMarketplaceSource(item.source) && !await pathExists(item.source.path)) {
2904
+ logForDebugging(`[reconcile] '${item.name}' declared path does not exist; keeping materialized entry`);
2905
+ skipped.push(item.name);
2906
+ continue;
2907
+ }
2908
+ toProcess.push(item);
2909
+ }
2910
+ if (toProcess.length === 0) {
2911
+ return {
2912
+ installed: [],
2913
+ updated: [],
2914
+ failed: [],
2915
+ upToDate: diff.upToDate,
2916
+ skipped
2917
+ };
2918
+ }
2919
+ logForDebugging(`[reconcile] ${toProcess.length} marketplace(s): ${toProcess.map((w) => `${w.name}(${w.action})`).join(", ")}`);
2920
+ const installed = [];
2921
+ const updated = [];
2922
+ const failed = [];
2923
+ for (let i = 0;i < toProcess.length; i++) {
2924
+ const { name, source, action } = toProcess[i];
2925
+ opts?.onProgress?.({
2926
+ type: "installing",
2927
+ name,
2928
+ action,
2929
+ index: i + 1,
2930
+ total: toProcess.length
2931
+ });
2932
+ try {
2933
+ const result = await addMarketplaceSource(source);
2934
+ if (action === "install")
2935
+ installed.push(name);
2936
+ else
2937
+ updated.push(name);
2938
+ opts?.onProgress?.({
2939
+ type: "installed",
2940
+ name,
2941
+ alreadyMaterialized: result.alreadyMaterialized
2942
+ });
2943
+ } catch (e) {
2944
+ const error = errorMessage(e);
2945
+ failed.push({ name, error });
2946
+ opts?.onProgress?.({ type: "failed", name, error });
2947
+ logError(e);
2948
+ }
2949
+ }
2950
+ return { installed, updated, failed, upToDate: diff.upToDate, skipped };
2951
+ }
2952
+ function normalizeSource(source, projectRoot) {
2953
+ if ((source.source === "directory" || source.source === "file") && !isAbsolute(source.path)) {
2954
+ const base = projectRoot ?? getOriginalCwd();
2955
+ const canonicalRoot = findCanonicalGitRoot(base);
2956
+ return {
2957
+ ...source,
2958
+ path: resolve(canonicalRoot ?? base, source.path)
2959
+ };
2960
+ }
2961
+ return source;
2962
+ }
2963
+
2964
+ export { MessageSelector, selectableUserMessagesFilter, messagesAfterAreOnlySynthetic, exports_MessageSelector, init_MessageSelector, findUltraplanTriggerPositions, findUltrareviewTriggerPositions, processUserInput, outputSchema, permissionPromptToolResultToPermissionDecision, ndjsonSafeStringify, StructuredIO, diffMarketplaces, reconcileMarketplaces, AwsAuthStatusManager, getCronJitterConfig, exports_cronJitterConfig, init_cronJitterConfig, createCronScheduler, exports_cronScheduler, init_cronScheduler };