@caspian2026/agent-sdk 0.0.24 → 0.0.26

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