@costrict/csc 4.0.1

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 (535) hide show
  1. package/README.md +398 -0
  2. package/dist/chunk-04hza677.js +24 -0
  3. package/dist/chunk-0559sa47.js +269 -0
  4. package/dist/chunk-06saje2v.js +39 -0
  5. package/dist/chunk-07069jq1.js +30 -0
  6. package/dist/chunk-070x53zd.js +2377 -0
  7. package/dist/chunk-0731m51q.js +8 -0
  8. package/dist/chunk-0858agqy.js +481 -0
  9. package/dist/chunk-09vwyeam.js +16 -0
  10. package/dist/chunk-0h5jp1k7.js +142 -0
  11. package/dist/chunk-0hhpf3sk.js +703 -0
  12. package/dist/chunk-0rpb2bdp.js +8 -0
  13. package/dist/chunk-0vkfrmqm.js +690 -0
  14. package/dist/chunk-0xjaqda8.js +1124 -0
  15. package/dist/chunk-0xv28twy.js +140 -0
  16. package/dist/chunk-0yrqcj0z.js +117 -0
  17. package/dist/chunk-1141xmr4.js +8 -0
  18. package/dist/chunk-11nzax0s.js +38 -0
  19. package/dist/chunk-13hhjhs8.js +1299 -0
  20. package/dist/chunk-15yrwc9c.js +110 -0
  21. package/dist/chunk-168xb8v1.js +436 -0
  22. package/dist/chunk-1a1qct3y.js +120 -0
  23. package/dist/chunk-1cwdhk7a.js +969 -0
  24. package/dist/chunk-1dz5e26z.js +726 -0
  25. package/dist/chunk-1h2famwb.js +49 -0
  26. package/dist/chunk-1hreef20.js +27 -0
  27. package/dist/chunk-1mpdkjdj.js +66 -0
  28. package/dist/chunk-1pvfqrpv.js +78 -0
  29. package/dist/chunk-1r1zzbv3.js +112 -0
  30. package/dist/chunk-1rvwfjaq.js +71 -0
  31. package/dist/chunk-1w2y3m4g.js +47290 -0
  32. package/dist/chunk-1xf1hn04.js +366 -0
  33. package/dist/chunk-225mq9kr.js +908 -0
  34. package/dist/chunk-238g70xa.js +36 -0
  35. package/dist/chunk-23my8c16.js +516 -0
  36. package/dist/chunk-26wtxbdc.js +13870 -0
  37. package/dist/chunk-2a42s11t.js +412 -0
  38. package/dist/chunk-2eykm0j0.js +20 -0
  39. package/dist/chunk-2fwze72g.js +24 -0
  40. package/dist/chunk-2gdm9hp2.js +1179 -0
  41. package/dist/chunk-2gzv8nrw.js +205 -0
  42. package/dist/chunk-2jb168ef.js +772 -0
  43. package/dist/chunk-2k995y2x.js +880 -0
  44. package/dist/chunk-2nayx6q1.js +63 -0
  45. package/dist/chunk-2p2kknmh.js +165 -0
  46. package/dist/chunk-2qa6bvek.js +146 -0
  47. package/dist/chunk-2qz6r4n3.js +74 -0
  48. package/dist/chunk-2s460rgh.js +61 -0
  49. package/dist/chunk-2wv3ttqg.js +199 -0
  50. package/dist/chunk-2wvz22ag.js +71 -0
  51. package/dist/chunk-2wz9qb4j.js +164 -0
  52. package/dist/chunk-30rst83v.js +168 -0
  53. package/dist/chunk-39jcea92.js +737 -0
  54. package/dist/chunk-3bes9fg8.js +78 -0
  55. package/dist/chunk-3c25bcsw.js +17 -0
  56. package/dist/chunk-3cg807vs.js +38 -0
  57. package/dist/chunk-3dy7fxmg.js +1072 -0
  58. package/dist/chunk-3h8a89gy.js +46 -0
  59. package/dist/chunk-3j0f3yyd.js +17 -0
  60. package/dist/chunk-3mgywd32.js +8 -0
  61. package/dist/chunk-3ng1qsw3.js +281 -0
  62. package/dist/chunk-3nk79af8.js +8 -0
  63. package/dist/chunk-3ns6ys7f.js +1648 -0
  64. package/dist/chunk-3sj7jkgr.js +35 -0
  65. package/dist/chunk-3tg3p70s.js +513 -0
  66. package/dist/chunk-3v18yz1s.js +21933 -0
  67. package/dist/chunk-3vxgde8h.js +830 -0
  68. package/dist/chunk-3w6s9m5w.js +16 -0
  69. package/dist/chunk-3x2jaxpw.js +254 -0
  70. package/dist/chunk-3xyekzfn.js +113 -0
  71. package/dist/chunk-3yeacwwq.js +115 -0
  72. package/dist/chunk-3z5e623j.js +130 -0
  73. package/dist/chunk-3z9478wf.js +14 -0
  74. package/dist/chunk-46fcr28b.js +131 -0
  75. package/dist/chunk-495d85x1.js +8066 -0
  76. package/dist/chunk-4bfwebv9.js +276 -0
  77. package/dist/chunk-4g3v8y12.js +23 -0
  78. package/dist/chunk-4gn5yqrx.js +79 -0
  79. package/dist/chunk-4jfp4pr0.js +24 -0
  80. package/dist/chunk-4jm600zv.js +13 -0
  81. package/dist/chunk-4nspekjp.js +69 -0
  82. package/dist/chunk-4pbx3g7s.js +26 -0
  83. package/dist/chunk-4t6efhvx.js +102 -0
  84. package/dist/chunk-4te4ttsn.js +42 -0
  85. package/dist/chunk-4x6wg2kg.js +254 -0
  86. package/dist/chunk-4y23e4m9.js +399 -0
  87. package/dist/chunk-4zfkzkt6.js +37 -0
  88. package/dist/chunk-4zh96y27.js +202 -0
  89. package/dist/chunk-512kh02z.js +117 -0
  90. package/dist/chunk-538ydk68.js +85 -0
  91. package/dist/chunk-56ax2vae.js +255 -0
  92. package/dist/chunk-56r79b2b.js +69 -0
  93. package/dist/chunk-57zse1aw.js +393 -0
  94. package/dist/chunk-5c5xde65.js +229 -0
  95. package/dist/chunk-5c8g21yn.js +334 -0
  96. package/dist/chunk-5hfekx34.js +158 -0
  97. package/dist/chunk-5j8wked2.js +125 -0
  98. package/dist/chunk-5krq9sjq.js +291 -0
  99. package/dist/chunk-5kstcfhs.js +180 -0
  100. package/dist/chunk-5q9t5raw.js +1077 -0
  101. package/dist/chunk-5z0vwms1.js +20 -0
  102. package/dist/chunk-5z28bqne.js +6748 -0
  103. package/dist/chunk-616twzqj.js +17 -0
  104. package/dist/chunk-62me46b4.js +115 -0
  105. package/dist/chunk-62xkxk9z.js +32 -0
  106. package/dist/chunk-64c1avct.js +13 -0
  107. package/dist/chunk-677as3nh.js +15 -0
  108. package/dist/chunk-68jt10ky.js +170 -0
  109. package/dist/chunk-6aspnjtj.js +213 -0
  110. package/dist/chunk-6bd8brc4.js +48 -0
  111. package/dist/chunk-6dj5t602.js +341 -0
  112. package/dist/chunk-6e7578mb.js +183 -0
  113. package/dist/chunk-6gr3c3w9.js +378 -0
  114. package/dist/chunk-6km733xr.js +1393 -0
  115. package/dist/chunk-6kpdq5vp.js +269 -0
  116. package/dist/chunk-6mzwkxka.js +591 -0
  117. package/dist/chunk-6n4rgw3j.js +308 -0
  118. package/dist/chunk-6p4cyhb3.js +16 -0
  119. package/dist/chunk-6ps660aq.js +177 -0
  120. package/dist/chunk-6rvt67cg.js +156 -0
  121. package/dist/chunk-6tq2v3rk.js +186 -0
  122. package/dist/chunk-6vhnnq2y.js +1410 -0
  123. package/dist/chunk-6wyva7w0.js +208 -0
  124. package/dist/chunk-6x0hj15f.js +502 -0
  125. package/dist/chunk-71pmx33m.js +367 -0
  126. package/dist/chunk-71ynp714.js +101 -0
  127. package/dist/chunk-73rpbt04.js +1947 -0
  128. package/dist/chunk-74vem2p2.js +34238 -0
  129. package/dist/chunk-760252na.js +101 -0
  130. package/dist/chunk-7739pg2c.js +4261 -0
  131. package/dist/chunk-78ynhtwg.js +71 -0
  132. package/dist/chunk-7aw745vx.js +40175 -0
  133. package/dist/chunk-7ethp9j4.js +785 -0
  134. package/dist/chunk-7f9h59mx.js +123 -0
  135. package/dist/chunk-7gwn2q3t.js +267 -0
  136. package/dist/chunk-7j39efa9.js +4521 -0
  137. package/dist/chunk-7nzp7c14.js +113 -0
  138. package/dist/chunk-7p0pvq5a.js +1189 -0
  139. package/dist/chunk-7pe7wxtx.js +37 -0
  140. package/dist/chunk-7wm5s02e.js +216 -0
  141. package/dist/chunk-7xyswgjh.js +8 -0
  142. package/dist/chunk-80ex85y3.js +231 -0
  143. package/dist/chunk-80v8c3v8.js +94 -0
  144. package/dist/chunk-8225arm6.js +6374 -0
  145. package/dist/chunk-82eajk9f.js +885 -0
  146. package/dist/chunk-83hfzbx3.js +10 -0
  147. package/dist/chunk-84bn8nbd.js +130 -0
  148. package/dist/chunk-85em0j2s.js +61 -0
  149. package/dist/chunk-86vz5aga.js +585 -0
  150. package/dist/chunk-86zqm75k.js +119 -0
  151. package/dist/chunk-894yt5ch.js +127 -0
  152. package/dist/chunk-89f30geq.js +114 -0
  153. package/dist/chunk-89m2z6cf.js +542 -0
  154. package/dist/chunk-89spcmeg.js +203 -0
  155. package/dist/chunk-8a1q7y7t.js +38 -0
  156. package/dist/chunk-8b9j5s4r.js +22 -0
  157. package/dist/chunk-8g5pe1gr.js +37 -0
  158. package/dist/chunk-8h45f69y.js +151 -0
  159. package/dist/chunk-8henn231.js +63 -0
  160. package/dist/chunk-8jprqan8.js +1580 -0
  161. package/dist/chunk-8pn8tvgg.js +637 -0
  162. package/dist/chunk-8psrvmy6.js +797 -0
  163. package/dist/chunk-8sq45snx.js +1585 -0
  164. package/dist/chunk-8tj3ttfr.js +122 -0
  165. package/dist/chunk-8tnsngw2.js +31 -0
  166. package/dist/chunk-8y12jxg8.js +10 -0
  167. package/dist/chunk-8ymf4e6z.js +48 -0
  168. package/dist/chunk-8yrcxv0n.js +17 -0
  169. package/dist/chunk-90wp6wez.js +10510 -0
  170. package/dist/chunk-92cm1qp0.js +387 -0
  171. package/dist/chunk-95g4wtbk.js +83 -0
  172. package/dist/chunk-95h99qt5.js +350 -0
  173. package/dist/chunk-9663bsk0.js +15 -0
  174. package/dist/chunk-96mf19ww.js +130 -0
  175. package/dist/chunk-97kwfkef.js +172626 -0
  176. package/dist/chunk-9d4wp328.js +121 -0
  177. package/dist/chunk-9h9j6e8f.js +340 -0
  178. package/dist/chunk-9k8qsaph.js +33068 -0
  179. package/dist/chunk-9mfbqw9k.js +24 -0
  180. package/dist/chunk-9n6x41fh.js +89 -0
  181. package/dist/chunk-9nsdc461.js +43 -0
  182. package/dist/chunk-9nyem167.js +68 -0
  183. package/dist/chunk-9q3r5pd2.js +80 -0
  184. package/dist/chunk-9wf38cty.js +83 -0
  185. package/dist/chunk-9x5zgy22.js +12 -0
  186. package/dist/chunk-a136cvvz.js +27 -0
  187. package/dist/chunk-a4twdmhf.js +45 -0
  188. package/dist/chunk-a53syfz4.js +348 -0
  189. package/dist/chunk-a783nmpc.js +240 -0
  190. package/dist/chunk-a8ejc632.js +3094 -0
  191. package/dist/chunk-a9vdeb6y.js +258 -0
  192. package/dist/chunk-a9zh40sj.js +48 -0
  193. package/dist/chunk-ae76ded0.js +30 -0
  194. package/dist/chunk-akdsj21e.js +37 -0
  195. package/dist/chunk-ase86y73.js +15 -0
  196. package/dist/chunk-avb9ff81.js +98 -0
  197. package/dist/chunk-ayydhscx.js +26 -0
  198. package/dist/chunk-az3db85f.js +301 -0
  199. package/dist/chunk-az7hwp39.js +111 -0
  200. package/dist/chunk-b4wg70y1.js +54 -0
  201. package/dist/chunk-b81hd3m6.js +32 -0
  202. package/dist/chunk-ba17dx50.js +30 -0
  203. package/dist/chunk-bcfd2zw7.js +20 -0
  204. package/dist/chunk-bcv6qax7.js +32 -0
  205. package/dist/chunk-bef1t5q0.js +1460 -0
  206. package/dist/chunk-bend4tmg.js +208 -0
  207. package/dist/chunk-bhxz6rzk.js +475 -0
  208. package/dist/chunk-bj6k61m9.js +130 -0
  209. package/dist/chunk-bnrctxq5.js +112 -0
  210. package/dist/chunk-bt64sq5y.js +19 -0
  211. package/dist/chunk-bxcfz5gy.js +56 -0
  212. package/dist/chunk-c11k4btd.js +1095 -0
  213. package/dist/chunk-c3eaj3gr.js +2997 -0
  214. package/dist/chunk-c51ns2ke.js +40 -0
  215. package/dist/chunk-c5kags80.js +141 -0
  216. package/dist/chunk-c6sjhj89.js +1284 -0
  217. package/dist/chunk-c77cvfqz.js +14 -0
  218. package/dist/chunk-cb68zyey.js +117 -0
  219. package/dist/chunk-cczpp302.js +223 -0
  220. package/dist/chunk-ce2v5y9y.js +338 -0
  221. package/dist/chunk-cfv996bs.js +22 -0
  222. package/dist/chunk-cgfdkzhb.js +12 -0
  223. package/dist/chunk-cj3ptgbw.js +918 -0
  224. package/dist/chunk-ck22v5n3.js +2745 -0
  225. package/dist/chunk-ck4be14j.js +8588 -0
  226. package/dist/chunk-cmwfcp4h.js +120 -0
  227. package/dist/chunk-cnsj3vq2.js +35 -0
  228. package/dist/chunk-cnvsytvx.js +182 -0
  229. package/dist/chunk-cp1aqm3d.js +66 -0
  230. package/dist/chunk-cpgjt97m.js +126 -0
  231. package/dist/chunk-cqrdcwc6.js +115 -0
  232. package/dist/chunk-crmjpsqe.js +68 -0
  233. package/dist/chunk-ctya0ggm.js +1606 -0
  234. package/dist/chunk-cvkzqcxn.js +26 -0
  235. package/dist/chunk-d4mdda98.js +94 -0
  236. package/dist/chunk-d8vwvym7.js +693 -0
  237. package/dist/chunk-d8xwx5h7.js +431 -0
  238. package/dist/chunk-dgepe1tj.js +557 -0
  239. package/dist/chunk-dggvswz1.js +104 -0
  240. package/dist/chunk-dgqrcy74.js +48 -0
  241. package/dist/chunk-dhgfme5s.js +622 -0
  242. package/dist/chunk-dkzwgrsa.js +336 -0
  243. package/dist/chunk-dmfnhfbm.js +63 -0
  244. package/dist/chunk-dnh7jtpb.js +37 -0
  245. package/dist/chunk-drtj50ge.js +112 -0
  246. package/dist/chunk-dtj6da60.js +173 -0
  247. package/dist/chunk-e3jdmhj3.js +122 -0
  248. package/dist/chunk-e5ey47fq.js +78 -0
  249. package/dist/chunk-ehtwnxpg.js +1591 -0
  250. package/dist/chunk-enz148g9.js +79 -0
  251. package/dist/chunk-eq5csq9z.js +147 -0
  252. package/dist/chunk-eqp1rfft.js +17 -0
  253. package/dist/chunk-ers3hn71.js +58 -0
  254. package/dist/chunk-evs073nf.js +9300 -0
  255. package/dist/chunk-ew2qn2ct.js +128 -0
  256. package/dist/chunk-ewadzrm8.js +103 -0
  257. package/dist/chunk-ewhxrzr7.js +282 -0
  258. package/dist/chunk-f076572y.js +29 -0
  259. package/dist/chunk-f1fd8rrx.js +458 -0
  260. package/dist/chunk-f2mhrmww.js +62 -0
  261. package/dist/chunk-f2rspz95.js +661 -0
  262. package/dist/chunk-f4evkbn3.js +109 -0
  263. package/dist/chunk-f5ma3nh5.js +3436 -0
  264. package/dist/chunk-f77bmbss.js +262 -0
  265. package/dist/chunk-fafwc5w7.js +63 -0
  266. package/dist/chunk-fas0j37w.js +206 -0
  267. package/dist/chunk-fbv4apne.js +51 -0
  268. package/dist/chunk-fbvwrs77.js +74 -0
  269. package/dist/chunk-feyzykye.js +10 -0
  270. package/dist/chunk-fk80f449.js +29032 -0
  271. package/dist/chunk-fqz39wqc.js +2754 -0
  272. package/dist/chunk-fs870v81.js +321 -0
  273. package/dist/chunk-fvrd2wnw.js +119 -0
  274. package/dist/chunk-fwqpwb0b.js +68 -0
  275. package/dist/chunk-fyc5fepv.js +10 -0
  276. package/dist/chunk-fz0ch109.js +329 -0
  277. package/dist/chunk-fzsn5y4x.js +74 -0
  278. package/dist/chunk-g1k68z1b.js +15 -0
  279. package/dist/chunk-g338npwr.js +1061 -0
  280. package/dist/chunk-g4mn27j2.js +125 -0
  281. package/dist/chunk-g5k4zxrz.js +285 -0
  282. package/dist/chunk-g7hbj02n.js +47 -0
  283. package/dist/chunk-g9f19ttm.js +15 -0
  284. package/dist/chunk-gmpnr1zb.js +248 -0
  285. package/dist/chunk-gnsx2xas.js +58 -0
  286. package/dist/chunk-gr2j2pnw.js +449 -0
  287. package/dist/chunk-gs8skfag.js +700 -0
  288. package/dist/chunk-gte39pa1.js +62 -0
  289. package/dist/chunk-gvee52bj.js +41 -0
  290. package/dist/chunk-gzvt7jsh.js +109 -0
  291. package/dist/chunk-gzykgb04.js +445 -0
  292. package/dist/chunk-h0qngp9w.js +157 -0
  293. package/dist/chunk-h4b85amj.js +2331 -0
  294. package/dist/chunk-h5w7hchy.js +851 -0
  295. package/dist/chunk-hakdhagh.js +16606 -0
  296. package/dist/chunk-hamq5sbn.js +398 -0
  297. package/dist/chunk-hezhnvr6.js +369 -0
  298. package/dist/chunk-hh7cmy4k.js +20 -0
  299. package/dist/chunk-hhgyxd84.js +259 -0
  300. package/dist/chunk-hk9xz7gk.js +118 -0
  301. package/dist/chunk-hkn7tzgv.js +2007 -0
  302. package/dist/chunk-hnafabz8.js +266 -0
  303. package/dist/chunk-hqhmy4sg.js +4181 -0
  304. package/dist/chunk-hvdbzsar.js +127 -0
  305. package/dist/chunk-hzhe8ygc.js +547 -0
  306. package/dist/chunk-j05addbw.js +132 -0
  307. package/dist/chunk-j2k4p94p.js +55 -0
  308. package/dist/chunk-j3a4p81y.js +184 -0
  309. package/dist/chunk-j5bth84e.js +97 -0
  310. package/dist/chunk-j64ga6ta.js +8035 -0
  311. package/dist/chunk-j7e5xs2n.js +225 -0
  312. package/dist/chunk-j9gxwbe3.js +349 -0
  313. package/dist/chunk-jaaxk89e.js +113 -0
  314. package/dist/chunk-jbe9jra5.js +132 -0
  315. package/dist/chunk-jd32zbps.js +15 -0
  316. package/dist/chunk-jdgeec04.js +4249 -0
  317. package/dist/chunk-jhvzhfs0.js +61 -0
  318. package/dist/chunk-jmczk6av.js +173 -0
  319. package/dist/chunk-jmmy2389.js +146 -0
  320. package/dist/chunk-jmt3t5ka.js +655 -0
  321. package/dist/chunk-jnhkref0.js +30 -0
  322. package/dist/chunk-jrw2ydrt.js +122 -0
  323. package/dist/chunk-jwrvnvn4.js +40 -0
  324. package/dist/chunk-jzmz18nn.js +65 -0
  325. package/dist/chunk-k04vbmv4.js +646 -0
  326. package/dist/chunk-k0p9w03v.js +4957 -0
  327. package/dist/chunk-k3dhz0k9.js +135 -0
  328. package/dist/chunk-k3s4yk22.js +477 -0
  329. package/dist/chunk-k9ssqns7.js +32 -0
  330. package/dist/chunk-kadfnk84.js +182 -0
  331. package/dist/chunk-kddy2dqe.js +251 -0
  332. package/dist/chunk-kfd89dsd.js +21 -0
  333. package/dist/chunk-kqnj25tn.js +6956 -0
  334. package/dist/chunk-kt7g00mq.js +435 -0
  335. package/dist/chunk-kwdta9bw.js +3437 -0
  336. package/dist/chunk-kwekc97v.js +18 -0
  337. package/dist/chunk-kyqp0hdk.js +410 -0
  338. package/dist/chunk-m19387gd.js +192 -0
  339. package/dist/chunk-m1k6c44h.js +97 -0
  340. package/dist/chunk-m2bcpk8j.js +30 -0
  341. package/dist/chunk-m2f2brtj.js +290 -0
  342. package/dist/chunk-m3vd4kjb.js +895 -0
  343. package/dist/chunk-m4y35n20.js +2845 -0
  344. package/dist/chunk-m53f3dw3.js +237 -0
  345. package/dist/chunk-m7e9yz7v.js +112 -0
  346. package/dist/chunk-m7gb3xym.js +196 -0
  347. package/dist/chunk-m85hmjj5.js +446 -0
  348. package/dist/chunk-mafty4rg.js +30 -0
  349. package/dist/chunk-mbgrtfd1.js +67 -0
  350. package/dist/chunk-mc9gapvy.js +1811 -0
  351. package/dist/chunk-md75xjhp.js +283 -0
  352. package/dist/chunk-mdkxrfbj.js +666 -0
  353. package/dist/chunk-mfq8d0nf.js +126 -0
  354. package/dist/chunk-mg4j7qa1.js +192 -0
  355. package/dist/chunk-mjnb2hkr.js +132 -0
  356. package/dist/chunk-mnc0y0d0.js +190 -0
  357. package/dist/chunk-mpvn2d5c.js +155 -0
  358. package/dist/chunk-mr2kw49k.js +116 -0
  359. package/dist/chunk-ms3y5kf0.js +252 -0
  360. package/dist/chunk-mwz7he7v.js +169 -0
  361. package/dist/chunk-mx28h61f.js +1147 -0
  362. package/dist/chunk-my3kzsjn.js +99 -0
  363. package/dist/chunk-n0a4xh5h.js +128 -0
  364. package/dist/chunk-n0qaeaa5.js +256 -0
  365. package/dist/chunk-n24pwjkp.js +139 -0
  366. package/dist/chunk-n2qz0nhv.js +93 -0
  367. package/dist/chunk-n7d8481f.js +68 -0
  368. package/dist/chunk-n7ttdtk0.js +641 -0
  369. package/dist/chunk-n9axs6t8.js +716 -0
  370. package/dist/chunk-netzwgv1.js +154 -0
  371. package/dist/chunk-nh3cd07f.js +14358 -0
  372. package/dist/chunk-njhgsxjj.js +237 -0
  373. package/dist/chunk-nk5x8t2h.js +132 -0
  374. package/dist/chunk-nka1g8f4.js +773 -0
  375. package/dist/chunk-nneembm7.js +31 -0
  376. package/dist/chunk-nq0fxyxh.js +752 -0
  377. package/dist/chunk-nt837qt9.js +21 -0
  378. package/dist/chunk-p0ng6w7n.js +315 -0
  379. package/dist/chunk-p1e5ajm6.js +90 -0
  380. package/dist/chunk-p2816w9z.js +1486 -0
  381. package/dist/chunk-p2d5nh3g.js +342 -0
  382. package/dist/chunk-p3a8pcmp.js +780 -0
  383. package/dist/chunk-p5rg8b87.js +157 -0
  384. package/dist/chunk-p7vkh4wx.js +15 -0
  385. package/dist/chunk-p99pzx02.js +65 -0
  386. package/dist/chunk-p9ce1a80.js +279 -0
  387. package/dist/chunk-pakvqawt.js +2544 -0
  388. package/dist/chunk-pfc94kdv.js +5387 -0
  389. package/dist/chunk-pfnzae5b.js +71 -0
  390. package/dist/chunk-pgyrvzpr.js +862 -0
  391. package/dist/chunk-pj77mrv7.js +879 -0
  392. package/dist/chunk-pk3s1vqt.js +136 -0
  393. package/dist/chunk-ppwjyveh.js +8 -0
  394. package/dist/chunk-ps1ds612.js +183 -0
  395. package/dist/chunk-ps49ymvj.js +43 -0
  396. package/dist/chunk-pshjyzq4.js +17656 -0
  397. package/dist/chunk-pskjqhz7.js +116 -0
  398. package/dist/chunk-pvc81kgd.js +1030 -0
  399. package/dist/chunk-pwwa7s62.js +11 -0
  400. package/dist/chunk-q3j9ktw6.js +313 -0
  401. package/dist/chunk-q4t5gjz6.js +180 -0
  402. package/dist/chunk-q7tpyeb3.js +39 -0
  403. package/dist/chunk-q82r31er.js +151 -0
  404. package/dist/chunk-qajrkk97.js +298 -0
  405. package/dist/chunk-qb6ej6am.js +118 -0
  406. package/dist/chunk-qbrsmra3.js +23 -0
  407. package/dist/chunk-qezabsdm.js +65 -0
  408. package/dist/chunk-qfdazq4f.js +81 -0
  409. package/dist/chunk-qjb5b625.js +382 -0
  410. package/dist/chunk-qjeytdb7.js +47 -0
  411. package/dist/chunk-qkn19vqd.js +116 -0
  412. package/dist/chunk-qnfx3qtx.js +617 -0
  413. package/dist/chunk-qp1047f9.js +16239 -0
  414. package/dist/chunk-qp2qdcda.js +100 -0
  415. package/dist/chunk-qtfc6wdh.js +19 -0
  416. package/dist/chunk-qvpvpfby.js +4951 -0
  417. package/dist/chunk-qwcs5mar.js +151 -0
  418. package/dist/chunk-qywms8ma.js +84 -0
  419. package/dist/chunk-qz2x630m.js +49145 -0
  420. package/dist/chunk-r1c1vckq.js +606 -0
  421. package/dist/chunk-r1cmrvhq.js +660 -0
  422. package/dist/chunk-r4w1khtr.js +479 -0
  423. package/dist/chunk-r5c7ntjh.js +308 -0
  424. package/dist/chunk-r6pqswky.js +118 -0
  425. package/dist/chunk-rcpmj2s6.js +51 -0
  426. package/dist/chunk-re5rh06v.js +151 -0
  427. package/dist/chunk-reta5k4w.js +127 -0
  428. package/dist/chunk-rfpx3se2.js +114 -0
  429. package/dist/chunk-rfzv16n9.js +140 -0
  430. package/dist/chunk-rhq6rjsm.js +139 -0
  431. package/dist/chunk-rn0v1hk8.js +34 -0
  432. package/dist/chunk-rpmxbsc4.js +106 -0
  433. package/dist/chunk-rw0b3wq4.js +54 -0
  434. package/dist/chunk-rwg99z4w.js +277 -0
  435. package/dist/chunk-rzz2be44.js +144 -0
  436. package/dist/chunk-s1pwx4p8.js +1029 -0
  437. package/dist/chunk-s2jznn2t.js +63 -0
  438. package/dist/chunk-s3pzvdss.js +50 -0
  439. package/dist/chunk-s5hrc81b.js +256 -0
  440. package/dist/chunk-s6zh6vsc.js +115 -0
  441. package/dist/chunk-sac40vch.js +41 -0
  442. package/dist/chunk-sd36yzx8.js +954 -0
  443. package/dist/chunk-sd6tyy2k.js +445 -0
  444. package/dist/chunk-sg9s9fhh.js +220 -0
  445. package/dist/chunk-st29kcjw.js +70 -0
  446. package/dist/chunk-szj5wvdy.js +28 -0
  447. package/dist/chunk-tazmxz0r.js +115 -0
  448. package/dist/chunk-tbbgpakn.js +352 -0
  449. package/dist/chunk-tbjjq4ry.js +70 -0
  450. package/dist/chunk-tezak8rx.js +6157 -0
  451. package/dist/chunk-tf79jran.js +15 -0
  452. package/dist/chunk-tg8bdmhy.js +148 -0
  453. package/dist/chunk-thjjw26s.js +369 -0
  454. package/dist/chunk-tq1ak9qz.js +3594 -0
  455. package/dist/chunk-tqvxvgcq.js +390 -0
  456. package/dist/chunk-ts2p6bv1.js +224 -0
  457. package/dist/chunk-tsmzsjkv.js +167 -0
  458. package/dist/chunk-ttk5dzz8.js +25 -0
  459. package/dist/chunk-v1kzp02e.js +785 -0
  460. package/dist/chunk-v4rp12y4.js +269 -0
  461. package/dist/chunk-v4t6dyyh.js +9076 -0
  462. package/dist/chunk-v78fj8by.js +145 -0
  463. package/dist/chunk-v9smspw2.js +4301 -0
  464. package/dist/chunk-var1et7e.js +66 -0
  465. package/dist/chunk-vest0y6x.js +3830 -0
  466. package/dist/chunk-vf5sd1nq.js +12 -0
  467. package/dist/chunk-vf612n57.js +472 -0
  468. package/dist/chunk-vhqtr0f1.js +343 -0
  469. package/dist/chunk-vnfempy5.js +43 -0
  470. package/dist/chunk-vp5pr5yv.js +443 -0
  471. package/dist/chunk-vp8cvspq.js +157 -0
  472. package/dist/chunk-vqqtdc8s.js +75 -0
  473. package/dist/chunk-vyjeh50y.js +2149 -0
  474. package/dist/chunk-w0nwhqww.js +295 -0
  475. package/dist/chunk-w32xjs44.js +306 -0
  476. package/dist/chunk-w4mdb23d.js +111 -0
  477. package/dist/chunk-w5j84xcj.js +226 -0
  478. package/dist/chunk-w78f4cd8.js +158 -0
  479. package/dist/chunk-wbpxzaty.js +66 -0
  480. package/dist/chunk-wfz0qffj.js +3939 -0
  481. package/dist/chunk-wm26jyc3.js +156 -0
  482. package/dist/chunk-wmw9c9ga.js +440 -0
  483. package/dist/chunk-wpp8s8bh.js +433 -0
  484. package/dist/chunk-wrb0tqk3.js +198 -0
  485. package/dist/chunk-wswsvthr.js +946 -0
  486. package/dist/chunk-wzpdet3m.js +843 -0
  487. package/dist/chunk-x1pmes5j.js +482 -0
  488. package/dist/chunk-x6r4v44b.js +8 -0
  489. package/dist/chunk-x92g7cqn.js +421 -0
  490. package/dist/chunk-xedf6d09.js +66 -0
  491. package/dist/chunk-xgwhhpvz.js +154 -0
  492. package/dist/chunk-xkxd7n8n.js +310 -0
  493. package/dist/chunk-xrt6e27s.js +60 -0
  494. package/dist/chunk-xsq9ae7x.js +90 -0
  495. package/dist/chunk-xv3era3s.js +8 -0
  496. package/dist/chunk-xwz1db00.js +34 -0
  497. package/dist/chunk-xx0570gb.js +120 -0
  498. package/dist/chunk-xxshn0tn.js +314 -0
  499. package/dist/chunk-xzc7k2hh.js +122 -0
  500. package/dist/chunk-y1784krc.js +19 -0
  501. package/dist/chunk-y2hdgkmv.js +244 -0
  502. package/dist/chunk-y82j1dne.js +524 -0
  503. package/dist/chunk-ybae225f.js +669 -0
  504. package/dist/chunk-ye7fmmc4.js +95 -0
  505. package/dist/chunk-ygj29dpk.js +100 -0
  506. package/dist/chunk-yj2t6a2t.js +216 -0
  507. package/dist/chunk-yja33bsx.js +300 -0
  508. package/dist/chunk-yjkamwzv.js +121 -0
  509. package/dist/chunk-ymjz2by8.js +120 -0
  510. package/dist/chunk-yqtda7b6.js +105 -0
  511. package/dist/chunk-yqx2fkma.js +2362 -0
  512. package/dist/chunk-yzx3mhfd.js +110 -0
  513. package/dist/chunk-z1bs6d7k.js +24 -0
  514. package/dist/chunk-z2dp53wn.js +17 -0
  515. package/dist/chunk-z6e5jp2w.js +119 -0
  516. package/dist/chunk-z915v06p.js +148 -0
  517. package/dist/chunk-ze6zvkg6.js +22820 -0
  518. package/dist/chunk-zejm280k.js +39 -0
  519. package/dist/chunk-zeytvkxt.js +142 -0
  520. package/dist/chunk-zgjh33vv.js +276 -0
  521. package/dist/chunk-zgncjtyk.js +264 -0
  522. package/dist/chunk-zmgzhwae.js +4389 -0
  523. package/dist/chunk-ztf1hdpb.js +456 -0
  524. package/dist/chunk-zzm33q8x.js +8 -0
  525. package/dist/cli.js +139 -0
  526. package/dist/download-ripgrep.js +24821 -0
  527. package/dist/vendor/audio-capture/arm64-darwin/audio-capture.node +0 -0
  528. package/dist/vendor/audio-capture/arm64-linux/audio-capture.node +0 -0
  529. package/dist/vendor/audio-capture/arm64-win32/audio-capture.node +0 -0
  530. package/dist/vendor/audio-capture/x64-darwin/audio-capture.node +0 -0
  531. package/dist/vendor/audio-capture/x64-linux/audio-capture.node +0 -0
  532. package/dist/vendor/audio-capture/x64-win32/audio-capture.node +0 -0
  533. package/package.json +177 -0
  534. package/scripts/download-ripgrep.ts +335 -0
  535. package/scripts/postinstall.cjs +319 -0
@@ -0,0 +1,4951 @@
1
+ // @bun
2
+ import {
3
+ StructuredIO,
4
+ buildSystemInitMessage,
5
+ exports_MessageSelector,
6
+ exports_cronJitterConfig,
7
+ exports_cronScheduler,
8
+ extractInboundMessageFields,
9
+ init_MessageSelector,
10
+ init_cronJitterConfig,
11
+ init_cronScheduler,
12
+ ndjsonSafeStringify,
13
+ outputSchema,
14
+ permissionPromptToolResultToPermissionDecision,
15
+ processUserInput,
16
+ reconcileMarketplaces,
17
+ sdkCompatToolName
18
+ } from "./chunk-c3eaj3gr.js";
19
+ import {
20
+ restoreAgentFromSession,
21
+ restoreSessionStateFromLog,
22
+ skillChangeDetector
23
+ } from "./chunk-f1fd8rrx.js";
24
+ import {
25
+ detectAndUninstallDelistedPlugins
26
+ } from "./chunk-9n6x41fh.js";
27
+ import"./chunk-kadfnk84.js";
28
+ import {
29
+ externalMetadataToAppState
30
+ } from "./chunk-e3jdmhj3.js";
31
+ import {
32
+ getSessionState,
33
+ notifySessionMetadataChanged,
34
+ notifySessionStateChanged,
35
+ setPermissionModeChangedListener,
36
+ setSessionMetadataChangedListener,
37
+ setSessionStateChangedListener
38
+ } from "./chunk-2s460rgh.js";
39
+ import {
40
+ HybridTransport,
41
+ WebSocketTransport
42
+ } from "./chunk-d8vwvym7.js";
43
+ import {
44
+ CCRClient,
45
+ CCRInitError
46
+ } from "./chunk-7ethp9j4.js";
47
+ import"./chunk-nt837qt9.js";
48
+ import {
49
+ resolveAndPrepend
50
+ } from "./chunk-zeytvkxt.js";
51
+ import {
52
+ getPollIntervalConfig
53
+ } from "./chunk-fafwc5w7.js";
54
+ import"./chunk-xgwhhpvz.js";
55
+ import {
56
+ SSETransport,
57
+ init_SSETransport
58
+ } from "./chunk-m85hmjj5.js";
59
+ import {
60
+ init_settingsSync
61
+ } from "./chunk-p1e5ajm6.js";
62
+ import {
63
+ init_refresh,
64
+ refreshActivePlugins
65
+ } from "./chunk-0h5jp1k7.js";
66
+ import {
67
+ init_toolPool,
68
+ mergeAndFilterTools
69
+ } from "./chunk-k9ssqns7.js";
70
+ import"./chunk-1rvwfjaq.js";
71
+ import {
72
+ init_mappers,
73
+ localCommandOutputToSDKAssistantMessage,
74
+ toInternalMessages,
75
+ toSDKCompactMetadata,
76
+ toSDKRateLimitInfo
77
+ } from "./chunk-5c5xde65.js";
78
+ import {
79
+ generateSessionTitle,
80
+ init_sessionTitle
81
+ } from "./chunk-nk5x8t2h.js";
82
+ import {
83
+ init_systemTheme,
84
+ resolveThemeSetting
85
+ } from "./chunk-cnsj3vq2.js";
86
+ import {
87
+ ChannelMessageNotificationSchema,
88
+ findChannelEntry,
89
+ gateChannelServer,
90
+ init_channelAllowlist,
91
+ init_channelNotification,
92
+ init_omit,
93
+ omit_default,
94
+ wrapChannelMessage
95
+ } from "./chunk-6x0hj15f.js";
96
+ import"./chunk-k04vbmv4.js";
97
+ import"./chunk-bend4tmg.js";
98
+ import {
99
+ collectContextData,
100
+ init_context_noninteractive
101
+ } from "./chunk-3ng1qsw3.js";
102
+ import {
103
+ init_sideQuestion,
104
+ runSideQuestion
105
+ } from "./chunk-avb9ff81.js";
106
+ import"./chunk-rn0v1hk8.js";
107
+ import {
108
+ DEFAULT_OUTPUT_STYLE_NAME,
109
+ EFFORT_LEVELS,
110
+ OAuthService,
111
+ SHELL_TOOL_NAMES,
112
+ SYNTHETIC_MESSAGES,
113
+ SYNTHETIC_OUTPUT_TOOL_NAME,
114
+ SandboxManager,
115
+ accumulateUsage,
116
+ applySettingsChange,
117
+ areMcpConfigsEqual,
118
+ asSessionId,
119
+ asSystemPrompt,
120
+ assembleToolPool,
121
+ atomicWriteToZipCache,
122
+ buildBridgeConnectUrl,
123
+ categorizeRetryableAPIError,
124
+ checkGroveForNonInteractive,
125
+ cleanupSessionPluginCache,
126
+ clearCommandsCache,
127
+ clearMarketplacesCache,
128
+ clearPluginCache,
129
+ clearServerCache,
130
+ commandBelongsToServer,
131
+ connectToServer,
132
+ countToolCalls,
133
+ createAbortController,
134
+ createCombinedAbortSignal,
135
+ createModelSwitchBreadcrumbs,
136
+ createSyntheticOutputTool,
137
+ dequeue,
138
+ dequeueAllMatching,
139
+ doesMessageExistInSession,
140
+ drainSdkEvents,
141
+ enqueue,
142
+ executeNotificationHooks,
143
+ exports_extractMemories,
144
+ exports_prompt,
145
+ extractReadFilesFromMessages,
146
+ fetchToolsForClient,
147
+ fileHistoryCanRestore,
148
+ fileHistoryEnabled,
149
+ fileHistoryGetDiffStats,
150
+ fileHistoryMakeSnapshot,
151
+ fileHistoryRewind,
152
+ filterMcpServersByPolicy,
153
+ filterToolsByDenyRules,
154
+ filterToolsByServer,
155
+ finalizePendingAsyncHooks,
156
+ findUnresolvedToolUse,
157
+ flushSessionStorage,
158
+ formatDescriptionWithSource,
159
+ fromArray,
160
+ getAllMcpConfigs,
161
+ getAllOutputStyles,
162
+ getAutoModeUnavailableNotification,
163
+ getAutoModeUnavailableReason,
164
+ getCommandName,
165
+ getCommands,
166
+ getCommandsByMaxPriority,
167
+ getDeclaredMarketplaces,
168
+ getLastCacheSafeParams,
169
+ getMarketplaceJsonRelativePath,
170
+ getMcpConfigByName,
171
+ getModelOptions,
172
+ getPluginZipCachePath,
173
+ getRemoteSessionUrl,
174
+ getRunningTasks,
175
+ getScratchpadDir,
176
+ getSlashCommandToolSkills,
177
+ getSystemContext,
178
+ getSystemPrompt,
179
+ getUserContext,
180
+ getZipCacheKnownMarketplacesPath,
181
+ getZipCacheMarketplacesDir,
182
+ getZipCachePluginsDir,
183
+ gracefulShutdown,
184
+ gracefulShutdownSync,
185
+ handleOrphanedPermission,
186
+ hasCommandsInQueue,
187
+ hasPermissionsToUseTool,
188
+ headlessProfilerCheckpoint,
189
+ headlessProfilerStartTurn,
190
+ hydrateFromCCRv2InternalEvents,
191
+ hydrateRemoteSession,
192
+ init_AsyncHookRegistry,
193
+ init_Shell,
194
+ init_SyntheticOutputTool,
195
+ init_Tool,
196
+ init_abortController,
197
+ init_applySettingsChange,
198
+ init_auth as init_auth2,
199
+ init_auth1 as init_auth3,
200
+ init_bridgeStatusUtil,
201
+ init_changeDetector,
202
+ init_claude,
203
+ init_claudeAiLimits,
204
+ init_client,
205
+ init_combinedAbortSignal,
206
+ init_commandLifecycle,
207
+ init_commands1 as init_commands,
208
+ init_config as init_config2,
209
+ init_constants,
210
+ init_constants1 as init_constants2,
211
+ init_context,
212
+ init_conversationRecovery,
213
+ init_cost_tracker,
214
+ init_effort,
215
+ init_elicitationHandler,
216
+ init_errors as init_errors2,
217
+ init_extractMemories,
218
+ init_fileHistory,
219
+ init_filesApi,
220
+ init_filesystem,
221
+ init_forkedAgent,
222
+ init_framework,
223
+ init_generators,
224
+ init_gracefulShutdown,
225
+ init_grove,
226
+ init_headlessProfiler,
227
+ init_hookEvents,
228
+ init_hookHelpers,
229
+ init_hooks1 as init_hooks,
230
+ init_ids,
231
+ init_last,
232
+ init_loadAgentsDir,
233
+ init_logging,
234
+ init_marketplaceManager,
235
+ init_memdir,
236
+ init_messageQueueManager,
237
+ init_messages1 as init_messages,
238
+ init_modelOptions,
239
+ init_oauth,
240
+ init_outputStyles,
241
+ init_outputsScanner,
242
+ init_permissionSetup,
243
+ init_permissions,
244
+ init_pluginIdentifier,
245
+ init_pluginLoader,
246
+ init_policyLimits,
247
+ init_product,
248
+ init_prompt as init_prompt2,
249
+ init_prompt1 as init_prompt3,
250
+ init_prompt10 as init_prompt8,
251
+ init_prompt11 as init_prompt9,
252
+ init_prompt2 as init_prompt4,
253
+ init_prompt3 as init_prompt5,
254
+ init_prompt5 as init_prompt6,
255
+ init_prompt9 as init_prompt7,
256
+ init_promptSuggestion,
257
+ init_prompts1 as init_prompts,
258
+ init_query,
259
+ init_queryHelpers,
260
+ init_queryProfiler,
261
+ init_reject,
262
+ init_remoteManagedSettings,
263
+ init_sandbox_adapter,
264
+ init_sdkEventQueue,
265
+ init_sessionStart,
266
+ init_sessionStorage,
267
+ init_shellToolUtils,
268
+ init_stopTask,
269
+ init_systemPromptType,
270
+ init_teammateMailbox,
271
+ init_thinking,
272
+ init_tools1 as init_tools,
273
+ init_types1 as init_types2,
274
+ init_uniqBy,
275
+ init_utils,
276
+ init_uuid,
277
+ init_vscodeSdkMcp,
278
+ init_zipCache,
279
+ installOAuthTokens,
280
+ isAutoModeGateEnabled,
281
+ isBackgroundTask,
282
+ isBuiltInAgent,
283
+ isBypassPermissionsModeDisabled,
284
+ isMarketplaceSourceSupportedByZipCache,
285
+ isMcpServerDisabled,
286
+ isPluginZipCacheEnabled,
287
+ isPolicyAllowed,
288
+ isQualifiedForGrove,
289
+ isResultSuccessful,
290
+ isScratchpadEnabled,
291
+ isShutdownApproved,
292
+ isShuttingDown,
293
+ last_default,
294
+ loadAllPluginsCacheOnly,
295
+ loadConversationForResume,
296
+ loadKnownMarketplacesConfigSafe,
297
+ loadMemoryPrompt,
298
+ logHeadlessProfilerTurn,
299
+ logQueryProfileReport,
300
+ logSuggestionOutcome,
301
+ logSuggestionSuppressed,
302
+ markMessagesAsRead,
303
+ modelSupportsAdaptiveThinking,
304
+ modelSupportsEffort,
305
+ modelSupportsMaxEffort,
306
+ normalizeMessage,
307
+ notifyCommandLifecycle,
308
+ parseAgentsFromJson,
309
+ parsePluginIdentifier,
310
+ peek,
311
+ performMCPOAuthFlow,
312
+ processSessionStartHooks,
313
+ processSetupHooks,
314
+ query,
315
+ readUnreadMessages,
316
+ reconnectMcpServerImpl,
317
+ recordTranscript,
318
+ registerHookEventHandler,
319
+ registerSeedMarketplaces,
320
+ registerStructuredOutputEnforcement,
321
+ reject_default,
322
+ resetSessionFilePointer,
323
+ resolveAppliedEffort,
324
+ restoreSessionMetadata,
325
+ revokeServerTokens,
326
+ runElicitationHooks,
327
+ runElicitationResultHooks,
328
+ saveAgentSetting,
329
+ saveAiGeneratedTitle,
330
+ setCommandLifecycleListener,
331
+ setCwd,
332
+ setInternalEventReader,
333
+ setInternalEventWriter,
334
+ setMcpServerEnabled,
335
+ settingsChangeDetector,
336
+ setupSdkMcpClients,
337
+ setupVscodeSdkMcp,
338
+ shouldEnableThinkingByDefault,
339
+ startQueryProfile,
340
+ statusListeners,
341
+ stopTask,
342
+ subscribeToCommandQueue,
343
+ takeInitialUserMessage,
344
+ toolMatchesName,
345
+ transitionPermissionMode,
346
+ tryGenerateSuggestion,
347
+ uniqBy_default,
348
+ updateUsage,
349
+ validateUuid,
350
+ waitForRemoteManagedSettingsToLoad
351
+ } from "./chunk-97kwfkef.js";
352
+ import"./chunk-4nspekjp.js";
353
+ import"./chunk-s2jznn2t.js";
354
+ import"./chunk-zejm280k.js";
355
+ import"./chunk-var1et7e.js";
356
+ import"./chunk-ehtwnxpg.js";
357
+ import"./chunk-enz148g9.js";
358
+ import {
359
+ init_commitAttribution
360
+ } from "./chunk-jmt3t5ka.js";
361
+ import {
362
+ EMPTY_USAGE,
363
+ getSessionIngressAuthToken,
364
+ init_sessionIngressAuth
365
+ } from "./chunk-3x2jaxpw.js";
366
+ import"./chunk-wm26jyc3.js";
367
+ import"./chunk-2gzv8nrw.js";
368
+ import"./chunk-bxcfz5gy.js";
369
+ import {
370
+ init_tasks,
371
+ init_teamHelpers,
372
+ removeTeammateFromTeamFile,
373
+ unassignTeammateTasks
374
+ } from "./chunk-3vxgde8h.js";
375
+ import"./chunk-9k8qsaph.js";
376
+ import"./chunk-bnrctxq5.js";
377
+ import"./chunk-9663bsk0.js";
378
+ import"./chunk-cgfdkzhb.js";
379
+ import"./chunk-gr2j2pnw.js";
380
+ import"./chunk-m7gb3xym.js";
381
+ import"./chunk-zgjh33vv.js";
382
+ import {
383
+ READ_FILE_STATE_CACHE_SIZE,
384
+ cloneFileStateCache,
385
+ createFileStateCacheWithSizeLimit,
386
+ init_fileStateCache,
387
+ mergeFileStateCaches
388
+ } from "./chunk-j5bth84e.js";
389
+ import"./chunk-39jcea92.js";
390
+ import"./chunk-reta5k4w.js";
391
+ import"./chunk-3z9478wf.js";
392
+ import"./chunk-ps49ymvj.js";
393
+ import"./chunk-eq5csq9z.js";
394
+ import"./chunk-qezabsdm.js";
395
+ import"./chunk-p7vkh4wx.js";
396
+ import"./chunk-3sj7jkgr.js";
397
+ import"./chunk-62xkxk9z.js";
398
+ import"./chunk-ers3hn71.js";
399
+ import"./chunk-5krq9sjq.js";
400
+ import"./chunk-85em0j2s.js";
401
+ import"./chunk-dmfnhfbm.js";
402
+ import"./chunk-4jm600zv.js";
403
+ import"./chunk-ew2qn2ct.js";
404
+ import"./chunk-3bes9fg8.js";
405
+ import"./chunk-ygj29dpk.js";
406
+ import"./chunk-6km733xr.js";
407
+ import"./chunk-mx28h61f.js";
408
+ import"./chunk-z915v06p.js";
409
+ import"./chunk-rw0b3wq4.js";
410
+ import"./chunk-ms3y5kf0.js";
411
+ import"./chunk-pfc94kdv.js";
412
+ import"./chunk-kwdta9bw.js";
413
+ import"./chunk-3dy7fxmg.js";
414
+ import {
415
+ AwsAuthStatusManager,
416
+ KnownMarketplacesFileSchema,
417
+ TASK_STOP_TOOL_NAME,
418
+ WORKLOAD_CRON,
419
+ ensureModelStringsInitialized,
420
+ getAPIProvider,
421
+ getAccountInformation,
422
+ getDefaultMainLoopModel,
423
+ getFastModeState,
424
+ getFeatureValue_CACHED_MAY_BE_STALE,
425
+ getGlobalConfig,
426
+ getMainLoopModel,
427
+ getMcpPrefix,
428
+ getSettingsWithSources,
429
+ getSettings_DEPRECATED,
430
+ hasAutoMemPathOverride,
431
+ init_auth,
432
+ init_awsAuthStatusManager,
433
+ init_betas1 as init_betas,
434
+ init_config1 as init_config,
435
+ init_fastMode,
436
+ init_growthbook,
437
+ init_mcpStringUtils,
438
+ init_model,
439
+ init_modelStrings,
440
+ init_paths,
441
+ init_prompt,
442
+ init_providers,
443
+ init_schemas,
444
+ init_settings1 as init_settings,
445
+ init_stringUtils,
446
+ init_workloadContext,
447
+ initializeGrowthBook,
448
+ isExtractModeActive,
449
+ isFastModeAvailable,
450
+ isFastModeEnabled,
451
+ isFastModeSupportedByModel,
452
+ modelDisplayString,
453
+ modelSupportsAutoMode,
454
+ parseUserSpecifiedModel,
455
+ runWithWorkload
456
+ } from "./chunk-qp1047f9.js";
457
+ import {
458
+ init_json,
459
+ safeParseJSON
460
+ } from "./chunk-3ns6ys7f.js";
461
+ import {
462
+ expandPath,
463
+ init_path
464
+ } from "./chunk-6aspnjtj.js";
465
+ import"./chunk-1dz5e26z.js";
466
+ import {
467
+ hasActiveInProcessTeammates,
468
+ hasWorkingInProcessTeammates,
469
+ init_array,
470
+ init_teammate,
471
+ isTeamLead,
472
+ uniq,
473
+ waitForTeammatesToBecomeIdle
474
+ } from "./chunk-1cwdhk7a.js";
475
+ import"./chunk-j9gxwbe3.js";
476
+ import"./chunk-64c1avct.js";
477
+ import"./chunk-qbrsmra3.js";
478
+ import {
479
+ init_sleep,
480
+ sleep
481
+ } from "./chunk-8g5pe1gr.js";
482
+ import"./chunk-5j8wked2.js";
483
+ import {
484
+ ElicitRequestSchema,
485
+ ElicitationCompleteNotificationSchema,
486
+ init_types
487
+ } from "./chunk-v4t6dyyh.js";
488
+ import"./chunk-4pbx3g7s.js";
489
+ import"./chunk-26wtxbdc.js";
490
+ import"./chunk-f5ma3nh5.js";
491
+ import"./chunk-qz2x630m.js";
492
+ import"./chunk-xzc7k2hh.js";
493
+ import"./chunk-rcpmj2s6.js";
494
+ import"./chunk-3c25bcsw.js";
495
+ import"./chunk-dkzwgrsa.js";
496
+ import"./chunk-q82r31er.js";
497
+ import"./chunk-p2816w9z.js";
498
+ import"./chunk-v9smspw2.js";
499
+ import"./chunk-v1kzp02e.js";
500
+ import"./chunk-ztf1hdpb.js";
501
+ import"./chunk-crmjpsqe.js";
502
+ import {
503
+ init_strip_ansi,
504
+ stripAnsi
505
+ } from "./chunk-fk80f449.js";
506
+ import"./chunk-g338npwr.js";
507
+ import {
508
+ init_analytics,
509
+ logEvent
510
+ } from "./chunk-f2mhrmww.js";
511
+ import"./chunk-0vkfrmqm.js";
512
+ import"./chunk-0xjaqda8.js";
513
+ import"./chunk-yjkamwzv.js";
514
+ import {
515
+ init_diagLogs,
516
+ logForDiagnosticsNoPII,
517
+ withDiagnosticsTiming
518
+ } from "./chunk-13hhjhs8.js";
519
+ import"./chunk-rpmxbsc4.js";
520
+ import"./chunk-qnfx3qtx.js";
521
+ import"./chunk-2wz9qb4j.js";
522
+ import {
523
+ getCwd,
524
+ init_cwd
525
+ } from "./chunk-b81hd3m6.js";
526
+ import {
527
+ LOCAL_COMMAND_STDERR_TAG,
528
+ LOCAL_COMMAND_STDOUT_TAG,
529
+ TEAMMATE_MESSAGE_TAG,
530
+ getInMemoryErrors,
531
+ init_log,
532
+ init_xml,
533
+ logError,
534
+ logMCPDebug
535
+ } from "./chunk-ce2v5y9y.js";
536
+ import"./chunk-8tnsngw2.js";
537
+ import"./chunk-56r79b2b.js";
538
+ import"./chunk-nneembm7.js";
539
+ import"./chunk-5z28bqne.js";
540
+ import"./chunk-qajrkk97.js";
541
+ import {
542
+ getFsImplementation,
543
+ init_cleanupRegistry,
544
+ init_debug,
545
+ init_fsOperations,
546
+ init_slowOperations,
547
+ isDebugMode,
548
+ jsonParse,
549
+ jsonStringify,
550
+ logForDebugging,
551
+ registerCleanup
552
+ } from "./chunk-ctya0ggm.js";
553
+ import {
554
+ init_process,
555
+ registerProcessOutputErrorHandlers,
556
+ writeToStdout
557
+ } from "./chunk-fbv4apne.js";
558
+ import {
559
+ errorMessage,
560
+ init_errors,
561
+ toError
562
+ } from "./chunk-z6e5jp2w.js";
563
+ import {
564
+ getAllowedChannels,
565
+ getFlagSettingsInline,
566
+ getInitJsonSchema,
567
+ getMainThreadAgentType,
568
+ getModelUsage,
569
+ getSessionId,
570
+ getTotalAPIDuration,
571
+ getTotalCostUSD,
572
+ init_state,
573
+ isSessionPersistenceDisabled,
574
+ registerHookCallbacks,
575
+ setAllowedChannels,
576
+ setFlagSettingsInline,
577
+ setInitJsonSchema,
578
+ setMainLoopModelOverride,
579
+ setMainThreadAgentType,
580
+ setSdkAgentProgressSummariesEnabled,
581
+ switchSession
582
+ } from "./chunk-h4b85amj.js";
583
+ import"./chunk-07069jq1.js";
584
+ import {
585
+ init_envUtils,
586
+ isBareMode,
587
+ isEnvDefinedFalsy,
588
+ isEnvTruthy
589
+ } from "./chunk-jaaxk89e.js";
590
+ import"./chunk-vf612n57.js";
591
+ import"./chunk-d4mdda98.js";
592
+ import"./chunk-7wm5s02e.js";
593
+ import"./chunk-4g3v8y12.js";
594
+ import"./chunk-7739pg2c.js";
595
+ import"./chunk-nh3cd07f.js";
596
+ import"./chunk-8pn8tvgg.js";
597
+ import"./chunk-netzwgv1.js";
598
+ import {
599
+ __require,
600
+ __toCommonJS
601
+ } from "./chunk-qp2qdcda.js";
602
+
603
+ // src/cli/print.ts
604
+ init_settingsSync();
605
+ init_remoteManagedSettings();
606
+ import { readFile as readFile2, stat } from "fs/promises";
607
+ import { dirname } from "path";
608
+
609
+ // src/cli/remoteIO.ts
610
+ init_state();
611
+ import { PassThrough } from "stream";
612
+ import { URL as URL3 } from "url";
613
+ init_cleanupRegistry();
614
+ init_commandLifecycle();
615
+ init_debug();
616
+ init_diagLogs();
617
+ init_envUtils();
618
+ init_errors();
619
+ init_gracefulShutdown();
620
+ init_log();
621
+ init_process();
622
+ init_sessionIngressAuth();
623
+ init_sessionStorage();
624
+ init_SSETransport();
625
+
626
+ // src/cli/transports/transportUtils.ts
627
+ init_envUtils();
628
+ import { URL as URL2 } from "url";
629
+ init_SSETransport();
630
+ function getTransportForUrl(url, headers = {}, sessionId, refreshHeaders) {
631
+ if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
632
+ const sseUrl = new URL2(url.href);
633
+ if (sseUrl.protocol === "wss:") {
634
+ sseUrl.protocol = "https:";
635
+ } else if (sseUrl.protocol === "ws:") {
636
+ sseUrl.protocol = "http:";
637
+ }
638
+ sseUrl.pathname = sseUrl.pathname.replace(/\/$/, "") + "/worker/events/stream";
639
+ return new SSETransport(sseUrl, headers, sessionId, refreshHeaders);
640
+ }
641
+ if (url.protocol === "ws:" || url.protocol === "wss:") {
642
+ if (isEnvTruthy(process.env.CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2)) {
643
+ return new HybridTransport(url, headers, sessionId, refreshHeaders);
644
+ }
645
+ return new WebSocketTransport(url, headers, sessionId, refreshHeaders);
646
+ } else {
647
+ throw new Error(`Unsupported protocol: ${url.protocol}`);
648
+ }
649
+ }
650
+
651
+ // src/cli/remoteIO.ts
652
+ class RemoteIO extends StructuredIO {
653
+ url;
654
+ transport;
655
+ inputStream;
656
+ isBridge = false;
657
+ isDebug = false;
658
+ ccrClient = null;
659
+ keepAliveTimer = null;
660
+ constructor(streamUrl, initialPrompt, replayUserMessages) {
661
+ const inputStream = new PassThrough({ encoding: "utf8" });
662
+ super(inputStream, replayUserMessages);
663
+ this.inputStream = inputStream;
664
+ this.url = new URL3(streamUrl);
665
+ const headers = {};
666
+ const sessionToken = getSessionIngressAuthToken();
667
+ if (sessionToken) {
668
+ headers["Authorization"] = `Bearer ${sessionToken}`;
669
+ } else {
670
+ logForDebugging("[remote-io] No session ingress token available", {
671
+ level: "error"
672
+ });
673
+ }
674
+ const erVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;
675
+ if (erVersion) {
676
+ headers["x-environment-runner-version"] = erVersion;
677
+ }
678
+ const refreshHeaders = () => {
679
+ const h = {};
680
+ const freshToken = getSessionIngressAuthToken();
681
+ if (freshToken) {
682
+ h["Authorization"] = `Bearer ${freshToken}`;
683
+ }
684
+ const freshErVersion = process.env.CLAUDE_CODE_ENVIRONMENT_RUNNER_VERSION;
685
+ if (freshErVersion) {
686
+ h["x-environment-runner-version"] = freshErVersion;
687
+ }
688
+ return h;
689
+ };
690
+ this.transport = getTransportForUrl(this.url, headers, getSessionId(), refreshHeaders);
691
+ this.isBridge = process.env.CLAUDE_CODE_ENVIRONMENT_KIND === "bridge";
692
+ this.isDebug = isDebugMode();
693
+ this.transport.setOnData((data) => {
694
+ this.inputStream.write(data);
695
+ if (this.isBridge && this.isDebug) {
696
+ writeToStdout(data.endsWith(`
697
+ `) ? data : data + `
698
+ `);
699
+ }
700
+ });
701
+ this.transport.setOnClose(() => {
702
+ this.inputStream.end();
703
+ });
704
+ if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
705
+ if (!(this.transport instanceof SSETransport)) {
706
+ throw new Error("CCR v2 requires SSETransport; check getTransportForUrl");
707
+ }
708
+ this.ccrClient = new CCRClient(this.transport, this.url);
709
+ const init = this.ccrClient.initialize();
710
+ this.restoredWorkerState = init.catch(() => null);
711
+ init.catch((error) => {
712
+ logForDiagnosticsNoPII("error", "cli_worker_lifecycle_init_failed", {
713
+ reason: error instanceof CCRInitError ? error.reason : "unknown"
714
+ });
715
+ logError(new Error(`CCRClient initialization failed: ${errorMessage(error)}`));
716
+ gracefulShutdown(1, "other");
717
+ });
718
+ registerCleanup(async () => this.ccrClient?.close());
719
+ setInternalEventWriter((eventType, payload, options) => this.ccrClient.writeInternalEvent(eventType, payload, options));
720
+ setInternalEventReader(() => this.ccrClient.readInternalEvents(), () => this.ccrClient.readSubagentInternalEvents());
721
+ const LIFECYCLE_TO_DELIVERY = {
722
+ started: "processing",
723
+ completed: "processed"
724
+ };
725
+ setCommandLifecycleListener((uuid, state) => {
726
+ this.ccrClient?.reportDelivery(uuid, LIFECYCLE_TO_DELIVERY[state]);
727
+ });
728
+ setSessionStateChangedListener((state, details) => {
729
+ this.ccrClient?.reportState(state, details);
730
+ });
731
+ setSessionMetadataChangedListener((metadata) => {
732
+ this.ccrClient?.reportMetadata(metadata);
733
+ });
734
+ }
735
+ this.transport.connect();
736
+ const keepAliveIntervalMs = getPollIntervalConfig().session_keepalive_interval_v2_ms;
737
+ if (this.isBridge && keepAliveIntervalMs > 0) {
738
+ this.keepAliveTimer = setInterval(() => {
739
+ logForDebugging("[remote-io] keep_alive sent");
740
+ this.write({ type: "keep_alive" }).catch((err) => {
741
+ logForDebugging(`[remote-io] keep_alive write failed: ${errorMessage(err)}`);
742
+ });
743
+ }, keepAliveIntervalMs);
744
+ this.keepAliveTimer.unref?.();
745
+ }
746
+ registerCleanup(async () => this.close());
747
+ if (initialPrompt) {
748
+ const stream = this.inputStream;
749
+ (async () => {
750
+ for await (const chunk of initialPrompt) {
751
+ stream.write(String(chunk).replace(/\n$/, "") + `
752
+ `);
753
+ }
754
+ })();
755
+ }
756
+ }
757
+ flushInternalEvents() {
758
+ return this.ccrClient?.flushInternalEvents() ?? Promise.resolve();
759
+ }
760
+ get internalEventsPending() {
761
+ return this.ccrClient?.internalEventsPending ?? 0;
762
+ }
763
+ async write(message) {
764
+ if (this.ccrClient) {
765
+ await this.ccrClient.writeEvent(message);
766
+ } else {
767
+ await this.transport.write(message);
768
+ }
769
+ if (this.isBridge) {
770
+ if (message.type === "control_request" || this.isDebug) {
771
+ writeToStdout(ndjsonSafeStringify(message) + `
772
+ `);
773
+ }
774
+ }
775
+ }
776
+ close() {
777
+ if (this.keepAliveTimer) {
778
+ clearInterval(this.keepAliveTimer);
779
+ this.keepAliveTimer = null;
780
+ }
781
+ this.transport.close();
782
+ this.inputStream.end();
783
+ }
784
+ }
785
+
786
+ // src/cli/print.ts
787
+ init_commands();
788
+
789
+ // src/utils/streamlinedTransform.ts
790
+ init_constants();
791
+ init_prompt3();
792
+ init_prompt4();
793
+ init_prompt5();
794
+ init_prompt2();
795
+ init_prompt8();
796
+ init_prompt9();
797
+ init_constants2();
798
+ init_prompt();
799
+ init_prompt6();
800
+ init_messages();
801
+ init_shellToolUtils();
802
+ init_stringUtils();
803
+ var COMMAND_TOOLS = [...SHELL_TOOL_NAMES, "Tmux", TASK_STOP_TOOL_NAME];
804
+
805
+ // src/utils/streamJsonStdoutGuard.ts
806
+ init_cleanupRegistry();
807
+ init_debug();
808
+ var STDOUT_GUARD_MARKER = "[stdout-guard]";
809
+ var installed = false;
810
+ var buffer = "";
811
+ var originalWrite = null;
812
+ function isJsonLine(line) {
813
+ if (line.length === 0) {
814
+ return true;
815
+ }
816
+ try {
817
+ JSON.parse(line);
818
+ return true;
819
+ } catch {
820
+ return false;
821
+ }
822
+ }
823
+ function installStreamJsonStdoutGuard() {
824
+ if (installed) {
825
+ return;
826
+ }
827
+ installed = true;
828
+ originalWrite = process.stdout.write.bind(process.stdout);
829
+ process.stdout.write = function(chunk, encodingOrCb, cb) {
830
+ const text = typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf-8");
831
+ buffer += text;
832
+ let newlineIdx;
833
+ let wrote = true;
834
+ while ((newlineIdx = buffer.indexOf(`
835
+ `)) !== -1) {
836
+ const line = buffer.slice(0, newlineIdx);
837
+ buffer = buffer.slice(newlineIdx + 1);
838
+ if (isJsonLine(line)) {
839
+ wrote = originalWrite(line + `
840
+ `);
841
+ } else {
842
+ process.stderr.write(`${STDOUT_GUARD_MARKER} ${line}
843
+ `);
844
+ logForDebugging(`streamJsonStdoutGuard diverted non-JSON stdout line: ${line.slice(0, 200)}`);
845
+ }
846
+ }
847
+ const callback = typeof encodingOrCb === "function" ? encodingOrCb : cb;
848
+ if (callback) {
849
+ queueMicrotask(() => callback());
850
+ }
851
+ return wrote;
852
+ };
853
+ registerCleanup(async () => {
854
+ if (buffer.length > 0) {
855
+ if (originalWrite && isJsonLine(buffer)) {
856
+ originalWrite(buffer + `
857
+ `);
858
+ } else {
859
+ process.stderr.write(`${STDOUT_GUARD_MARKER} ${buffer}
860
+ `);
861
+ }
862
+ buffer = "";
863
+ }
864
+ if (originalWrite) {
865
+ process.stdout.write = originalWrite;
866
+ originalWrite = null;
867
+ }
868
+ installed = false;
869
+ });
870
+ }
871
+
872
+ // src/cli/print.ts
873
+ init_tools();
874
+ init_uniqBy();
875
+ init_array();
876
+ init_toolPool();
877
+ init_analytics();
878
+ init_growthbook();
879
+ init_debug();
880
+ init_diagLogs();
881
+ init_Tool();
882
+ init_loadAgentsDir();
883
+ init_messageQueueManager();
884
+ init_commandLifecycle();
885
+ init_log();
886
+ init_process();
887
+ init_logging();
888
+ init_conversationRecovery();
889
+ init_channelNotification();
890
+ init_channelAllowlist();
891
+ init_pluginIdentifier();
892
+ init_uuid();
893
+ init_generators();
894
+
895
+ // src/QueryEngine.ts
896
+ init_last();
897
+ init_state();
898
+ init_claude();
899
+ init_logging();
900
+ init_strip_ansi();
901
+ init_commands();
902
+ init_xml();
903
+ init_cost_tracker();
904
+ init_memdir();
905
+ init_paths();
906
+ init_query();
907
+ init_errors2();
908
+ init_Tool();
909
+ init_SyntheticOutputTool();
910
+ init_abortController();
911
+ init_config();
912
+ init_cwd();
913
+ init_envUtils();
914
+ init_fastMode();
915
+ init_fileHistory();
916
+ init_fileStateCache();
917
+ init_headlessProfiler();
918
+ init_hookHelpers();
919
+ init_log();
920
+ init_messages();
921
+ init_model();
922
+ init_pluginLoader();
923
+ import { randomUUID } from "crypto";
924
+
925
+ // src/utils/queryContext.ts
926
+ init_prompts();
927
+ init_context();
928
+ init_abortController();
929
+ init_model();
930
+ init_systemPromptType();
931
+ init_thinking();
932
+ async function fetchSystemPromptParts({
933
+ tools,
934
+ mainLoopModel,
935
+ additionalWorkingDirectories,
936
+ mcpClients,
937
+ customSystemPrompt
938
+ }) {
939
+ const [defaultSystemPrompt, userContext, systemContext] = await Promise.all([
940
+ customSystemPrompt !== undefined ? Promise.resolve([]) : getSystemPrompt(tools, mainLoopModel, additionalWorkingDirectories, mcpClients),
941
+ getUserContext(),
942
+ customSystemPrompt !== undefined ? Promise.resolve({}) : getSystemContext()
943
+ ]);
944
+ return { defaultSystemPrompt, userContext, systemContext };
945
+ }
946
+ async function buildSideQuestionFallbackParams({
947
+ tools,
948
+ commands,
949
+ mcpClients,
950
+ messages,
951
+ readFileState,
952
+ getAppState,
953
+ setAppState,
954
+ customSystemPrompt,
955
+ appendSystemPrompt,
956
+ thinkingConfig,
957
+ agents
958
+ }) {
959
+ const mainLoopModel = getMainLoopModel();
960
+ const appState = getAppState();
961
+ const { defaultSystemPrompt, userContext, systemContext } = await fetchSystemPromptParts({
962
+ tools,
963
+ mainLoopModel,
964
+ additionalWorkingDirectories: Array.from(appState.toolPermissionContext.additionalWorkingDirectories.keys()),
965
+ mcpClients,
966
+ customSystemPrompt
967
+ });
968
+ const systemPrompt = asSystemPrompt([
969
+ ...customSystemPrompt !== undefined ? [customSystemPrompt] : defaultSystemPrompt,
970
+ ...appendSystemPrompt ? [appendSystemPrompt] : []
971
+ ]);
972
+ const last = messages.at(-1);
973
+ const forkContextMessages = last?.type === "assistant" && last.message.stop_reason === null ? messages.slice(0, -1) : messages;
974
+ const toolUseContext = {
975
+ options: {
976
+ commands,
977
+ debug: false,
978
+ mainLoopModel,
979
+ tools,
980
+ verbose: false,
981
+ thinkingConfig: thinkingConfig ?? (shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" }),
982
+ mcpClients,
983
+ mcpResources: {},
984
+ isNonInteractiveSession: true,
985
+ agentDefinitions: { activeAgents: agents, allAgents: [] },
986
+ customSystemPrompt,
987
+ appendSystemPrompt
988
+ },
989
+ abortController: createAbortController(),
990
+ readFileState,
991
+ getAppState,
992
+ setAppState,
993
+ messages: forkContextMessages,
994
+ setInProgressToolUseIDs: () => {},
995
+ setResponseLength: () => {},
996
+ updateFileHistoryState: () => {},
997
+ updateAttributionState: () => {}
998
+ };
999
+ return {
1000
+ systemPrompt,
1001
+ userContext,
1002
+ systemContext,
1003
+ toolUseContext,
1004
+ forkContextMessages
1005
+ };
1006
+ }
1007
+
1008
+ // src/QueryEngine.ts
1009
+ init_Shell();
1010
+ init_sessionStorage();
1011
+ init_systemPromptType();
1012
+ init_systemTheme();
1013
+ init_thinking();
1014
+ init_mappers();
1015
+ init_filesystem();
1016
+ init_queryHelpers();
1017
+ var messageSelector = () => (init_MessageSelector(), __toCommonJS(exports_MessageSelector));
1018
+ var getCoordinatorUserContext = () => ({});
1019
+ class QueryEngine {
1020
+ config;
1021
+ mutableMessages;
1022
+ abortController;
1023
+ permissionDenials;
1024
+ totalUsage;
1025
+ hasHandledOrphanedPermission = false;
1026
+ readFileState;
1027
+ discoveredSkillNames = new Set;
1028
+ loadedNestedMemoryPaths = new Set;
1029
+ constructor(config) {
1030
+ this.config = config;
1031
+ this.mutableMessages = config.initialMessages ?? [];
1032
+ this.abortController = config.abortController ?? createAbortController();
1033
+ this.permissionDenials = [];
1034
+ this.readFileState = config.readFileCache;
1035
+ this.totalUsage = EMPTY_USAGE;
1036
+ }
1037
+ async* submitMessage(prompt, options) {
1038
+ const {
1039
+ cwd,
1040
+ commands,
1041
+ tools,
1042
+ mcpClients,
1043
+ verbose = false,
1044
+ thinkingConfig,
1045
+ maxTurns,
1046
+ maxBudgetUsd,
1047
+ taskBudget,
1048
+ canUseTool,
1049
+ customSystemPrompt,
1050
+ appendSystemPrompt,
1051
+ userSpecifiedModel,
1052
+ fallbackModel,
1053
+ jsonSchema,
1054
+ getAppState,
1055
+ setAppState,
1056
+ replayUserMessages = false,
1057
+ includePartialMessages = false,
1058
+ agents = [],
1059
+ setSDKStatus,
1060
+ orphanedPermission
1061
+ } = this.config;
1062
+ this.discoveredSkillNames.clear();
1063
+ setCwd(cwd);
1064
+ const persistSession = !isSessionPersistenceDisabled();
1065
+ const startTime = Date.now();
1066
+ const wrappedCanUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision) => {
1067
+ const result2 = await canUseTool(tool, input, toolUseContext, assistantMessage, toolUseID, forceDecision);
1068
+ if (result2.behavior !== "allow") {
1069
+ this.permissionDenials.push({
1070
+ type: "permission_denial",
1071
+ tool_name: sdkCompatToolName(tool.name),
1072
+ tool_use_id: toolUseID,
1073
+ tool_input: input
1074
+ });
1075
+ }
1076
+ return result2;
1077
+ };
1078
+ const initialAppState = getAppState();
1079
+ const initialMainLoopModel = userSpecifiedModel ? parseUserSpecifiedModel(userSpecifiedModel) : getMainLoopModel();
1080
+ const initialThinkingConfig = thinkingConfig ? thinkingConfig : shouldEnableThinkingByDefault() !== false ? { type: "adaptive" } : { type: "disabled" };
1081
+ headlessProfilerCheckpoint("before_getSystemPrompt");
1082
+ const customPrompt = typeof customSystemPrompt === "string" ? customSystemPrompt : undefined;
1083
+ const {
1084
+ defaultSystemPrompt,
1085
+ userContext: baseUserContext,
1086
+ systemContext
1087
+ } = await fetchSystemPromptParts({
1088
+ tools,
1089
+ mainLoopModel: initialMainLoopModel,
1090
+ additionalWorkingDirectories: Array.from(initialAppState.toolPermissionContext.additionalWorkingDirectories.keys()),
1091
+ mcpClients,
1092
+ customSystemPrompt: customPrompt
1093
+ });
1094
+ headlessProfilerCheckpoint("after_getSystemPrompt");
1095
+ const userContext = {
1096
+ ...baseUserContext,
1097
+ ...getCoordinatorUserContext(mcpClients, isScratchpadEnabled() ? getScratchpadDir() : undefined)
1098
+ };
1099
+ const memoryMechanicsPrompt = customPrompt !== undefined && hasAutoMemPathOverride() ? await loadMemoryPrompt() : null;
1100
+ const systemPrompt = asSystemPrompt([
1101
+ ...customPrompt !== undefined ? [customPrompt] : defaultSystemPrompt,
1102
+ ...memoryMechanicsPrompt ? [memoryMechanicsPrompt] : [],
1103
+ ...appendSystemPrompt ? [appendSystemPrompt] : []
1104
+ ]);
1105
+ const hasStructuredOutputTool = tools.some((t) => toolMatchesName(t, SYNTHETIC_OUTPUT_TOOL_NAME));
1106
+ if (jsonSchema && hasStructuredOutputTool) {
1107
+ registerStructuredOutputEnforcement(setAppState, getSessionId());
1108
+ }
1109
+ let processUserInputContext = {
1110
+ messages: this.mutableMessages,
1111
+ setMessages: (fn) => {
1112
+ this.mutableMessages = fn(this.mutableMessages);
1113
+ },
1114
+ onChangeAPIKey: () => {},
1115
+ handleElicitation: this.config.handleElicitation,
1116
+ options: {
1117
+ commands,
1118
+ debug: false,
1119
+ tools,
1120
+ verbose,
1121
+ mainLoopModel: initialMainLoopModel,
1122
+ thinkingConfig: initialThinkingConfig,
1123
+ mcpClients,
1124
+ mcpResources: {},
1125
+ ideInstallationStatus: null,
1126
+ isNonInteractiveSession: true,
1127
+ customSystemPrompt,
1128
+ appendSystemPrompt,
1129
+ agentDefinitions: { activeAgents: agents, allAgents: [] },
1130
+ theme: resolveThemeSetting(getGlobalConfig().theme),
1131
+ maxBudgetUsd
1132
+ },
1133
+ getAppState,
1134
+ setAppState,
1135
+ abortController: this.abortController,
1136
+ readFileState: this.readFileState,
1137
+ nestedMemoryAttachmentTriggers: new Set,
1138
+ loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
1139
+ dynamicSkillDirTriggers: new Set,
1140
+ discoveredSkillNames: this.discoveredSkillNames,
1141
+ setInProgressToolUseIDs: () => {},
1142
+ setResponseLength: () => {},
1143
+ updateFileHistoryState: (updater) => {
1144
+ setAppState((prev) => {
1145
+ const updated = updater(prev.fileHistory);
1146
+ if (updated === prev.fileHistory)
1147
+ return prev;
1148
+ return { ...prev, fileHistory: updated };
1149
+ });
1150
+ },
1151
+ updateAttributionState: (updater) => {
1152
+ setAppState((prev) => {
1153
+ const updated = updater(prev.attribution);
1154
+ if (updated === prev.attribution)
1155
+ return prev;
1156
+ return { ...prev, attribution: updated };
1157
+ });
1158
+ },
1159
+ setSDKStatus
1160
+ };
1161
+ if (orphanedPermission && !this.hasHandledOrphanedPermission) {
1162
+ this.hasHandledOrphanedPermission = true;
1163
+ for await (const message of handleOrphanedPermission(orphanedPermission, tools, this.mutableMessages, processUserInputContext)) {
1164
+ yield message;
1165
+ }
1166
+ }
1167
+ const {
1168
+ messages: messagesFromUserInput,
1169
+ shouldQuery,
1170
+ allowedTools,
1171
+ model: modelFromUserInput,
1172
+ resultText
1173
+ } = await processUserInput({
1174
+ input: prompt,
1175
+ mode: "prompt",
1176
+ setToolJSX: () => {},
1177
+ context: {
1178
+ ...processUserInputContext,
1179
+ messages: this.mutableMessages
1180
+ },
1181
+ messages: this.mutableMessages,
1182
+ uuid: options?.uuid,
1183
+ isMeta: options?.isMeta,
1184
+ querySource: "sdk"
1185
+ });
1186
+ this.mutableMessages.push(...messagesFromUserInput);
1187
+ const messages = [...this.mutableMessages];
1188
+ if (persistSession && messagesFromUserInput.length > 0) {
1189
+ const transcriptPromise = recordTranscript(messages);
1190
+ if (isBareMode()) {} else {
1191
+ await transcriptPromise;
1192
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1193
+ await flushSessionStorage();
1194
+ }
1195
+ }
1196
+ }
1197
+ const replayableMessages = messagesFromUserInput.filter((msg) => msg.type === "user" && !msg.isMeta && !msg.toolUseResult && messageSelector().selectableUserMessagesFilter(msg) || msg.type === "system" && msg.subtype === "compact_boundary");
1198
+ const messagesToAck = replayUserMessages ? replayableMessages : [];
1199
+ setAppState((prev) => ({
1200
+ ...prev,
1201
+ toolPermissionContext: {
1202
+ ...prev.toolPermissionContext,
1203
+ alwaysAllowRules: {
1204
+ ...prev.toolPermissionContext.alwaysAllowRules,
1205
+ command: allowedTools
1206
+ }
1207
+ }
1208
+ }));
1209
+ const mainLoopModel = modelFromUserInput ?? initialMainLoopModel;
1210
+ processUserInputContext = {
1211
+ messages,
1212
+ setMessages: () => {},
1213
+ onChangeAPIKey: () => {},
1214
+ handleElicitation: this.config.handleElicitation,
1215
+ options: {
1216
+ commands,
1217
+ debug: false,
1218
+ tools,
1219
+ verbose,
1220
+ mainLoopModel,
1221
+ thinkingConfig: initialThinkingConfig,
1222
+ mcpClients,
1223
+ mcpResources: {},
1224
+ ideInstallationStatus: null,
1225
+ isNonInteractiveSession: true,
1226
+ customSystemPrompt,
1227
+ appendSystemPrompt,
1228
+ theme: resolveThemeSetting(getGlobalConfig().theme),
1229
+ agentDefinitions: { activeAgents: agents, allAgents: [] },
1230
+ maxBudgetUsd
1231
+ },
1232
+ getAppState,
1233
+ setAppState,
1234
+ abortController: this.abortController,
1235
+ readFileState: this.readFileState,
1236
+ nestedMemoryAttachmentTriggers: new Set,
1237
+ loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
1238
+ dynamicSkillDirTriggers: new Set,
1239
+ discoveredSkillNames: this.discoveredSkillNames,
1240
+ setInProgressToolUseIDs: () => {},
1241
+ setResponseLength: () => {},
1242
+ updateFileHistoryState: processUserInputContext.updateFileHistoryState,
1243
+ updateAttributionState: processUserInputContext.updateAttributionState,
1244
+ setSDKStatus
1245
+ };
1246
+ headlessProfilerCheckpoint("before_skills_plugins");
1247
+ const [skills, { enabled: enabledPlugins }] = await Promise.all([
1248
+ getSlashCommandToolSkills(getCwd()),
1249
+ loadAllPluginsCacheOnly()
1250
+ ]);
1251
+ headlessProfilerCheckpoint("after_skills_plugins");
1252
+ yield buildSystemInitMessage({
1253
+ tools,
1254
+ mcpClients,
1255
+ model: mainLoopModel,
1256
+ permissionMode: initialAppState.toolPermissionContext.mode,
1257
+ commands,
1258
+ agents,
1259
+ skills,
1260
+ plugins: enabledPlugins,
1261
+ fastMode: initialAppState.fastMode
1262
+ });
1263
+ headlessProfilerCheckpoint("system_message_yielded");
1264
+ if (!shouldQuery) {
1265
+ for (const msg of messagesFromUserInput) {
1266
+ if (msg.type === "user" && typeof msg.message.content === "string" && (msg.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.message.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`) || msg.isCompactSummary)) {
1267
+ yield {
1268
+ type: "user",
1269
+ message: {
1270
+ ...msg.message,
1271
+ content: stripAnsi(msg.message.content)
1272
+ },
1273
+ session_id: getSessionId(),
1274
+ parent_tool_use_id: null,
1275
+ uuid: msg.uuid,
1276
+ timestamp: msg.timestamp,
1277
+ isReplay: !msg.isCompactSummary,
1278
+ isSynthetic: msg.isMeta || msg.isVisibleInTranscriptOnly
1279
+ };
1280
+ }
1281
+ if (msg.type === "system" && msg.subtype === "local_command" && typeof msg.content === "string" && (msg.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) || msg.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`))) {
1282
+ yield localCommandOutputToSDKAssistantMessage(msg.content, msg.uuid);
1283
+ }
1284
+ if (msg.type === "system" && msg.subtype === "compact_boundary") {
1285
+ const compactMsg = msg;
1286
+ yield {
1287
+ type: "system",
1288
+ subtype: "compact_boundary",
1289
+ session_id: getSessionId(),
1290
+ uuid: msg.uuid,
1291
+ compact_metadata: toSDKCompactMetadata(compactMsg.compactMetadata)
1292
+ };
1293
+ }
1294
+ }
1295
+ if (persistSession) {
1296
+ await recordTranscript(messages);
1297
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1298
+ await flushSessionStorage();
1299
+ }
1300
+ }
1301
+ yield {
1302
+ type: "result",
1303
+ subtype: "success",
1304
+ is_error: false,
1305
+ duration_ms: Date.now() - startTime,
1306
+ duration_api_ms: getTotalAPIDuration(),
1307
+ num_turns: messages.length - 1,
1308
+ result: resultText ?? "",
1309
+ stop_reason: null,
1310
+ session_id: getSessionId(),
1311
+ total_cost_usd: getTotalCostUSD(),
1312
+ usage: this.totalUsage,
1313
+ modelUsage: getModelUsage(),
1314
+ permission_denials: this.permissionDenials,
1315
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1316
+ uuid: randomUUID()
1317
+ };
1318
+ return;
1319
+ }
1320
+ if (fileHistoryEnabled() && persistSession) {
1321
+ messagesFromUserInput.filter(messageSelector().selectableUserMessagesFilter).forEach((message) => {
1322
+ fileHistoryMakeSnapshot((updater) => {
1323
+ setAppState((prev) => ({
1324
+ ...prev,
1325
+ fileHistory: updater(prev.fileHistory)
1326
+ }));
1327
+ }, message.uuid);
1328
+ });
1329
+ }
1330
+ let currentMessageUsage = EMPTY_USAGE;
1331
+ let turnCount = 1;
1332
+ let hasAcknowledgedInitialMessages = false;
1333
+ let structuredOutputFromTool;
1334
+ let lastStopReason = null;
1335
+ const errorLogWatermark = getInMemoryErrors().at(-1);
1336
+ const initialStructuredOutputCalls = jsonSchema ? countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME) : 0;
1337
+ for await (const message of query({
1338
+ messages,
1339
+ systemPrompt,
1340
+ userContext,
1341
+ systemContext,
1342
+ canUseTool: wrappedCanUseTool,
1343
+ toolUseContext: processUserInputContext,
1344
+ fallbackModel,
1345
+ querySource: "sdk",
1346
+ maxTurns,
1347
+ taskBudget
1348
+ })) {
1349
+ if (message.type === "assistant" || message.type === "user" || message.type === "system" && message.subtype === "compact_boundary") {
1350
+ if (persistSession && message.type === "system" && message.subtype === "compact_boundary") {
1351
+ const compactMsg = message;
1352
+ const tailUuid = compactMsg.compactMetadata?.preservedSegment?.tailUuid;
1353
+ if (tailUuid) {
1354
+ const tailIdx = this.mutableMessages.findLastIndex((m) => m.uuid === tailUuid);
1355
+ if (tailIdx !== -1) {
1356
+ await recordTranscript(this.mutableMessages.slice(0, tailIdx + 1));
1357
+ }
1358
+ }
1359
+ }
1360
+ messages.push(message);
1361
+ if (persistSession) {
1362
+ if (message.type === "assistant") {
1363
+ recordTranscript(messages);
1364
+ } else {
1365
+ await recordTranscript(messages);
1366
+ }
1367
+ }
1368
+ if (!hasAcknowledgedInitialMessages && messagesToAck.length > 0) {
1369
+ hasAcknowledgedInitialMessages = true;
1370
+ for (const msgToAck of messagesToAck) {
1371
+ if (msgToAck.type === "user") {
1372
+ yield {
1373
+ type: "user",
1374
+ message: msgToAck.message,
1375
+ session_id: getSessionId(),
1376
+ parent_tool_use_id: null,
1377
+ uuid: msgToAck.uuid,
1378
+ timestamp: msgToAck.timestamp,
1379
+ isReplay: true
1380
+ };
1381
+ }
1382
+ }
1383
+ }
1384
+ }
1385
+ if (message.type === "user") {
1386
+ turnCount++;
1387
+ }
1388
+ switch (message.type) {
1389
+ case "tombstone":
1390
+ break;
1391
+ case "assistant": {
1392
+ const msg = message;
1393
+ const stopReason = msg.message?.stop_reason;
1394
+ if (stopReason != null) {
1395
+ lastStopReason = stopReason;
1396
+ }
1397
+ this.mutableMessages.push(msg);
1398
+ yield* normalizeMessage(msg);
1399
+ break;
1400
+ }
1401
+ case "progress": {
1402
+ const msg = message;
1403
+ this.mutableMessages.push(msg);
1404
+ if (persistSession) {
1405
+ messages.push(msg);
1406
+ recordTranscript(messages);
1407
+ }
1408
+ yield* normalizeMessage(msg);
1409
+ break;
1410
+ }
1411
+ case "user": {
1412
+ const msg = message;
1413
+ this.mutableMessages.push(msg);
1414
+ yield* normalizeMessage(msg);
1415
+ break;
1416
+ }
1417
+ case "stream_event": {
1418
+ const event = message.event;
1419
+ if (event.type === "message_start") {
1420
+ currentMessageUsage = EMPTY_USAGE;
1421
+ const eventMessage = event.message;
1422
+ currentMessageUsage = updateUsage(currentMessageUsage, eventMessage.usage);
1423
+ }
1424
+ if (event.type === "message_delta") {
1425
+ currentMessageUsage = updateUsage(currentMessageUsage, event.usage);
1426
+ const delta = event.delta;
1427
+ if (delta.stop_reason != null) {
1428
+ lastStopReason = delta.stop_reason;
1429
+ }
1430
+ }
1431
+ if (event.type === "message_stop") {
1432
+ this.totalUsage = accumulateUsage(this.totalUsage, currentMessageUsage);
1433
+ }
1434
+ if (includePartialMessages) {
1435
+ yield {
1436
+ type: "stream_event",
1437
+ event,
1438
+ session_id: getSessionId(),
1439
+ parent_tool_use_id: null,
1440
+ uuid: randomUUID()
1441
+ };
1442
+ }
1443
+ break;
1444
+ }
1445
+ case "attachment": {
1446
+ const msg = message;
1447
+ this.mutableMessages.push(msg);
1448
+ if (persistSession) {
1449
+ messages.push(msg);
1450
+ recordTranscript(messages);
1451
+ }
1452
+ const attachment = msg.attachment;
1453
+ if (attachment.type === "structured_output") {
1454
+ structuredOutputFromTool = attachment.data;
1455
+ } else if (attachment.type === "max_turns_reached") {
1456
+ if (persistSession) {
1457
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1458
+ await flushSessionStorage();
1459
+ }
1460
+ }
1461
+ yield {
1462
+ type: "result",
1463
+ subtype: "error_max_turns",
1464
+ duration_ms: Date.now() - startTime,
1465
+ duration_api_ms: getTotalAPIDuration(),
1466
+ is_error: true,
1467
+ num_turns: attachment.turnCount,
1468
+ stop_reason: lastStopReason,
1469
+ session_id: getSessionId(),
1470
+ total_cost_usd: getTotalCostUSD(),
1471
+ usage: this.totalUsage,
1472
+ modelUsage: getModelUsage(),
1473
+ permission_denials: this.permissionDenials,
1474
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1475
+ uuid: randomUUID(),
1476
+ errors: [
1477
+ `Reached maximum number of turns (${attachment.maxTurns})`
1478
+ ]
1479
+ };
1480
+ return;
1481
+ } else if (replayUserMessages && attachment.type === "queued_command") {
1482
+ yield {
1483
+ type: "user",
1484
+ message: {
1485
+ role: "user",
1486
+ content: attachment.prompt
1487
+ },
1488
+ session_id: getSessionId(),
1489
+ parent_tool_use_id: null,
1490
+ uuid: attachment.source_uuid || msg.uuid,
1491
+ timestamp: msg.timestamp,
1492
+ isReplay: true
1493
+ };
1494
+ }
1495
+ break;
1496
+ }
1497
+ case "stream_request_start":
1498
+ break;
1499
+ case "system": {
1500
+ const msg = message;
1501
+ const snipResult = this.config.snipReplay?.(msg, this.mutableMessages);
1502
+ if (snipResult !== undefined) {
1503
+ if (snipResult.executed) {
1504
+ this.mutableMessages.length = 0;
1505
+ this.mutableMessages.push(...snipResult.messages);
1506
+ }
1507
+ break;
1508
+ }
1509
+ this.mutableMessages.push(msg);
1510
+ if (msg.subtype === "compact_boundary" && msg.compactMetadata) {
1511
+ const compactMsg = msg;
1512
+ const mutableBoundaryIdx = this.mutableMessages.length - 1;
1513
+ if (mutableBoundaryIdx > 0) {
1514
+ this.mutableMessages.splice(0, mutableBoundaryIdx);
1515
+ }
1516
+ const localBoundaryIdx = messages.length - 1;
1517
+ if (localBoundaryIdx > 0) {
1518
+ messages.splice(0, localBoundaryIdx);
1519
+ }
1520
+ yield {
1521
+ type: "system",
1522
+ subtype: "compact_boundary",
1523
+ session_id: getSessionId(),
1524
+ uuid: msg.uuid,
1525
+ compact_metadata: toSDKCompactMetadata(compactMsg.compactMetadata)
1526
+ };
1527
+ }
1528
+ if (msg.subtype === "api_error") {
1529
+ const apiErrorMsg = msg;
1530
+ yield {
1531
+ type: "system",
1532
+ subtype: "api_retry",
1533
+ attempt: apiErrorMsg.retryAttempt,
1534
+ max_retries: apiErrorMsg.maxRetries,
1535
+ retry_delay_ms: apiErrorMsg.retryInMs,
1536
+ error_status: apiErrorMsg.error.status ?? null,
1537
+ error: categorizeRetryableAPIError(apiErrorMsg.error),
1538
+ session_id: getSessionId(),
1539
+ uuid: msg.uuid
1540
+ };
1541
+ }
1542
+ break;
1543
+ }
1544
+ case "tool_use_summary": {
1545
+ const msg = message;
1546
+ yield {
1547
+ type: "tool_use_summary",
1548
+ summary: msg.summary,
1549
+ preceding_tool_use_ids: msg.precedingToolUseIds,
1550
+ session_id: getSessionId(),
1551
+ uuid: msg.uuid
1552
+ };
1553
+ break;
1554
+ }
1555
+ }
1556
+ if (maxBudgetUsd !== undefined && getTotalCostUSD() >= maxBudgetUsd) {
1557
+ if (persistSession) {
1558
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1559
+ await flushSessionStorage();
1560
+ }
1561
+ }
1562
+ yield {
1563
+ type: "result",
1564
+ subtype: "error_max_budget_usd",
1565
+ duration_ms: Date.now() - startTime,
1566
+ duration_api_ms: getTotalAPIDuration(),
1567
+ is_error: true,
1568
+ num_turns: turnCount,
1569
+ stop_reason: lastStopReason,
1570
+ session_id: getSessionId(),
1571
+ total_cost_usd: getTotalCostUSD(),
1572
+ usage: this.totalUsage,
1573
+ modelUsage: getModelUsage(),
1574
+ permission_denials: this.permissionDenials,
1575
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1576
+ uuid: randomUUID(),
1577
+ errors: [`Reached maximum budget ($${maxBudgetUsd})`]
1578
+ };
1579
+ return;
1580
+ }
1581
+ if (message.type === "user" && jsonSchema) {
1582
+ const currentCalls = countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME);
1583
+ const callsThisQuery = currentCalls - initialStructuredOutputCalls;
1584
+ const maxRetries = parseInt(process.env.MAX_STRUCTURED_OUTPUT_RETRIES || "5", 10);
1585
+ if (callsThisQuery >= maxRetries) {
1586
+ if (persistSession) {
1587
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1588
+ await flushSessionStorage();
1589
+ }
1590
+ }
1591
+ yield {
1592
+ type: "result",
1593
+ subtype: "error_max_structured_output_retries",
1594
+ duration_ms: Date.now() - startTime,
1595
+ duration_api_ms: getTotalAPIDuration(),
1596
+ is_error: true,
1597
+ num_turns: turnCount,
1598
+ stop_reason: lastStopReason,
1599
+ session_id: getSessionId(),
1600
+ total_cost_usd: getTotalCostUSD(),
1601
+ usage: this.totalUsage,
1602
+ modelUsage: getModelUsage(),
1603
+ permission_denials: this.permissionDenials,
1604
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1605
+ uuid: randomUUID(),
1606
+ errors: [
1607
+ `Failed to provide valid structured output after ${maxRetries} attempts`
1608
+ ]
1609
+ };
1610
+ return;
1611
+ }
1612
+ }
1613
+ }
1614
+ const result = messages.findLast((m) => m.type === "assistant" || m.type === "user");
1615
+ const edeResultType = result?.type ?? "undefined";
1616
+ const edeLastContentType = result?.type === "assistant" ? last_default(result.message.content)?.type ?? "none" : "n/a";
1617
+ if (persistSession) {
1618
+ if (isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) || isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)) {
1619
+ await flushSessionStorage();
1620
+ }
1621
+ }
1622
+ if (!isResultSuccessful(result, lastStopReason)) {
1623
+ yield {
1624
+ type: "result",
1625
+ subtype: "error_during_execution",
1626
+ duration_ms: Date.now() - startTime,
1627
+ duration_api_ms: getTotalAPIDuration(),
1628
+ is_error: true,
1629
+ num_turns: turnCount,
1630
+ stop_reason: lastStopReason,
1631
+ session_id: getSessionId(),
1632
+ total_cost_usd: getTotalCostUSD(),
1633
+ usage: this.totalUsage,
1634
+ modelUsage: getModelUsage(),
1635
+ permission_denials: this.permissionDenials,
1636
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1637
+ uuid: randomUUID(),
1638
+ errors: (() => {
1639
+ const all = getInMemoryErrors();
1640
+ const start = errorLogWatermark ? all.lastIndexOf(errorLogWatermark) + 1 : 0;
1641
+ return [
1642
+ `[ede_diagnostic] result_type=${edeResultType} last_content_type=${edeLastContentType} stop_reason=${lastStopReason}`,
1643
+ ...all.slice(start).map((_) => _.error)
1644
+ ];
1645
+ })()
1646
+ };
1647
+ return;
1648
+ }
1649
+ let textResult = "";
1650
+ let isApiError = false;
1651
+ if (result.type === "assistant") {
1652
+ const lastContent = last_default(result.message.content);
1653
+ if (lastContent?.type === "text" && !SYNTHETIC_MESSAGES.has(lastContent.text)) {
1654
+ textResult = lastContent.text;
1655
+ }
1656
+ isApiError = Boolean(result.isApiErrorMessage);
1657
+ }
1658
+ yield {
1659
+ type: "result",
1660
+ subtype: "success",
1661
+ is_error: isApiError,
1662
+ duration_ms: Date.now() - startTime,
1663
+ duration_api_ms: getTotalAPIDuration(),
1664
+ num_turns: turnCount,
1665
+ result: textResult,
1666
+ stop_reason: lastStopReason,
1667
+ session_id: getSessionId(),
1668
+ total_cost_usd: getTotalCostUSD(),
1669
+ usage: this.totalUsage,
1670
+ modelUsage: getModelUsage(),
1671
+ permission_denials: this.permissionDenials,
1672
+ structured_output: structuredOutputFromTool,
1673
+ fast_mode_state: getFastModeState(mainLoopModel, initialAppState.fastMode),
1674
+ uuid: randomUUID()
1675
+ };
1676
+ }
1677
+ interrupt() {
1678
+ this.abortController.abort();
1679
+ }
1680
+ getMessages() {
1681
+ return this.mutableMessages;
1682
+ }
1683
+ getReadFileState() {
1684
+ return this.readFileState;
1685
+ }
1686
+ getSessionId() {
1687
+ return getSessionId();
1688
+ }
1689
+ setModel(model) {
1690
+ this.config.userSpecifiedModel = model;
1691
+ }
1692
+ }
1693
+ async function* ask({
1694
+ commands,
1695
+ prompt,
1696
+ promptUuid,
1697
+ isMeta,
1698
+ cwd,
1699
+ tools,
1700
+ mcpClients,
1701
+ verbose = false,
1702
+ thinkingConfig,
1703
+ maxTurns,
1704
+ maxBudgetUsd,
1705
+ taskBudget,
1706
+ canUseTool,
1707
+ mutableMessages = [],
1708
+ getReadFileCache,
1709
+ setReadFileCache,
1710
+ customSystemPrompt,
1711
+ appendSystemPrompt,
1712
+ userSpecifiedModel,
1713
+ fallbackModel,
1714
+ jsonSchema,
1715
+ getAppState,
1716
+ setAppState,
1717
+ abortController,
1718
+ replayUserMessages = false,
1719
+ includePartialMessages = false,
1720
+ handleElicitation,
1721
+ agents = [],
1722
+ setSDKStatus,
1723
+ orphanedPermission
1724
+ }) {
1725
+ const engine = new QueryEngine({
1726
+ cwd,
1727
+ tools,
1728
+ commands,
1729
+ mcpClients,
1730
+ agents: agents ?? [],
1731
+ canUseTool,
1732
+ getAppState,
1733
+ setAppState,
1734
+ initialMessages: mutableMessages,
1735
+ readFileCache: cloneFileStateCache(getReadFileCache()),
1736
+ customSystemPrompt,
1737
+ appendSystemPrompt,
1738
+ userSpecifiedModel,
1739
+ fallbackModel,
1740
+ thinkingConfig,
1741
+ maxTurns,
1742
+ maxBudgetUsd,
1743
+ taskBudget,
1744
+ jsonSchema,
1745
+ verbose,
1746
+ handleElicitation,
1747
+ replayUserMessages,
1748
+ includePartialMessages,
1749
+ setSDKStatus,
1750
+ abortController,
1751
+ orphanedPermission,
1752
+ ...{}
1753
+ });
1754
+ try {
1755
+ yield* engine.submitMessage(prompt, {
1756
+ uuid: promptUuid,
1757
+ isMeta
1758
+ });
1759
+ } finally {
1760
+ setReadFileCache(engine.getReadFileState());
1761
+ }
1762
+ }
1763
+
1764
+ // src/cli/print.ts
1765
+ init_fileStateCache();
1766
+ init_path();
1767
+ init_queryHelpers();
1768
+ init_hookEvents();
1769
+
1770
+ // src/utils/filePersistence/filePersistence.ts
1771
+ init_analytics();
1772
+ init_filesApi();
1773
+ init_cwd();
1774
+ init_errors();
1775
+ init_log();
1776
+ init_sessionIngressAuth();
1777
+ init_outputsScanner();
1778
+
1779
+ // src/cli/print.ts
1780
+ init_AsyncHookRegistry();
1781
+ init_gracefulShutdown();
1782
+ init_cleanupRegistry();
1783
+
1784
+ // src/utils/idleTimeout.ts
1785
+ init_debug();
1786
+ init_gracefulShutdown();
1787
+ function createIdleTimeoutManager(isIdle) {
1788
+ const exitAfterStopDelay = process.env.CLAUDE_CODE_EXIT_AFTER_STOP_DELAY;
1789
+ const delayMs = exitAfterStopDelay ? parseInt(exitAfterStopDelay, 10) : null;
1790
+ const isValidDelay = delayMs && !isNaN(delayMs) && delayMs > 0;
1791
+ let timer = null;
1792
+ let lastIdleTime = 0;
1793
+ return {
1794
+ start() {
1795
+ if (timer) {
1796
+ clearTimeout(timer);
1797
+ timer = null;
1798
+ }
1799
+ if (isValidDelay) {
1800
+ lastIdleTime = Date.now();
1801
+ timer = setTimeout(() => {
1802
+ const idleDuration = Date.now() - lastIdleTime;
1803
+ if (isIdle() && idleDuration >= delayMs) {
1804
+ logForDebugging(`Exiting after ${delayMs}ms of idle time`);
1805
+ gracefulShutdownSync();
1806
+ }
1807
+ }, delayMs);
1808
+ }
1809
+ },
1810
+ stop() {
1811
+ if (timer) {
1812
+ clearTimeout(timer);
1813
+ timer = null;
1814
+ }
1815
+ }
1816
+ };
1817
+ }
1818
+
1819
+ // src/cli/print.ts
1820
+ init_cwd();
1821
+ init_omit();
1822
+ init_reject();
1823
+ init_policyLimits();
1824
+ init_product();
1825
+ init_bridgeStatusUtil();
1826
+ import { cwd } from "process";
1827
+ init_permissions();
1828
+ init_json();
1829
+ init_abortController();
1830
+ init_combinedAbortSignal();
1831
+ init_sessionTitle();
1832
+ init_sideQuestion();
1833
+ init_sessionStart();
1834
+ init_outputStyles();
1835
+ init_xml();
1836
+ init_settings();
1837
+ init_changeDetector();
1838
+ init_applySettingsChange();
1839
+ init_fastMode();
1840
+ init_permissionSetup();
1841
+ init_promptSuggestion();
1842
+ init_forkedAgent();
1843
+ init_auth();
1844
+ init_oauth();
1845
+ init_auth3();
1846
+ init_providers();
1847
+ init_awsAuthStatusManager();
1848
+ init_state();
1849
+ init_SyntheticOutputTool();
1850
+
1851
+ // src/utils/sessionUrl.ts
1852
+ init_uuid();
1853
+ import { randomUUID as randomUUID2 } from "crypto";
1854
+ function parseSessionIdentifier(resumeIdentifier) {
1855
+ if (resumeIdentifier.toLowerCase().endsWith(".jsonl")) {
1856
+ return {
1857
+ sessionId: randomUUID2(),
1858
+ ingressUrl: null,
1859
+ isUrl: false,
1860
+ jsonlFile: resumeIdentifier,
1861
+ isJsonlFile: true
1862
+ };
1863
+ }
1864
+ if (validateUuid(resumeIdentifier)) {
1865
+ return {
1866
+ sessionId: resumeIdentifier,
1867
+ ingressUrl: null,
1868
+ isUrl: false,
1869
+ jsonlFile: null,
1870
+ isJsonlFile: false
1871
+ };
1872
+ }
1873
+ try {
1874
+ const url = new URL(resumeIdentifier);
1875
+ return {
1876
+ sessionId: randomUUID2(),
1877
+ ingressUrl: url.href,
1878
+ isUrl: true,
1879
+ jsonlFile: null,
1880
+ isJsonlFile: false
1881
+ };
1882
+ } catch {}
1883
+ return null;
1884
+ }
1885
+
1886
+ // src/cli/print.ts
1887
+ init_sessionStorage();
1888
+ init_commitAttribution();
1889
+ init_client();
1890
+ init_config2();
1891
+ init_auth2();
1892
+ init_elicitationHandler();
1893
+ init_hooks();
1894
+ init_types();
1895
+ init_mcpStringUtils();
1896
+ init_utils();
1897
+ init_vscodeSdkMcp();
1898
+ init_config2();
1899
+ init_grove();
1900
+ init_mappers();
1901
+ init_messages();
1902
+ init_context_noninteractive();
1903
+ init_xml();
1904
+ init_claudeAiLimits();
1905
+ init_model();
1906
+ init_modelOptions();
1907
+ init_effort();
1908
+ init_thinking();
1909
+ init_betas();
1910
+ init_modelStrings();
1911
+ init_state();
1912
+ init_workloadContext();
1913
+ init_fileHistory();
1914
+ import { randomUUID as randomUUID3 } from "crypto";
1915
+ init_sandbox_adapter();
1916
+ init_headlessProfiler();
1917
+ init_queryProfiler();
1918
+ init_ids();
1919
+ init_slowOperations();
1920
+ init_commands();
1921
+ init_envUtils();
1922
+
1923
+ // src/utils/plugins/headlessPluginInstall.ts
1924
+ init_analytics();
1925
+ init_cleanupRegistry();
1926
+ init_debug();
1927
+ init_diagLogs();
1928
+ init_fsOperations();
1929
+ init_log();
1930
+ init_marketplaceManager();
1931
+ init_pluginLoader();
1932
+ init_zipCache();
1933
+
1934
+ // src/utils/plugins/zipCacheAdapters.ts
1935
+ init_debug();
1936
+ init_slowOperations();
1937
+ init_marketplaceManager();
1938
+ init_schemas();
1939
+ init_zipCache();
1940
+ import { readFile } from "fs/promises";
1941
+ import { join } from "path";
1942
+ async function readZipCacheKnownMarketplaces() {
1943
+ try {
1944
+ const content = await readFile(getZipCacheKnownMarketplacesPath(), "utf-8");
1945
+ const parsed = KnownMarketplacesFileSchema().safeParse(jsonParse(content));
1946
+ if (!parsed.success) {
1947
+ logForDebugging(`Invalid known_marketplaces.json in zip cache: ${parsed.error.message}`, { level: "error" });
1948
+ return {};
1949
+ }
1950
+ return parsed.data;
1951
+ } catch {
1952
+ return {};
1953
+ }
1954
+ }
1955
+ async function writeZipCacheKnownMarketplaces(data) {
1956
+ await atomicWriteToZipCache(getZipCacheKnownMarketplacesPath(), jsonStringify(data, null, 2));
1957
+ }
1958
+ async function saveMarketplaceJsonToZipCache(marketplaceName, installLocation) {
1959
+ const zipCachePath = getPluginZipCachePath();
1960
+ if (!zipCachePath) {
1961
+ return;
1962
+ }
1963
+ const content = await readMarketplaceJsonContent(installLocation);
1964
+ if (content !== null) {
1965
+ const relPath = getMarketplaceJsonRelativePath(marketplaceName);
1966
+ await atomicWriteToZipCache(join(zipCachePath, relPath), content);
1967
+ }
1968
+ }
1969
+ async function readMarketplaceJsonContent(dir) {
1970
+ const candidates = [
1971
+ join(dir, ".claude-plugin", "marketplace.json"),
1972
+ join(dir, "marketplace.json"),
1973
+ dir
1974
+ ];
1975
+ for (const candidate of candidates) {
1976
+ try {
1977
+ return await readFile(candidate, "utf-8");
1978
+ } catch {}
1979
+ }
1980
+ return null;
1981
+ }
1982
+ async function syncMarketplacesToZipCache() {
1983
+ const knownMarketplaces = await loadKnownMarketplacesConfigSafe();
1984
+ for (const [name, entry] of Object.entries(knownMarketplaces)) {
1985
+ if (!entry.installLocation)
1986
+ continue;
1987
+ try {
1988
+ await saveMarketplaceJsonToZipCache(name, entry.installLocation);
1989
+ } catch (error) {
1990
+ logForDebugging(`Failed to save marketplace JSON for ${name}: ${error}`);
1991
+ }
1992
+ }
1993
+ const zipCacheKnownMarketplaces = await readZipCacheKnownMarketplaces();
1994
+ const mergedKnownMarketplaces = {
1995
+ ...zipCacheKnownMarketplaces,
1996
+ ...knownMarketplaces
1997
+ };
1998
+ await writeZipCacheKnownMarketplaces(mergedKnownMarketplaces);
1999
+ }
2000
+
2001
+ // src/utils/plugins/headlessPluginInstall.ts
2002
+ async function installPluginsForHeadless() {
2003
+ const zipCacheMode = isPluginZipCacheEnabled();
2004
+ logForDebugging(`installPluginsForHeadless: starting${zipCacheMode ? " (zip cache mode)" : ""}`);
2005
+ const seedChanged = await registerSeedMarketplaces();
2006
+ if (seedChanged) {
2007
+ clearMarketplacesCache();
2008
+ clearPluginCache("headlessPluginInstall: seed marketplaces registered");
2009
+ }
2010
+ if (zipCacheMode) {
2011
+ await getFsImplementation().mkdir(getZipCacheMarketplacesDir());
2012
+ await getFsImplementation().mkdir(getZipCachePluginsDir());
2013
+ }
2014
+ const declaredCount = Object.keys(getDeclaredMarketplaces()).length;
2015
+ const metrics = {
2016
+ marketplaces_installed: 0,
2017
+ delisted_count: 0
2018
+ };
2019
+ let pluginsChanged = seedChanged;
2020
+ try {
2021
+ if (declaredCount === 0) {
2022
+ logForDebugging("installPluginsForHeadless: no marketplaces declared");
2023
+ } else {
2024
+ const reconcileResult = await withDiagnosticsTiming("headless_marketplace_reconcile", () => reconcileMarketplaces({
2025
+ skip: zipCacheMode ? (_name, source) => !isMarketplaceSourceSupportedByZipCache(source) : undefined,
2026
+ onProgress: (event) => {
2027
+ if (event.type === "installed") {
2028
+ logForDebugging(`installPluginsForHeadless: installed marketplace ${event.name}`);
2029
+ } else if (event.type === "failed") {
2030
+ logForDebugging(`installPluginsForHeadless: failed to install marketplace ${event.name}: ${event.error}`);
2031
+ }
2032
+ }
2033
+ }), (r) => ({
2034
+ installed_count: r.installed.length,
2035
+ updated_count: r.updated.length,
2036
+ failed_count: r.failed.length,
2037
+ skipped_count: r.skipped.length
2038
+ }));
2039
+ if (reconcileResult.skipped.length > 0) {
2040
+ logForDebugging(`installPluginsForHeadless: skipped ${reconcileResult.skipped.length} marketplace(s) unsupported by zip cache: ${reconcileResult.skipped.join(", ")}`);
2041
+ }
2042
+ const marketplacesChanged = reconcileResult.installed.length + reconcileResult.updated.length;
2043
+ if (marketplacesChanged > 0) {
2044
+ clearMarketplacesCache();
2045
+ clearPluginCache("headlessPluginInstall: marketplaces reconciled");
2046
+ pluginsChanged = true;
2047
+ }
2048
+ metrics.marketplaces_installed = marketplacesChanged;
2049
+ }
2050
+ if (zipCacheMode) {
2051
+ await syncMarketplacesToZipCache();
2052
+ }
2053
+ const newlyDelisted = await detectAndUninstallDelistedPlugins();
2054
+ metrics.delisted_count = newlyDelisted.length;
2055
+ if (newlyDelisted.length > 0) {
2056
+ pluginsChanged = true;
2057
+ }
2058
+ if (pluginsChanged) {
2059
+ clearPluginCache("headlessPluginInstall: plugins changed");
2060
+ }
2061
+ if (zipCacheMode) {
2062
+ registerCleanup(cleanupSessionPluginCache);
2063
+ }
2064
+ return pluginsChanged;
2065
+ } catch (error) {
2066
+ logError(error);
2067
+ return false;
2068
+ } finally {
2069
+ logEvent("tengu_headless_plugin_install", metrics);
2070
+ }
2071
+ }
2072
+
2073
+ // src/cli/print.ts
2074
+ init_refresh();
2075
+ init_pluginLoader();
2076
+ init_teammate();
2077
+ init_teammateMailbox();
2078
+ init_teamHelpers();
2079
+ init_tasks();
2080
+ init_framework();
2081
+ init_types2();
2082
+ init_stopTask();
2083
+ init_sdkEventQueue();
2084
+ init_growthbook();
2085
+ init_errors();
2086
+ init_sleep();
2087
+ init_paths();
2088
+ var cronSchedulerModule = (init_cronScheduler(), __toCommonJS(exports_cronScheduler));
2089
+ var cronJitterConfigModule = (init_cronJitterConfig(), __toCommonJS(exports_cronJitterConfig));
2090
+ var cronGate = (init_prompt7(), __toCommonJS(exports_prompt));
2091
+ var extractMemoriesModule = (init_extractMemories(), __toCommonJS(exports_extractMemories));
2092
+ var SHUTDOWN_TEAM_PROMPT = `<system-reminder>
2093
+ You are running in non-interactive mode and cannot return a response to the user until your team is shut down.
2094
+
2095
+ You MUST shut down your team before preparing your final response:
2096
+ 1. Use requestShutdown to ask each team member to shut down gracefully
2097
+ 2. Wait for shutdown approvals
2098
+ 3. Use the cleanup operation to clean up the team
2099
+ 4. Only then provide your final response to the user
2100
+
2101
+ The user cannot receive your response until the team is completely shut down.
2102
+ </system-reminder>
2103
+
2104
+ Shut down your team and prepare your final response for the user.`;
2105
+ var MAX_RECEIVED_UUIDS = 1e4;
2106
+ var receivedMessageUuids = new Set;
2107
+ var receivedMessageUuidsOrder = [];
2108
+ function trackReceivedMessageUuid(uuid) {
2109
+ if (receivedMessageUuids.has(uuid)) {
2110
+ return false;
2111
+ }
2112
+ receivedMessageUuids.add(uuid);
2113
+ receivedMessageUuidsOrder.push(uuid);
2114
+ if (receivedMessageUuidsOrder.length > MAX_RECEIVED_UUIDS) {
2115
+ const toEvict = receivedMessageUuidsOrder.splice(0, receivedMessageUuidsOrder.length - MAX_RECEIVED_UUIDS);
2116
+ for (const old of toEvict) {
2117
+ receivedMessageUuids.delete(old);
2118
+ }
2119
+ }
2120
+ return true;
2121
+ }
2122
+ function toBlocks(v) {
2123
+ return typeof v === "string" ? [{ type: "text", text: v }] : v;
2124
+ }
2125
+ function joinPromptValues(values) {
2126
+ if (values.length === 1)
2127
+ return values[0];
2128
+ if (values.every((v) => typeof v === "string")) {
2129
+ return values.join(`
2130
+ `);
2131
+ }
2132
+ return values.flatMap(toBlocks);
2133
+ }
2134
+ function canBatchWith(head, next) {
2135
+ return next !== undefined && next.mode === "prompt" && next.workload === head.workload && next.isMeta === head.isMeta;
2136
+ }
2137
+ async function runHeadless(inputPrompt, getAppState, setAppState, commands, tools, sdkMcpConfigs, agents, options) {
2138
+ if (process.env.USER_TYPE === "ant" && isEnvTruthy(process.env.CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER)) {
2139
+ process.stderr.write(`
2140
+ Startup time: ${Math.round(process.uptime() * 1000)}ms
2141
+ `);
2142
+ process.exit(0);
2143
+ }
2144
+ if (false) {}
2145
+ settingsChangeDetector.subscribe((source) => {
2146
+ applySettingsChange(source, setAppState);
2147
+ if (isFastModeEnabled()) {
2148
+ setAppState((prev) => {
2149
+ const s = prev.settings;
2150
+ const fastMode = s.fastMode === true && !s.fastModePerSessionOptIn;
2151
+ return { ...prev, fastMode };
2152
+ });
2153
+ }
2154
+ });
2155
+ if (false) {}
2156
+ if (typeof Bun !== "undefined") {
2157
+ const gcTimer = setInterval(Bun.gc, 1000);
2158
+ gcTimer.unref();
2159
+ }
2160
+ headlessProfilerStartTurn();
2161
+ headlessProfilerCheckpoint("runHeadless_entry");
2162
+ if (await isQualifiedForGrove()) {
2163
+ await checkGroveForNonInteractive();
2164
+ }
2165
+ headlessProfilerCheckpoint("after_grove_check");
2166
+ initializeGrowthBook();
2167
+ if (options.resumeSessionAt && !options.resume) {
2168
+ process.stderr.write(`Error: --resume-session-at requires --resume
2169
+ `);
2170
+ gracefulShutdownSync(1);
2171
+ return;
2172
+ }
2173
+ if (options.rewindFiles && !options.resume) {
2174
+ process.stderr.write(`Error: --rewind-files requires --resume
2175
+ `);
2176
+ gracefulShutdownSync(1);
2177
+ return;
2178
+ }
2179
+ if (options.rewindFiles && inputPrompt) {
2180
+ process.stderr.write(`Error: --rewind-files is a standalone operation and cannot be used with a prompt
2181
+ `);
2182
+ gracefulShutdownSync(1);
2183
+ return;
2184
+ }
2185
+ const structuredIO = getStructuredIO(inputPrompt, options);
2186
+ if (options.outputFormat === "stream-json") {
2187
+ installStreamJsonStdoutGuard();
2188
+ }
2189
+ const sandboxUnavailableReason = SandboxManager.getSandboxUnavailableReason();
2190
+ if (sandboxUnavailableReason) {
2191
+ if (SandboxManager.isSandboxRequired()) {
2192
+ process.stderr.write(`
2193
+ Error: sandbox required but unavailable: ${sandboxUnavailableReason}
2194
+ ` + ` sandbox.failIfUnavailable is set \u2014 refusing to start without a working sandbox.
2195
+
2196
+ `);
2197
+ gracefulShutdownSync(1);
2198
+ return;
2199
+ }
2200
+ process.stderr.write(`
2201
+ \u26A0 Sandbox disabled: ${sandboxUnavailableReason}
2202
+ ` + ` Commands will run WITHOUT sandboxing. Network and filesystem restrictions will NOT be enforced.
2203
+
2204
+ `);
2205
+ } else if (SandboxManager.isSandboxingEnabled()) {
2206
+ try {
2207
+ await SandboxManager.initialize(structuredIO.createSandboxAskCallback());
2208
+ } catch (err) {
2209
+ process.stderr.write(`
2210
+ \u274C Sandbox Error: ${errorMessage(err)}
2211
+ `);
2212
+ gracefulShutdownSync(1, "other");
2213
+ return;
2214
+ }
2215
+ }
2216
+ if (options.outputFormat === "stream-json" && options.verbose) {
2217
+ registerHookEventHandler((event) => {
2218
+ const message = (() => {
2219
+ switch (event.type) {
2220
+ case "started":
2221
+ return {
2222
+ type: "system",
2223
+ subtype: "hook_started",
2224
+ hook_id: event.hookId,
2225
+ hook_name: event.hookName,
2226
+ hook_event: event.hookEvent,
2227
+ uuid: randomUUID3(),
2228
+ session_id: getSessionId()
2229
+ };
2230
+ case "progress":
2231
+ return {
2232
+ type: "system",
2233
+ subtype: "hook_progress",
2234
+ hook_id: event.hookId,
2235
+ hook_name: event.hookName,
2236
+ hook_event: event.hookEvent,
2237
+ stdout: event.stdout,
2238
+ stderr: event.stderr,
2239
+ output: event.output,
2240
+ uuid: randomUUID3(),
2241
+ session_id: getSessionId()
2242
+ };
2243
+ case "response":
2244
+ return {
2245
+ type: "system",
2246
+ subtype: "hook_response",
2247
+ hook_id: event.hookId,
2248
+ hook_name: event.hookName,
2249
+ hook_event: event.hookEvent,
2250
+ output: event.output,
2251
+ stdout: event.stdout,
2252
+ stderr: event.stderr,
2253
+ exit_code: event.exitCode,
2254
+ outcome: event.outcome,
2255
+ uuid: randomUUID3(),
2256
+ session_id: getSessionId()
2257
+ };
2258
+ }
2259
+ })();
2260
+ structuredIO.write(message);
2261
+ });
2262
+ }
2263
+ if (options.setupTrigger) {
2264
+ await processSetupHooks(options.setupTrigger);
2265
+ }
2266
+ headlessProfilerCheckpoint("before_loadInitialMessages");
2267
+ const appState = getAppState();
2268
+ const {
2269
+ messages: initialMessages,
2270
+ turnInterruptionState,
2271
+ agentSetting: resumedAgentSetting
2272
+ } = await loadInitialMessages(setAppState, {
2273
+ continue: options.continue,
2274
+ teleport: options.teleport,
2275
+ resume: options.resume,
2276
+ resumeSessionAt: options.resumeSessionAt,
2277
+ forkSession: options.forkSession,
2278
+ outputFormat: options.outputFormat,
2279
+ sessionStartHooksPromise: options.sessionStartHooksPromise,
2280
+ restoredWorkerState: structuredIO.restoredWorkerState
2281
+ });
2282
+ const hookInitialUserMessage = takeInitialUserMessage();
2283
+ if (hookInitialUserMessage) {
2284
+ structuredIO.prependUserMessage(hookInitialUserMessage);
2285
+ }
2286
+ if (!options.agent && !getMainThreadAgentType() && resumedAgentSetting) {
2287
+ const { agentDefinition: restoredAgent } = restoreAgentFromSession(resumedAgentSetting, undefined, { activeAgents: agents, allAgents: agents });
2288
+ if (restoredAgent) {
2289
+ setAppState((prev) => ({ ...prev, agent: restoredAgent.agentType }));
2290
+ if (!options.systemPrompt && !isBuiltInAgent(restoredAgent)) {
2291
+ const agentSystemPrompt = restoredAgent.getSystemPrompt();
2292
+ if (agentSystemPrompt) {
2293
+ options.systemPrompt = agentSystemPrompt;
2294
+ }
2295
+ }
2296
+ saveAgentSetting(restoredAgent.agentType);
2297
+ }
2298
+ }
2299
+ if (initialMessages.length === 0 && process.exitCode !== undefined) {
2300
+ return;
2301
+ }
2302
+ if (options.rewindFiles) {
2303
+ const targetMessage = initialMessages.find((m) => m.uuid === options.rewindFiles);
2304
+ if (!targetMessage || targetMessage.type !== "user") {
2305
+ process.stderr.write(`Error: --rewind-files requires a user message UUID, but ${options.rewindFiles} is not a user message in this session
2306
+ `);
2307
+ gracefulShutdownSync(1);
2308
+ return;
2309
+ }
2310
+ const currentAppState = getAppState();
2311
+ const result = await handleRewindFiles(options.rewindFiles, currentAppState, setAppState, false);
2312
+ if (!result.canRewind) {
2313
+ process.stderr.write(`Error: ${result.error || "Unexpected error"}
2314
+ `);
2315
+ gracefulShutdownSync(1);
2316
+ return;
2317
+ }
2318
+ process.stdout.write(`Files rewound to state at message ${options.rewindFiles}
2319
+ `);
2320
+ gracefulShutdownSync(0);
2321
+ return;
2322
+ }
2323
+ const hasValidResumeSessionId = typeof options.resume === "string" && (Boolean(validateUuid(options.resume)) || options.resume.endsWith(".jsonl"));
2324
+ const isUsingSdkUrl = Boolean(options.sdkUrl);
2325
+ if (!inputPrompt && !hasValidResumeSessionId && !isUsingSdkUrl) {
2326
+ process.stderr.write(`Error: Input must be provided either through stdin or as a prompt argument when using --print
2327
+ `);
2328
+ gracefulShutdownSync(1);
2329
+ return;
2330
+ }
2331
+ if (options.outputFormat === "stream-json" && !options.verbose) {
2332
+ process.stderr.write(`Error: When using --print, --output-format=stream-json requires --verbose
2333
+ `);
2334
+ gracefulShutdownSync(1);
2335
+ return;
2336
+ }
2337
+ const allowedMcpTools = filterToolsByDenyRules(appState.mcp.tools, appState.toolPermissionContext);
2338
+ let filteredTools = [...tools, ...allowedMcpTools];
2339
+ const effectivePermissionPromptToolName = options.sdkUrl ? "stdio" : options.permissionPromptToolName;
2340
+ const onPermissionPrompt = (details) => {
2341
+ if (false) {}
2342
+ notifySessionStateChanged("requires_action", details);
2343
+ };
2344
+ const canUseTool = getCanUseToolFn(effectivePermissionPromptToolName, structuredIO, () => getAppState().mcp.tools, onPermissionPrompt);
2345
+ if (options.permissionPromptToolName) {
2346
+ filteredTools = filteredTools.filter((tool) => !toolMatchesName(tool, options.permissionPromptToolName));
2347
+ }
2348
+ registerProcessOutputErrorHandlers();
2349
+ headlessProfilerCheckpoint("after_loadInitialMessages");
2350
+ await ensureModelStringsInitialized();
2351
+ headlessProfilerCheckpoint("after_modelStrings");
2352
+ const needsFullArray = options.outputFormat === "json" && options.verbose;
2353
+ const messages = [];
2354
+ let lastMessage;
2355
+ const transformToStreamlined = null;
2356
+ headlessProfilerCheckpoint("before_runHeadlessStreaming");
2357
+ for await (const message of runHeadlessStreaming(structuredIO, appState.mcp.clients, [...commands, ...appState.mcp.commands], filteredTools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState)) {
2358
+ if (transformToStreamlined) {
2359
+ const transformed = transformToStreamlined(message);
2360
+ if (transformed) {
2361
+ await structuredIO.write(transformed);
2362
+ }
2363
+ } else if (options.outputFormat === "stream-json" && options.verbose) {
2364
+ await structuredIO.write(message);
2365
+ }
2366
+ if (message.type !== "control_response" && message.type !== "control_request" && message.type !== "control_cancel_request" && !(message.type === "system" && (message.subtype === "session_state_changed" || message.subtype === "task_notification" || message.subtype === "task_started" || message.subtype === "task_progress" || message.subtype === "post_turn_summary")) && message.type !== "stream_event" && message.type !== "keep_alive" && message.type !== "streamlined_text" && message.type !== "streamlined_tool_use_summary" && message.type !== "prompt_suggestion") {
2367
+ if (needsFullArray) {
2368
+ messages.push(message);
2369
+ }
2370
+ lastMessage = message;
2371
+ }
2372
+ }
2373
+ switch (options.outputFormat) {
2374
+ case "json":
2375
+ if (!lastMessage || lastMessage.type !== "result") {
2376
+ throw new Error("No messages returned");
2377
+ }
2378
+ if (options.verbose) {
2379
+ writeToStdout(jsonStringify(messages) + `
2380
+ `);
2381
+ break;
2382
+ }
2383
+ writeToStdout(jsonStringify(lastMessage) + `
2384
+ `);
2385
+ break;
2386
+ case "stream-json":
2387
+ break;
2388
+ default:
2389
+ if (!lastMessage || lastMessage.type !== "result") {
2390
+ throw new Error("No messages returned");
2391
+ }
2392
+ switch (lastMessage.subtype) {
2393
+ case "success":
2394
+ writeToStdout(lastMessage.result.endsWith(`
2395
+ `) ? lastMessage.result : lastMessage.result + `
2396
+ `);
2397
+ break;
2398
+ case "error_during_execution":
2399
+ writeToStdout(`Execution error`);
2400
+ break;
2401
+ case "error_max_turns":
2402
+ writeToStdout(`Error: Reached max turns (${options.maxTurns})`);
2403
+ break;
2404
+ case "error_max_budget_usd":
2405
+ writeToStdout(`Error: Exceeded USD budget (${options.maxBudgetUsd})`);
2406
+ break;
2407
+ case "error_max_structured_output_retries":
2408
+ writeToStdout(`Error: Failed to provide valid structured output after maximum retries`);
2409
+ }
2410
+ }
2411
+ logHeadlessProfilerTurn();
2412
+ if (isExtractModeActive()) {
2413
+ await extractMemoriesModule.drainPendingExtraction();
2414
+ }
2415
+ gracefulShutdownSync(lastMessage?.type === "result" && lastMessage?.is_error ? 1 : 0);
2416
+ }
2417
+ function runHeadlessStreaming(structuredIO, mcpClients, commands, tools, initialMessages, canUseTool, sdkMcpConfigs, getAppState, setAppState, agents, options, turnInterruptionState) {
2418
+ let running = false;
2419
+ let runPhase;
2420
+ let inputClosed = false;
2421
+ let shutdownPromptInjected = false;
2422
+ let heldBackResult = null;
2423
+ let abortController;
2424
+ const output = structuredIO.outbound;
2425
+ const sigintHandler = () => {
2426
+ logForDiagnosticsNoPII("info", "shutdown_signal", { signal: "SIGINT" });
2427
+ if (abortController && !abortController.signal.aborted) {
2428
+ abortController.abort();
2429
+ }
2430
+ gracefulShutdown(0);
2431
+ };
2432
+ process.on("SIGINT", sigintHandler);
2433
+ registerCleanup(async () => {
2434
+ const bg = {};
2435
+ for (const t of getRunningTasks(getAppState())) {
2436
+ if (isBackgroundTask(t))
2437
+ bg[t.type] = (bg[t.type] ?? 0) + 1;
2438
+ }
2439
+ logForDiagnosticsNoPII("info", "run_state_at_shutdown", {
2440
+ run_active: running,
2441
+ run_phase: runPhase,
2442
+ worker_status: getSessionState(),
2443
+ internal_events_pending: structuredIO.internalEventsPending,
2444
+ bg_tasks: bg
2445
+ });
2446
+ });
2447
+ setPermissionModeChangedListener((newMode) => {
2448
+ if (newMode === "default" || newMode === "acceptEdits" || newMode === "bypassPermissions" || newMode === "plan" || newMode === "auto" || newMode === "dontAsk") {
2449
+ output.enqueue({
2450
+ type: "system",
2451
+ subtype: "status",
2452
+ status: null,
2453
+ permissionMode: newMode,
2454
+ uuid: randomUUID3(),
2455
+ session_id: getSessionId()
2456
+ });
2457
+ }
2458
+ });
2459
+ const suggestionState = {
2460
+ abortController: null,
2461
+ inflightPromise: null,
2462
+ lastEmitted: null,
2463
+ pendingSuggestion: null,
2464
+ pendingLastEmittedEntry: null
2465
+ };
2466
+ let unsubscribeAuthStatus;
2467
+ if (options.enableAuthStatus) {
2468
+ const authStatusManager = AwsAuthStatusManager.getInstance();
2469
+ unsubscribeAuthStatus = authStatusManager.subscribe((status) => {
2470
+ output.enqueue({
2471
+ type: "auth_status",
2472
+ isAuthenticating: status.isAuthenticating,
2473
+ output: status.output,
2474
+ error: status.error,
2475
+ uuid: randomUUID3(),
2476
+ session_id: getSessionId()
2477
+ });
2478
+ });
2479
+ }
2480
+ const rateLimitListener = (limits) => {
2481
+ const rateLimitInfo = toSDKRateLimitInfo(limits);
2482
+ if (rateLimitInfo) {
2483
+ output.enqueue({
2484
+ type: "rate_limit_event",
2485
+ rate_limit_info: rateLimitInfo,
2486
+ uuid: randomUUID3(),
2487
+ session_id: getSessionId()
2488
+ });
2489
+ }
2490
+ };
2491
+ statusListeners.add(rateLimitListener);
2492
+ const mutableMessages = initialMessages;
2493
+ let readFileState = extractReadFilesFromMessages(initialMessages, cwd(), READ_FILE_STATE_CACHE_SIZE);
2494
+ const pendingSeeds = createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE);
2495
+ const resumeInterruptedTurnEnv = process.env.CLAUDE_CODE_RESUME_INTERRUPTED_TURN;
2496
+ if (turnInterruptionState && turnInterruptionState.kind !== "none" && resumeInterruptedTurnEnv) {
2497
+ logForDebugging(`[print.ts] Auto-resuming interrupted turn (kind: ${turnInterruptionState.kind})`);
2498
+ removeInterruptedMessage(mutableMessages, turnInterruptionState.message);
2499
+ enqueue({
2500
+ mode: "prompt",
2501
+ value: turnInterruptionState.message.message.content,
2502
+ uuid: randomUUID3()
2503
+ });
2504
+ }
2505
+ const modelOptions = getModelOptions();
2506
+ const modelInfos = modelOptions.map((option) => {
2507
+ const modelId = option.value === null ? "default" : option.value;
2508
+ const resolvedModel = modelId === "default" ? getDefaultMainLoopModel() : parseUserSpecifiedModel(modelId);
2509
+ const hasEffort = modelSupportsEffort(resolvedModel);
2510
+ const hasAdaptiveThinking = modelSupportsAdaptiveThinking(resolvedModel);
2511
+ const hasFastMode = isFastModeSupportedByModel(option.value);
2512
+ const hasAutoMode = modelSupportsAutoMode(resolvedModel);
2513
+ return {
2514
+ name: modelId,
2515
+ value: modelId,
2516
+ displayName: option.label,
2517
+ description: option.description,
2518
+ ...hasEffort && {
2519
+ supportsEffort: true,
2520
+ supportedEffortLevels: modelSupportsMaxEffort(resolvedModel) ? [...EFFORT_LEVELS] : EFFORT_LEVELS.filter((l) => l !== "max")
2521
+ },
2522
+ ...hasAdaptiveThinking && { supportsAdaptiveThinking: true },
2523
+ ...hasFastMode && { supportsFastMode: true },
2524
+ ...hasAutoMode && { supportsAutoMode: true }
2525
+ };
2526
+ });
2527
+ let activeUserSpecifiedModel = options.userSpecifiedModel;
2528
+ function injectModelSwitchBreadcrumbs(modelArg, resolvedModel) {
2529
+ const breadcrumbs = createModelSwitchBreadcrumbs(modelArg, modelDisplayString(resolvedModel));
2530
+ mutableMessages.push(...breadcrumbs);
2531
+ for (const crumb of breadcrumbs) {
2532
+ if (typeof crumb.message.content === "string" && crumb.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`)) {
2533
+ output.enqueue({
2534
+ type: "user",
2535
+ content: crumb.message.content,
2536
+ message: crumb.message,
2537
+ session_id: getSessionId(),
2538
+ parent_tool_use_id: null,
2539
+ uuid: crumb.uuid,
2540
+ timestamp: crumb.timestamp,
2541
+ isReplay: true
2542
+ });
2543
+ }
2544
+ }
2545
+ }
2546
+ let sdkClients = [];
2547
+ let sdkTools = [];
2548
+ const elicitationRegistered = new Set;
2549
+ function registerElicitationHandlers(clients) {
2550
+ for (const connection of clients) {
2551
+ if (connection.type !== "connected" || elicitationRegistered.has(connection.name)) {
2552
+ continue;
2553
+ }
2554
+ if (connection.config.type === "sdk") {
2555
+ continue;
2556
+ }
2557
+ const serverName = connection.name;
2558
+ try {
2559
+ connection.client.setRequestHandler(ElicitRequestSchema, async (request, extra) => {
2560
+ logMCPDebug(serverName, `Elicitation request received in print mode: ${jsonStringify(request)}`);
2561
+ const mode = request.params.mode === "url" ? "url" : "form";
2562
+ logEvent("tengu_mcp_elicitation_shown", {
2563
+ mode
2564
+ });
2565
+ const hookResponse = await runElicitationHooks(serverName, request.params, extra.signal);
2566
+ if (hookResponse) {
2567
+ logMCPDebug(serverName, `Elicitation resolved by hook: ${jsonStringify(hookResponse)}`);
2568
+ logEvent("tengu_mcp_elicitation_response", {
2569
+ mode,
2570
+ action: hookResponse.action
2571
+ });
2572
+ return hookResponse;
2573
+ }
2574
+ const url = "url" in request.params ? request.params.url : undefined;
2575
+ const requestedSchema = "requestedSchema" in request.params ? request.params.requestedSchema : undefined;
2576
+ const elicitationId = "elicitationId" in request.params ? request.params.elicitationId : undefined;
2577
+ const rawResult = await structuredIO.handleElicitation(serverName, request.params.message, requestedSchema, extra.signal, mode, url, elicitationId);
2578
+ const result = await runElicitationResultHooks(serverName, rawResult, extra.signal, mode, elicitationId);
2579
+ logEvent("tengu_mcp_elicitation_response", {
2580
+ mode,
2581
+ action: result.action
2582
+ });
2583
+ return result;
2584
+ });
2585
+ connection.client.setNotificationHandler(ElicitationCompleteNotificationSchema, (notification) => {
2586
+ const { elicitationId } = notification.params;
2587
+ logMCPDebug(serverName, `Elicitation completion notification: ${elicitationId}`);
2588
+ executeNotificationHooks({
2589
+ message: `MCP server "${serverName}" confirmed elicitation ${elicitationId} complete`,
2590
+ notificationType: "elicitation_complete"
2591
+ });
2592
+ output.enqueue({
2593
+ type: "system",
2594
+ subtype: "elicitation_complete",
2595
+ mcp_server_name: serverName,
2596
+ elicitation_id: elicitationId,
2597
+ uuid: randomUUID3(),
2598
+ session_id: getSessionId()
2599
+ });
2600
+ });
2601
+ elicitationRegistered.add(serverName);
2602
+ } catch {}
2603
+ }
2604
+ }
2605
+ async function updateSdkMcp() {
2606
+ const currentServerNames = new Set(Object.keys(sdkMcpConfigs));
2607
+ const connectedServerNames = new Set(sdkClients.map((c) => c.name));
2608
+ const hasNewServers = Array.from(currentServerNames).some((name) => !connectedServerNames.has(name));
2609
+ const hasRemovedServers = Array.from(connectedServerNames).some((name) => !currentServerNames.has(name));
2610
+ const hasPendingSdkClients = sdkClients.some((c) => c.type === "pending");
2611
+ const hasFailedSdkClients = sdkClients.some((c) => c.type === "failed");
2612
+ const haveServersChanged = hasNewServers || hasRemovedServers || hasPendingSdkClients || hasFailedSdkClients;
2613
+ if (haveServersChanged) {
2614
+ for (const client of sdkClients) {
2615
+ if (!currentServerNames.has(client.name)) {
2616
+ if (client.type === "connected") {
2617
+ await client.cleanup();
2618
+ }
2619
+ }
2620
+ }
2621
+ const sdkSetup = await setupSdkMcpClients(sdkMcpConfigs, (serverName, message) => structuredIO.sendMcpMessage(serverName, message));
2622
+ sdkClients = sdkSetup.clients;
2623
+ sdkTools = sdkSetup.tools;
2624
+ const allSdkNames = uniq([...connectedServerNames, ...currentServerNames]);
2625
+ setAppState((prev) => ({
2626
+ ...prev,
2627
+ mcp: {
2628
+ ...prev.mcp,
2629
+ tools: [
2630
+ ...prev.mcp.tools.filter((t) => !allSdkNames.some((name) => t.name.startsWith(getMcpPrefix(name)))),
2631
+ ...sdkTools
2632
+ ]
2633
+ }
2634
+ }));
2635
+ setupVscodeSdkMcp(sdkClients);
2636
+ }
2637
+ }
2638
+ updateSdkMcp();
2639
+ let dynamicMcpState = {
2640
+ clients: [],
2641
+ tools: [],
2642
+ configs: {}
2643
+ };
2644
+ const buildAllTools = (appState) => {
2645
+ const assembledTools = assembleToolPool(appState.toolPermissionContext, appState.mcp.tools);
2646
+ let allTools = uniqBy_default(mergeAndFilterTools([...tools, ...sdkTools, ...dynamicMcpState.tools], assembledTools, appState.toolPermissionContext.mode), "name");
2647
+ if (options.permissionPromptToolName) {
2648
+ allTools = allTools.filter((tool) => !toolMatchesName(tool, options.permissionPromptToolName));
2649
+ }
2650
+ const initJsonSchema = getInitJsonSchema();
2651
+ if (initJsonSchema && !options.jsonSchema) {
2652
+ const syntheticOutputResult = createSyntheticOutputTool(initJsonSchema);
2653
+ if ("tool" in syntheticOutputResult) {
2654
+ allTools = [...allTools, syntheticOutputResult.tool];
2655
+ }
2656
+ }
2657
+ return allTools;
2658
+ };
2659
+ let bridgeHandle = null;
2660
+ let bridgeLastForwardedIndex = 0;
2661
+ function forwardMessagesToBridge() {
2662
+ if (!bridgeHandle)
2663
+ return;
2664
+ const startIndex = Math.min(bridgeLastForwardedIndex, mutableMessages.length);
2665
+ const newMessages = mutableMessages.slice(startIndex).filter((m) => m.type === "user" || m.type === "assistant");
2666
+ bridgeLastForwardedIndex = mutableMessages.length;
2667
+ if (newMessages.length > 0) {
2668
+ bridgeHandle.writeMessages(newMessages);
2669
+ }
2670
+ }
2671
+ let mcpChangesPromise = Promise.resolve({
2672
+ response: {
2673
+ added: [],
2674
+ removed: [],
2675
+ errors: {}
2676
+ },
2677
+ sdkServersChanged: false
2678
+ });
2679
+ function applyMcpServerChanges(servers) {
2680
+ const doWork = async () => {
2681
+ const oldSdkClientNames = new Set(sdkClients.map((c) => c.name));
2682
+ const result = await handleMcpSetServers(servers, { configs: sdkMcpConfigs, clients: sdkClients, tools: sdkTools }, dynamicMcpState, setAppState);
2683
+ for (const key of Object.keys(sdkMcpConfigs)) {
2684
+ delete sdkMcpConfigs[key];
2685
+ }
2686
+ Object.assign(sdkMcpConfigs, result.newSdkState.configs);
2687
+ sdkClients = result.newSdkState.clients;
2688
+ sdkTools = result.newSdkState.tools;
2689
+ dynamicMcpState = result.newDynamicState;
2690
+ if (result.sdkServersChanged) {
2691
+ const newSdkClientNames = new Set(sdkClients.map((c) => c.name));
2692
+ const allSdkNames = uniq([...oldSdkClientNames, ...newSdkClientNames]);
2693
+ setAppState((prev) => ({
2694
+ ...prev,
2695
+ mcp: {
2696
+ ...prev.mcp,
2697
+ tools: [
2698
+ ...prev.mcp.tools.filter((t) => !allSdkNames.some((name) => t.name.startsWith(getMcpPrefix(name)))),
2699
+ ...sdkTools
2700
+ ]
2701
+ }
2702
+ }));
2703
+ }
2704
+ return {
2705
+ response: result.response,
2706
+ sdkServersChanged: result.sdkServersChanged
2707
+ };
2708
+ };
2709
+ mcpChangesPromise = mcpChangesPromise.then(doWork, doWork);
2710
+ return mcpChangesPromise;
2711
+ }
2712
+ function buildMcpServerStatuses() {
2713
+ const currentAppState = getAppState();
2714
+ const currentMcpClients = currentAppState.mcp.clients;
2715
+ const allMcpTools = uniqBy_default([...currentAppState.mcp.tools, ...dynamicMcpState.tools], "name");
2716
+ const existingNames = new Set([
2717
+ ...currentMcpClients.map((c) => c.name),
2718
+ ...sdkClients.map((c) => c.name)
2719
+ ]);
2720
+ return [
2721
+ ...currentMcpClients,
2722
+ ...sdkClients,
2723
+ ...dynamicMcpState.clients.filter((c) => !existingNames.has(c.name))
2724
+ ].map((connection) => {
2725
+ let config;
2726
+ if (connection.config.type === "sse" || connection.config.type === "http") {
2727
+ config = {
2728
+ type: connection.config.type,
2729
+ url: connection.config.url,
2730
+ headers: connection.config.headers,
2731
+ oauth: connection.config.oauth
2732
+ };
2733
+ } else if (connection.config.type === "claudeai-proxy") {
2734
+ config = {
2735
+ type: "claudeai-proxy",
2736
+ url: connection.config.url,
2737
+ id: connection.config.id
2738
+ };
2739
+ } else if (connection.config.type === "stdio" || connection.config.type === undefined) {
2740
+ const stdioConfig = connection.config;
2741
+ config = {
2742
+ type: "stdio",
2743
+ command: stdioConfig.command,
2744
+ args: stdioConfig.args
2745
+ };
2746
+ }
2747
+ const serverTools = connection.type === "connected" ? filterToolsByServer(allMcpTools, connection.name).map((tool) => ({
2748
+ name: tool.mcpInfo?.toolName ?? tool.name,
2749
+ annotations: {
2750
+ readOnly: tool.isReadOnly({}) || undefined,
2751
+ destructive: tool.isDestructive?.({}) || undefined,
2752
+ openWorld: tool.isOpenWorld?.({}) || undefined
2753
+ }
2754
+ })) : undefined;
2755
+ let capabilities;
2756
+ if (false) {}
2757
+ return {
2758
+ name: connection.name,
2759
+ status: connection.type,
2760
+ serverInfo: connection.type === "connected" ? connection.serverInfo : undefined,
2761
+ error: connection.type === "failed" ? connection.error : undefined,
2762
+ config,
2763
+ scope: connection.config.scope,
2764
+ tools: serverTools,
2765
+ capabilities
2766
+ };
2767
+ });
2768
+ }
2769
+ async function installPluginsAndApplyMcpInBackground() {
2770
+ try {
2771
+ await Promise.all([
2772
+ Promise.resolve(),
2773
+ withDiagnosticsTiming("headless_managed_settings_wait", () => waitForRemoteManagedSettingsToLoad())
2774
+ ]);
2775
+ const pluginsInstalled = await installPluginsForHeadless();
2776
+ if (pluginsInstalled) {
2777
+ await applyPluginMcpDiff();
2778
+ }
2779
+ } catch (error) {
2780
+ logError(error);
2781
+ }
2782
+ }
2783
+ let pluginInstallPromise = null;
2784
+ if (!isBareMode()) {
2785
+ if (isEnvTruthy(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL)) {
2786
+ pluginInstallPromise = installPluginsAndApplyMcpInBackground();
2787
+ } else {
2788
+ installPluginsAndApplyMcpInBackground();
2789
+ }
2790
+ }
2791
+ const idleTimeout = createIdleTimeoutManager(() => !running);
2792
+ let currentCommands = commands;
2793
+ let currentAgents = agents;
2794
+ async function refreshPluginState() {
2795
+ const { agentDefinitions: freshAgentDefs } = await refreshActivePlugins(setAppState);
2796
+ currentCommands = await getCommands(cwd());
2797
+ const sdkAgents = currentAgents.filter((a) => a.source === "flagSettings");
2798
+ currentAgents = [...freshAgentDefs.allAgents, ...sdkAgents];
2799
+ }
2800
+ async function applyPluginMcpDiff() {
2801
+ const { servers: newConfigs } = await getAllMcpConfigs();
2802
+ const supportedConfigs = {};
2803
+ for (const [name, config] of Object.entries(newConfigs)) {
2804
+ const type = config.type;
2805
+ if (type === undefined || type === "stdio" || type === "sse" || type === "http" || type === "sdk") {
2806
+ supportedConfigs[name] = config;
2807
+ }
2808
+ }
2809
+ for (const [name, config] of Object.entries(sdkMcpConfigs)) {
2810
+ if (config.type === "sdk" && !(name in supportedConfigs)) {
2811
+ supportedConfigs[name] = config;
2812
+ }
2813
+ }
2814
+ const { response, sdkServersChanged } = await applyMcpServerChanges(supportedConfigs);
2815
+ if (sdkServersChanged) {
2816
+ updateSdkMcp();
2817
+ }
2818
+ logForDebugging(`Headless MCP refresh: added=${response.added.length}, removed=${response.removed.length}`);
2819
+ }
2820
+ const unsubscribeSkillChanges = skillChangeDetector.subscribe(() => {
2821
+ clearCommandsCache();
2822
+ getCommands(cwd()).then((newCommands) => {
2823
+ currentCommands = newCommands;
2824
+ });
2825
+ });
2826
+ const scheduleProactiveTick = undefined;
2827
+ subscribeToCommandQueue(() => {
2828
+ if (abortController && getCommandsByMaxPriority("now").length > 0) {
2829
+ abortController.abort("interrupt");
2830
+ }
2831
+ });
2832
+ const run = async () => {
2833
+ if (running) {
2834
+ return;
2835
+ }
2836
+ running = true;
2837
+ runPhase = undefined;
2838
+ notifySessionStateChanged("running");
2839
+ idleTimeout.stop();
2840
+ headlessProfilerCheckpoint("run_entry");
2841
+ await updateSdkMcp();
2842
+ headlessProfilerCheckpoint("after_updateSdkMcp");
2843
+ if (pluginInstallPromise) {
2844
+ const timeoutMs = parseInt(process.env.CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS || "", 10);
2845
+ if (timeoutMs > 0) {
2846
+ const timeout = sleep(timeoutMs).then(() => "timeout");
2847
+ const result = await Promise.race([pluginInstallPromise, timeout]);
2848
+ if (result === "timeout") {
2849
+ logError(new Error(`CLAUDE_CODE_SYNC_PLUGIN_INSTALL: plugin installation timed out after ${timeoutMs}ms`));
2850
+ logEvent("tengu_sync_plugin_install_timeout", {
2851
+ timeout_ms: timeoutMs
2852
+ });
2853
+ }
2854
+ } else {
2855
+ await pluginInstallPromise;
2856
+ }
2857
+ pluginInstallPromise = null;
2858
+ await refreshPluginState();
2859
+ const { setupPluginHookHotReload } = await import("./chunk-8tj3ttfr.js");
2860
+ setupPluginHookHotReload();
2861
+ }
2862
+ const isMainThread = (cmd) => cmd.agentId === undefined;
2863
+ try {
2864
+ let command;
2865
+ let waitingForAgents = false;
2866
+ const drainCommandQueue = async () => {
2867
+ while (command = dequeue(isMainThread)) {
2868
+ if (command.mode !== "prompt" && command.mode !== "orphaned-permission" && command.mode !== "task-notification") {
2869
+ throw new Error("only prompt commands are supported in streaming mode");
2870
+ }
2871
+ const batch = [command];
2872
+ if (command.mode === "prompt") {
2873
+ while (canBatchWith(command, peek(isMainThread))) {
2874
+ batch.push(dequeue(isMainThread));
2875
+ }
2876
+ if (batch.length > 1) {
2877
+ command = {
2878
+ ...command,
2879
+ value: joinPromptValues(batch.map((c) => c.value)),
2880
+ uuid: batch.findLast((c) => c.uuid)?.uuid ?? command.uuid
2881
+ };
2882
+ }
2883
+ }
2884
+ const batchUuids = batch.map((c) => c.uuid).filter((u) => u !== undefined);
2885
+ if (options.replayUserMessages && batch.length > 1) {
2886
+ for (const c of batch) {
2887
+ if (c.uuid && c.uuid !== command.uuid) {
2888
+ output.enqueue({
2889
+ type: "user",
2890
+ content: c.value,
2891
+ message: { role: "user", content: c.value },
2892
+ session_id: getSessionId(),
2893
+ parent_tool_use_id: null,
2894
+ uuid: c.uuid,
2895
+ isReplay: true
2896
+ });
2897
+ }
2898
+ }
2899
+ }
2900
+ const appState = getAppState();
2901
+ const allMcpClients = [
2902
+ ...appState.mcp.clients,
2903
+ ...sdkClients,
2904
+ ...dynamicMcpState.clients
2905
+ ];
2906
+ registerElicitationHandlers(allMcpClients);
2907
+ for (const client of allMcpClients) {
2908
+ reregisterChannelHandlerAfterReconnect(client);
2909
+ }
2910
+ const allTools = buildAllTools(appState);
2911
+ for (const uuid of batchUuids) {
2912
+ notifyCommandLifecycle(uuid, "started");
2913
+ }
2914
+ if (command.mode === "task-notification") {
2915
+ const notificationText = typeof command.value === "string" ? command.value : "";
2916
+ const taskIdMatch = notificationText.match(/<task-id>([^<]+)<\/task-id>/);
2917
+ const toolUseIdMatch = notificationText.match(/<tool-use-id>([^<]+)<\/tool-use-id>/);
2918
+ const outputFileMatch = notificationText.match(/<output-file>([^<]+)<\/output-file>/);
2919
+ const statusMatch = notificationText.match(/<status>([^<]+)<\/status>/);
2920
+ const summaryMatch = notificationText.match(/<summary>([^<]+)<\/summary>/);
2921
+ const isValidStatus = (s) => s === "completed" || s === "failed" || s === "stopped" || s === "killed";
2922
+ const rawStatus = statusMatch?.[1];
2923
+ const status = isValidStatus(rawStatus) ? rawStatus === "killed" ? "stopped" : rawStatus : "completed";
2924
+ const usageMatch = notificationText.match(/<usage>([\s\S]*?)<\/usage>/);
2925
+ const usageContent = usageMatch?.[1] ?? "";
2926
+ const totalTokensMatch = usageContent.match(/<total_tokens>(\d+)<\/total_tokens>/);
2927
+ const toolUsesMatch = usageContent.match(/<tool_uses>(\d+)<\/tool_uses>/);
2928
+ const durationMsMatch = usageContent.match(/<duration_ms>(\d+)<\/duration_ms>/);
2929
+ if (statusMatch) {
2930
+ output.enqueue({
2931
+ type: "system",
2932
+ subtype: "task_notification",
2933
+ task_id: taskIdMatch?.[1] ?? "",
2934
+ tool_use_id: toolUseIdMatch?.[1],
2935
+ status,
2936
+ output_file: outputFileMatch?.[1] ?? "",
2937
+ summary: summaryMatch?.[1] ?? "",
2938
+ usage: totalTokensMatch && toolUsesMatch ? {
2939
+ total_tokens: parseInt(totalTokensMatch[1], 10),
2940
+ tool_uses: parseInt(toolUsesMatch[1], 10),
2941
+ duration_ms: durationMsMatch ? parseInt(durationMsMatch[1], 10) : 0
2942
+ } : undefined,
2943
+ session_id: getSessionId(),
2944
+ uuid: randomUUID3()
2945
+ });
2946
+ }
2947
+ }
2948
+ const input = command.value;
2949
+ if (structuredIO instanceof RemoteIO && command.mode === "prompt") {
2950
+ logEvent("tengu_bridge_message_received", {
2951
+ is_repl: false
2952
+ });
2953
+ }
2954
+ suggestionState.abortController?.abort();
2955
+ suggestionState.abortController = null;
2956
+ suggestionState.pendingSuggestion = null;
2957
+ suggestionState.pendingLastEmittedEntry = null;
2958
+ if (suggestionState.lastEmitted) {
2959
+ if (command.mode === "prompt") {
2960
+ const inputText = typeof input === "string" ? input : input.find((b) => b.type === "text")?.text;
2961
+ if (typeof inputText === "string") {
2962
+ logSuggestionOutcome(suggestionState.lastEmitted.text, inputText, suggestionState.lastEmitted.emittedAt, suggestionState.lastEmitted.promptId, suggestionState.lastEmitted.generationRequestId);
2963
+ }
2964
+ suggestionState.lastEmitted = null;
2965
+ }
2966
+ }
2967
+ abortController = createAbortController();
2968
+ const turnStartTime = undefined;
2969
+ headlessProfilerCheckpoint("before_ask");
2970
+ startQueryProfile();
2971
+ const cmd = command;
2972
+ await runWithWorkload(cmd.workload ?? options.workload, async () => {
2973
+ for await (const message of ask({
2974
+ commands: uniqBy_default([...currentCommands, ...appState.mcp.commands], "name"),
2975
+ prompt: input,
2976
+ promptUuid: cmd.uuid,
2977
+ isMeta: cmd.isMeta,
2978
+ cwd: cwd(),
2979
+ tools: allTools,
2980
+ verbose: options.verbose,
2981
+ mcpClients: allMcpClients,
2982
+ thinkingConfig: options.thinkingConfig,
2983
+ maxTurns: options.maxTurns,
2984
+ maxBudgetUsd: options.maxBudgetUsd,
2985
+ taskBudget: options.taskBudget,
2986
+ canUseTool,
2987
+ userSpecifiedModel: activeUserSpecifiedModel,
2988
+ fallbackModel: options.fallbackModel,
2989
+ jsonSchema: getInitJsonSchema() ?? options.jsonSchema,
2990
+ mutableMessages,
2991
+ getReadFileCache: () => pendingSeeds.size === 0 ? readFileState : mergeFileStateCaches(readFileState, pendingSeeds),
2992
+ setReadFileCache: (cache) => {
2993
+ readFileState = cache;
2994
+ for (const [path, seed] of pendingSeeds.entries()) {
2995
+ const existing = readFileState.get(path);
2996
+ if (!existing || seed.timestamp > existing.timestamp) {
2997
+ readFileState.set(path, seed);
2998
+ }
2999
+ }
3000
+ pendingSeeds.clear();
3001
+ },
3002
+ customSystemPrompt: options.systemPrompt,
3003
+ appendSystemPrompt: options.appendSystemPrompt,
3004
+ getAppState,
3005
+ setAppState,
3006
+ abortController,
3007
+ replayUserMessages: options.replayUserMessages,
3008
+ includePartialMessages: options.includePartialMessages,
3009
+ handleElicitation: (serverName, params, elicitSignal) => structuredIO.handleElicitation(serverName, params.message, undefined, elicitSignal, params.mode, params.url, "elicitationId" in params ? params.elicitationId : undefined),
3010
+ agents: currentAgents,
3011
+ orphanedPermission: cmd.orphanedPermission,
3012
+ setSDKStatus: (status) => {
3013
+ output.enqueue({
3014
+ type: "system",
3015
+ subtype: "status",
3016
+ status,
3017
+ session_id: getSessionId(),
3018
+ uuid: randomUUID3()
3019
+ });
3020
+ }
3021
+ })) {
3022
+ forwardMessagesToBridge();
3023
+ if (message.type === "result") {
3024
+ for (const event of drainSdkEvents()) {
3025
+ output.enqueue(event);
3026
+ }
3027
+ const currentState = getAppState();
3028
+ if (getRunningTasks(currentState).some((t) => (t.type === "local_agent" || t.type === "local_workflow") && isBackgroundTask(t))) {
3029
+ heldBackResult = message;
3030
+ } else {
3031
+ heldBackResult = null;
3032
+ output.enqueue(message);
3033
+ }
3034
+ } else {
3035
+ for (const event of drainSdkEvents()) {
3036
+ output.enqueue(event);
3037
+ }
3038
+ output.enqueue(message);
3039
+ }
3040
+ }
3041
+ });
3042
+ for (const uuid of batchUuids) {
3043
+ notifyCommandLifecycle(uuid, "completed");
3044
+ }
3045
+ forwardMessagesToBridge();
3046
+ bridgeHandle?.sendResult();
3047
+ if (false) {}
3048
+ if (options.promptSuggestions && !isEnvDefinedFalsy(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)) {
3049
+ const state = suggestionState;
3050
+ state.abortController?.abort();
3051
+ const localAbort = new AbortController;
3052
+ suggestionState.abortController = localAbort;
3053
+ const cacheSafeParams = getLastCacheSafeParams();
3054
+ if (!cacheSafeParams) {
3055
+ logSuggestionSuppressed("sdk_no_params", undefined, undefined, "sdk");
3056
+ } else {
3057
+ const ref = { promise: null };
3058
+ ref.promise = (async () => {
3059
+ try {
3060
+ const result = await tryGenerateSuggestion(localAbort, mutableMessages, getAppState, cacheSafeParams, "sdk");
3061
+ if (!result || localAbort.signal.aborted)
3062
+ return;
3063
+ const suggestionMsg = {
3064
+ type: "prompt_suggestion",
3065
+ suggestion: result.suggestion,
3066
+ uuid: randomUUID3(),
3067
+ session_id: getSessionId()
3068
+ };
3069
+ const lastEmittedEntry = {
3070
+ text: result.suggestion,
3071
+ emittedAt: Date.now(),
3072
+ promptId: result.promptId,
3073
+ generationRequestId: result.generationRequestId
3074
+ };
3075
+ if (heldBackResult) {
3076
+ suggestionState.pendingSuggestion = suggestionMsg;
3077
+ suggestionState.pendingLastEmittedEntry = {
3078
+ text: lastEmittedEntry.text,
3079
+ promptId: lastEmittedEntry.promptId,
3080
+ generationRequestId: lastEmittedEntry.generationRequestId
3081
+ };
3082
+ } else {
3083
+ suggestionState.lastEmitted = lastEmittedEntry;
3084
+ output.enqueue(suggestionMsg);
3085
+ }
3086
+ } catch (error) {
3087
+ if (error instanceof Error && (error.name === "AbortError" || error.name === "APIUserAbortError")) {
3088
+ logSuggestionSuppressed("aborted", undefined, undefined, "sdk");
3089
+ return;
3090
+ }
3091
+ logError(toError(error));
3092
+ } finally {
3093
+ if (suggestionState.inflightPromise === ref.promise) {
3094
+ suggestionState.inflightPromise = null;
3095
+ }
3096
+ }
3097
+ })();
3098
+ suggestionState.inflightPromise = ref.promise;
3099
+ }
3100
+ }
3101
+ logHeadlessProfilerTurn();
3102
+ logQueryProfileReport();
3103
+ headlessProfilerStartTurn();
3104
+ }
3105
+ };
3106
+ do {
3107
+ for (const event of drainSdkEvents()) {
3108
+ output.enqueue(event);
3109
+ }
3110
+ runPhase = "draining_commands";
3111
+ await drainCommandQueue();
3112
+ waitingForAgents = false;
3113
+ {
3114
+ const state = getAppState();
3115
+ const hasRunningBg = getRunningTasks(state).some((t) => isBackgroundTask(t) && t.type !== "in_process_teammate");
3116
+ const hasMainThreadQueued = peek(isMainThread) !== undefined;
3117
+ if (hasRunningBg || hasMainThreadQueued) {
3118
+ waitingForAgents = true;
3119
+ if (!hasMainThreadQueued) {
3120
+ runPhase = "waiting_for_agents";
3121
+ await sleep(100);
3122
+ }
3123
+ }
3124
+ }
3125
+ } while (waitingForAgents);
3126
+ if (heldBackResult) {
3127
+ output.enqueue(heldBackResult);
3128
+ heldBackResult = null;
3129
+ if (suggestionState.pendingSuggestion) {
3130
+ output.enqueue(suggestionState.pendingSuggestion);
3131
+ if (suggestionState.pendingLastEmittedEntry) {
3132
+ suggestionState.lastEmitted = {
3133
+ ...suggestionState.pendingLastEmittedEntry,
3134
+ emittedAt: Date.now()
3135
+ };
3136
+ suggestionState.pendingLastEmittedEntry = null;
3137
+ }
3138
+ suggestionState.pendingSuggestion = null;
3139
+ }
3140
+ }
3141
+ } catch (error) {
3142
+ try {
3143
+ await structuredIO.write({
3144
+ type: "result",
3145
+ subtype: "error_during_execution",
3146
+ duration_ms: 0,
3147
+ duration_api_ms: 0,
3148
+ is_error: true,
3149
+ num_turns: 0,
3150
+ stop_reason: null,
3151
+ session_id: getSessionId(),
3152
+ total_cost_usd: 0,
3153
+ usage: EMPTY_USAGE,
3154
+ modelUsage: {},
3155
+ permission_denials: [],
3156
+ uuid: randomUUID3(),
3157
+ errors: [
3158
+ errorMessage(error),
3159
+ ...getInMemoryErrors().map((_) => _.error)
3160
+ ]
3161
+ });
3162
+ } catch {}
3163
+ suggestionState.abortController?.abort();
3164
+ gracefulShutdownSync(1);
3165
+ return;
3166
+ } finally {
3167
+ runPhase = "finally_flush";
3168
+ await structuredIO.flushInternalEvents();
3169
+ runPhase = "finally_post_flush";
3170
+ if (!isShuttingDown()) {
3171
+ notifySessionStateChanged("idle");
3172
+ for (const event of drainSdkEvents()) {
3173
+ output.enqueue(event);
3174
+ }
3175
+ }
3176
+ running = false;
3177
+ idleTimeout.start();
3178
+ }
3179
+ if (false) {}
3180
+ if (peek(isMainThread) !== undefined) {
3181
+ run();
3182
+ return;
3183
+ }
3184
+ {
3185
+ const currentAppState = getAppState();
3186
+ const teamContext = currentAppState.teamContext;
3187
+ if (teamContext && isTeamLead(teamContext)) {
3188
+ const agentName = "team-lead";
3189
+ const POLL_INTERVAL_MS = 500;
3190
+ while (true) {
3191
+ const refreshedState = getAppState();
3192
+ const hasActiveTeammates = hasActiveInProcessTeammates(refreshedState) || refreshedState.teamContext && Object.keys(refreshedState.teamContext.teammates).length > 0;
3193
+ if (!hasActiveTeammates) {
3194
+ logForDebugging("[print.ts] No more active teammates, stopping poll");
3195
+ break;
3196
+ }
3197
+ const unread = await readUnreadMessages(agentName, refreshedState.teamContext?.teamName);
3198
+ if (unread.length > 0) {
3199
+ logForDebugging(`[print.ts] Team-lead found ${unread.length} unread messages`);
3200
+ await markMessagesAsRead(agentName, refreshedState.teamContext?.teamName);
3201
+ const teamName = refreshedState.teamContext?.teamName;
3202
+ for (const m of unread) {
3203
+ const shutdownApproval = isShutdownApproved(m.text);
3204
+ if (shutdownApproval && teamName) {
3205
+ const teammateToRemove = shutdownApproval.from;
3206
+ logForDebugging(`[print.ts] Processing shutdown_approved from ${teammateToRemove}`);
3207
+ const teammateId = refreshedState.teamContext?.teammates ? Object.entries(refreshedState.teamContext.teammates).find(([, t]) => t.name === teammateToRemove)?.[0] : undefined;
3208
+ if (teammateId) {
3209
+ removeTeammateFromTeamFile(teamName, {
3210
+ agentId: teammateId,
3211
+ name: teammateToRemove
3212
+ });
3213
+ logForDebugging(`[print.ts] Removed ${teammateToRemove} from team file`);
3214
+ await unassignTeammateTasks(teamName, teammateId, teammateToRemove, "shutdown");
3215
+ setAppState((prev) => {
3216
+ if (!prev.teamContext?.teammates)
3217
+ return prev;
3218
+ if (!(teammateId in prev.teamContext.teammates))
3219
+ return prev;
3220
+ const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates;
3221
+ return {
3222
+ ...prev,
3223
+ teamContext: {
3224
+ ...prev.teamContext,
3225
+ teammates: remainingTeammates
3226
+ }
3227
+ };
3228
+ });
3229
+ }
3230
+ }
3231
+ }
3232
+ const formatted = unread.map((m) => `<${TEAMMATE_MESSAGE_TAG} teammate_id="${m.from}"${m.color ? ` color="${m.color}"` : ""}>
3233
+ ${m.text}
3234
+ </${TEAMMATE_MESSAGE_TAG}>`).join(`
3235
+
3236
+ `);
3237
+ enqueue({
3238
+ mode: "prompt",
3239
+ value: formatted,
3240
+ uuid: randomUUID3()
3241
+ });
3242
+ run();
3243
+ return;
3244
+ }
3245
+ if (inputClosed && !shutdownPromptInjected) {
3246
+ shutdownPromptInjected = true;
3247
+ logForDebugging("[print.ts] Input closed with active teammates, injecting shutdown prompt");
3248
+ enqueue({
3249
+ mode: "prompt",
3250
+ value: SHUTDOWN_TEAM_PROMPT,
3251
+ uuid: randomUUID3()
3252
+ });
3253
+ run();
3254
+ return;
3255
+ }
3256
+ await sleep(POLL_INTERVAL_MS);
3257
+ }
3258
+ }
3259
+ }
3260
+ if (inputClosed) {
3261
+ const hasActiveSwarm = await (async () => {
3262
+ const currentAppState = getAppState();
3263
+ if (hasWorkingInProcessTeammates(currentAppState)) {
3264
+ await waitForTeammatesToBecomeIdle(setAppState, currentAppState);
3265
+ }
3266
+ const refreshedAppState = getAppState();
3267
+ const refreshedTeamContext = refreshedAppState.teamContext;
3268
+ const hasTeamMembersNotCleanedUp = refreshedTeamContext && Object.keys(refreshedTeamContext.teammates).length > 0;
3269
+ return hasTeamMembersNotCleanedUp || hasActiveInProcessTeammates(refreshedAppState);
3270
+ })();
3271
+ if (hasActiveSwarm) {
3272
+ enqueue({
3273
+ mode: "prompt",
3274
+ value: SHUTDOWN_TEAM_PROMPT,
3275
+ uuid: randomUUID3()
3276
+ });
3277
+ run();
3278
+ } else {
3279
+ if (suggestionState.inflightPromise) {
3280
+ await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
3281
+ }
3282
+ suggestionState.abortController?.abort();
3283
+ suggestionState.abortController = null;
3284
+ await finalizePendingAsyncHooks();
3285
+ unsubscribeSkillChanges();
3286
+ unsubscribeAuthStatus?.();
3287
+ statusListeners.delete(rateLimitListener);
3288
+ output.done();
3289
+ }
3290
+ }
3291
+ };
3292
+ if (false) {}
3293
+ let cronScheduler = null;
3294
+ if (cronGate.isKairosCronEnabled()) {
3295
+ cronScheduler = cronSchedulerModule.createCronScheduler({
3296
+ onFire: (prompt) => {
3297
+ if (inputClosed)
3298
+ return;
3299
+ enqueue({
3300
+ mode: "prompt",
3301
+ value: prompt,
3302
+ uuid: randomUUID3(),
3303
+ priority: "later",
3304
+ isMeta: true,
3305
+ workload: WORKLOAD_CRON
3306
+ });
3307
+ run();
3308
+ },
3309
+ isLoading: () => running || inputClosed,
3310
+ getJitterConfig: cronJitterConfigModule?.getCronJitterConfig,
3311
+ isKilled: () => !cronGate?.isKairosCronEnabled()
3312
+ });
3313
+ cronScheduler.start();
3314
+ }
3315
+ const sendControlResponseSuccess = function(message, response) {
3316
+ output.enqueue({
3317
+ type: "control_response",
3318
+ response: {
3319
+ subtype: "success",
3320
+ request_id: message.request_id,
3321
+ response
3322
+ }
3323
+ });
3324
+ };
3325
+ const sendControlResponseError = function(message, errorMessage2) {
3326
+ output.enqueue({
3327
+ type: "control_response",
3328
+ response: {
3329
+ subtype: "error",
3330
+ request_id: message.request_id,
3331
+ error: errorMessage2
3332
+ }
3333
+ });
3334
+ };
3335
+ const handledOrphanedToolUseIds = new Set;
3336
+ structuredIO.setUnexpectedResponseCallback(async (message) => {
3337
+ await handleOrphanedPermissionResponse({
3338
+ message,
3339
+ setAppState,
3340
+ handledToolUseIds: handledOrphanedToolUseIds,
3341
+ onEnqueued: () => {
3342
+ run();
3343
+ }
3344
+ });
3345
+ });
3346
+ const activeOAuthFlows = new Map;
3347
+ const oauthCallbackSubmitters = new Map;
3348
+ const oauthManualCallbackUsed = new Set;
3349
+ const oauthAuthPromises = new Map;
3350
+ let claudeOAuth = null;
3351
+ (async () => {
3352
+ let initialized = false;
3353
+ logForDiagnosticsNoPII("info", "cli_message_loop_started");
3354
+ for await (const message of structuredIO.structuredInput) {
3355
+ const eventId = "uuid" in message ? message.uuid : undefined;
3356
+ if (eventId && message.type !== "user" && message.type !== "control_response") {
3357
+ notifyCommandLifecycle(eventId, "completed");
3358
+ }
3359
+ if (message.type === "control_request") {
3360
+ const msg = message;
3361
+ const req = msg.request;
3362
+ if (msg.request.subtype === "interrupt") {
3363
+ if (false) {}
3364
+ if (abortController) {
3365
+ abortController.abort();
3366
+ }
3367
+ suggestionState.abortController?.abort();
3368
+ suggestionState.abortController = null;
3369
+ suggestionState.lastEmitted = null;
3370
+ suggestionState.pendingSuggestion = null;
3371
+ sendControlResponseSuccess(msg);
3372
+ } else if (req.subtype === "end_session") {
3373
+ logForDebugging(`[print.ts] end_session received, reason=${req.reason ?? "unspecified"}`);
3374
+ if (abortController) {
3375
+ abortController.abort();
3376
+ }
3377
+ suggestionState.abortController?.abort();
3378
+ suggestionState.abortController = null;
3379
+ suggestionState.lastEmitted = null;
3380
+ suggestionState.pendingSuggestion = null;
3381
+ sendControlResponseSuccess(msg);
3382
+ break;
3383
+ } else if (msg.request.subtype === "initialize") {
3384
+ if (msg.request.sdkMcpServers && msg.request.sdkMcpServers.length > 0) {
3385
+ for (const serverName of msg.request.sdkMcpServers) {
3386
+ sdkMcpConfigs[serverName] = {
3387
+ type: "sdk",
3388
+ name: serverName
3389
+ };
3390
+ }
3391
+ }
3392
+ await handleInitializeRequest(msg.request, msg.request_id, initialized, output, commands, modelInfos, structuredIO, !!options.enableAuthStatus, options, agents, getAppState);
3393
+ if (msg.request.promptSuggestions) {
3394
+ setAppState((prev) => {
3395
+ if (prev.promptSuggestionEnabled)
3396
+ return prev;
3397
+ return { ...prev, promptSuggestionEnabled: true };
3398
+ });
3399
+ }
3400
+ if (msg.request.agentProgressSummaries && getFeatureValue_CACHED_MAY_BE_STALE("tengu_slate_prism", true)) {
3401
+ setSdkAgentProgressSummariesEnabled(true);
3402
+ }
3403
+ initialized = true;
3404
+ if (hasCommandsInQueue()) {
3405
+ run();
3406
+ }
3407
+ } else if (msg.request.subtype === "set_permission_mode") {
3408
+ const m = msg.request;
3409
+ setAppState((prev) => ({
3410
+ ...prev,
3411
+ toolPermissionContext: handleSetPermissionMode(m, msg.request_id, prev.toolPermissionContext, output),
3412
+ isUltraplanMode: m.ultraplan ?? prev.isUltraplanMode
3413
+ }));
3414
+ } else if (msg.request.subtype === "set_model") {
3415
+ const requestedModel = msg.request.model ?? "default";
3416
+ const model = requestedModel === "default" ? getDefaultMainLoopModel() : requestedModel;
3417
+ activeUserSpecifiedModel = model;
3418
+ setMainLoopModelOverride(model);
3419
+ notifySessionMetadataChanged({ model });
3420
+ injectModelSwitchBreadcrumbs(requestedModel, model);
3421
+ sendControlResponseSuccess(msg);
3422
+ } else if (msg.request.subtype === "set_max_thinking_tokens") {
3423
+ if (msg.request.max_thinking_tokens === null) {
3424
+ options.thinkingConfig = undefined;
3425
+ } else if (msg.request.max_thinking_tokens === 0) {
3426
+ options.thinkingConfig = { type: "disabled" };
3427
+ } else {
3428
+ options.thinkingConfig = {
3429
+ type: "enabled",
3430
+ budgetTokens: msg.request.max_thinking_tokens
3431
+ };
3432
+ }
3433
+ sendControlResponseSuccess(msg);
3434
+ } else if (msg.request.subtype === "mcp_status") {
3435
+ sendControlResponseSuccess(msg, {
3436
+ mcpServers: buildMcpServerStatuses()
3437
+ });
3438
+ } else if (msg.request.subtype === "get_context_usage") {
3439
+ try {
3440
+ const appState = getAppState();
3441
+ const data = await collectContextData({
3442
+ messages: mutableMessages,
3443
+ getAppState,
3444
+ options: {
3445
+ mainLoopModel: getMainLoopModel(),
3446
+ tools: buildAllTools(appState),
3447
+ agentDefinitions: appState.agentDefinitions,
3448
+ customSystemPrompt: options.systemPrompt,
3449
+ appendSystemPrompt: options.appendSystemPrompt
3450
+ }
3451
+ });
3452
+ sendControlResponseSuccess(msg, { ...data });
3453
+ } catch (error) {
3454
+ sendControlResponseError(msg, errorMessage(error));
3455
+ }
3456
+ } else if (msg.request.subtype === "mcp_message") {
3457
+ const mcpRequest = msg.request;
3458
+ const sdkClient = sdkClients.find((client) => client.name === mcpRequest.server_name);
3459
+ if (sdkClient && sdkClient.type === "connected" && sdkClient.client?.transport?.onmessage) {
3460
+ sdkClient.client.transport.onmessage(mcpRequest.message);
3461
+ }
3462
+ sendControlResponseSuccess(msg);
3463
+ } else if (msg.request.subtype === "rewind_files") {
3464
+ const appState = getAppState();
3465
+ const result = await handleRewindFiles(msg.request.user_message_id, appState, setAppState, msg.request.dry_run ?? false);
3466
+ if (result.canRewind || msg.request.dry_run) {
3467
+ sendControlResponseSuccess(msg, result);
3468
+ } else {
3469
+ sendControlResponseError(msg, result.error ?? "Unexpected error");
3470
+ }
3471
+ } else if (msg.request.subtype === "cancel_async_message") {
3472
+ const targetUuid = msg.request.message_uuid;
3473
+ const removed = dequeueAllMatching((cmd) => cmd.uuid === targetUuid);
3474
+ sendControlResponseSuccess(msg, {
3475
+ cancelled: removed.length > 0
3476
+ });
3477
+ } else if (msg.request.subtype === "seed_read_state") {
3478
+ try {
3479
+ const normalizedPath = expandPath(msg.request.path);
3480
+ const diskMtime = Math.floor((await stat(normalizedPath)).mtimeMs);
3481
+ if (diskMtime <= msg.request.mtime) {
3482
+ const raw = await readFile2(normalizedPath, "utf-8");
3483
+ const content = (raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw).replaceAll(`\r
3484
+ `, `
3485
+ `);
3486
+ pendingSeeds.set(normalizedPath, {
3487
+ content,
3488
+ timestamp: diskMtime,
3489
+ offset: undefined,
3490
+ limit: undefined
3491
+ });
3492
+ }
3493
+ } catch {}
3494
+ sendControlResponseSuccess(msg);
3495
+ } else if (msg.request.subtype === "mcp_set_servers") {
3496
+ const { response, sdkServersChanged } = await applyMcpServerChanges(msg.request.servers);
3497
+ sendControlResponseSuccess(msg, response);
3498
+ if (sdkServersChanged) {
3499
+ updateSdkMcp();
3500
+ }
3501
+ } else if (msg.request.subtype === "reload_plugins") {
3502
+ try {
3503
+ if (false) {}
3504
+ const r = await refreshActivePlugins(setAppState);
3505
+ const sdkAgents = currentAgents.filter((a) => a.source === "flagSettings");
3506
+ currentAgents = [...r.agentDefinitions.allAgents, ...sdkAgents];
3507
+ let plugins = [];
3508
+ const [cmdsR, mcpR, pluginsR] = await Promise.allSettled([
3509
+ getCommands(cwd()),
3510
+ applyPluginMcpDiff(),
3511
+ loadAllPluginsCacheOnly()
3512
+ ]);
3513
+ if (cmdsR.status === "fulfilled") {
3514
+ currentCommands = cmdsR.value;
3515
+ } else {
3516
+ logError(cmdsR.reason);
3517
+ }
3518
+ if (mcpR.status === "rejected") {
3519
+ logError(mcpR.reason);
3520
+ }
3521
+ if (pluginsR.status === "fulfilled") {
3522
+ plugins = pluginsR.value.enabled.map((p) => ({
3523
+ name: p.name,
3524
+ path: p.path,
3525
+ source: p.source
3526
+ }));
3527
+ } else {
3528
+ logError(pluginsR.reason);
3529
+ }
3530
+ sendControlResponseSuccess(msg, {
3531
+ commands: currentCommands.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({
3532
+ name: getCommandName(cmd),
3533
+ description: formatDescriptionWithSource(cmd),
3534
+ argumentHint: cmd.argumentHint || ""
3535
+ })),
3536
+ agents: currentAgents.map((a) => ({
3537
+ name: a.agentType,
3538
+ description: a.whenToUse,
3539
+ model: a.model === "inherit" ? undefined : a.model
3540
+ })),
3541
+ plugins,
3542
+ mcpServers: buildMcpServerStatuses(),
3543
+ error_count: r.error_count
3544
+ });
3545
+ } catch (error) {
3546
+ sendControlResponseError(msg, errorMessage(error));
3547
+ }
3548
+ } else if (msg.request.subtype === "mcp_reconnect") {
3549
+ const currentAppState = getAppState();
3550
+ const { serverName } = msg.request;
3551
+ elicitationRegistered.delete(serverName);
3552
+ const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? sdkClients.find((c) => c.name === serverName)?.config ?? dynamicMcpState.clients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
3553
+ if (!config) {
3554
+ sendControlResponseError(msg, `Server not found: ${serverName}`);
3555
+ } else {
3556
+ const result = await reconnectMcpServerImpl(serverName, config);
3557
+ const prefix = getMcpPrefix(serverName);
3558
+ setAppState((prev) => ({
3559
+ ...prev,
3560
+ mcp: {
3561
+ ...prev.mcp,
3562
+ clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
3563
+ tools: [
3564
+ ...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
3565
+ ...result.tools
3566
+ ],
3567
+ commands: [
3568
+ ...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
3569
+ ...result.commands
3570
+ ],
3571
+ resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName)
3572
+ }
3573
+ }));
3574
+ dynamicMcpState = {
3575
+ ...dynamicMcpState,
3576
+ clients: [
3577
+ ...dynamicMcpState.clients.filter((c) => c.name !== serverName),
3578
+ result.client
3579
+ ],
3580
+ tools: [
3581
+ ...dynamicMcpState.tools.filter((t) => !t.name?.startsWith(prefix)),
3582
+ ...result.tools
3583
+ ]
3584
+ };
3585
+ if (result.client.type === "connected") {
3586
+ registerElicitationHandlers([result.client]);
3587
+ reregisterChannelHandlerAfterReconnect(result.client);
3588
+ sendControlResponseSuccess(msg);
3589
+ } else {
3590
+ const errorMessage2 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`;
3591
+ sendControlResponseError(msg, errorMessage2);
3592
+ }
3593
+ }
3594
+ } else if (msg.request.subtype === "mcp_toggle") {
3595
+ const currentAppState = getAppState();
3596
+ const { serverName, enabled } = msg.request;
3597
+ elicitationRegistered.delete(serverName);
3598
+ const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? sdkClients.find((c) => c.name === serverName)?.config ?? dynamicMcpState.clients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
3599
+ if (!config) {
3600
+ sendControlResponseError(msg, `Server not found: ${serverName}`);
3601
+ } else if (!enabled) {
3602
+ setMcpServerEnabled(serverName, false);
3603
+ const client = [
3604
+ ...mcpClients,
3605
+ ...sdkClients,
3606
+ ...dynamicMcpState.clients,
3607
+ ...currentAppState.mcp.clients
3608
+ ].find((c) => c.name === serverName);
3609
+ if (client && client.type === "connected") {
3610
+ await clearServerCache(serverName, config);
3611
+ }
3612
+ const prefix = getMcpPrefix(serverName);
3613
+ setAppState((prev) => ({
3614
+ ...prev,
3615
+ mcp: {
3616
+ ...prev.mcp,
3617
+ clients: prev.mcp.clients.map((c) => c.name === serverName ? { name: serverName, type: "disabled", config } : c),
3618
+ tools: reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
3619
+ commands: reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
3620
+ resources: omit_default(prev.mcp.resources, serverName)
3621
+ }
3622
+ }));
3623
+ sendControlResponseSuccess(msg);
3624
+ } else {
3625
+ setMcpServerEnabled(serverName, true);
3626
+ const result = await reconnectMcpServerImpl(serverName, config);
3627
+ const prefix = getMcpPrefix(serverName);
3628
+ setAppState((prev) => ({
3629
+ ...prev,
3630
+ mcp: {
3631
+ ...prev.mcp,
3632
+ clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
3633
+ tools: [
3634
+ ...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
3635
+ ...result.tools
3636
+ ],
3637
+ commands: [
3638
+ ...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
3639
+ ...result.commands
3640
+ ],
3641
+ resources: result.resources && result.resources.length > 0 ? { ...prev.mcp.resources, [serverName]: result.resources } : omit_default(prev.mcp.resources, serverName)
3642
+ }
3643
+ }));
3644
+ if (result.client.type === "connected") {
3645
+ registerElicitationHandlers([result.client]);
3646
+ reregisterChannelHandlerAfterReconnect(result.client);
3647
+ sendControlResponseSuccess(msg);
3648
+ } else {
3649
+ const errorMessage2 = result.client.type === "failed" ? result.client.error ?? "Connection failed" : `Server status: ${result.client.type}`;
3650
+ sendControlResponseError(msg, errorMessage2);
3651
+ }
3652
+ }
3653
+ } else if (req.subtype === "channel_enable") {
3654
+ const currentAppState = getAppState();
3655
+ handleChannelEnable(msg.request_id, req.serverName, [
3656
+ ...currentAppState.mcp.clients,
3657
+ ...sdkClients,
3658
+ ...dynamicMcpState.clients
3659
+ ], output);
3660
+ } else if (req.subtype === "mcp_authenticate") {
3661
+ const { serverName } = req;
3662
+ const currentAppState = getAppState();
3663
+ const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
3664
+ if (!config) {
3665
+ sendControlResponseError(msg, `Server not found: ${serverName}`);
3666
+ } else if (config.type !== "sse" && config.type !== "http") {
3667
+ sendControlResponseError(msg, `Server type "${config.type}" does not support OAuth authentication`);
3668
+ } else {
3669
+ try {
3670
+ activeOAuthFlows.get(serverName)?.abort();
3671
+ const controller = new AbortController;
3672
+ activeOAuthFlows.set(serverName, controller);
3673
+ let resolveAuthUrl;
3674
+ const authUrlPromise = new Promise((resolve) => {
3675
+ resolveAuthUrl = resolve;
3676
+ });
3677
+ const oauthPromise = performMCPOAuthFlow(serverName, config, (url) => resolveAuthUrl(url), controller.signal, {
3678
+ skipBrowserOpen: true,
3679
+ onWaitingForCallback: (submit) => {
3680
+ oauthCallbackSubmitters.set(serverName, submit);
3681
+ }
3682
+ });
3683
+ const authUrl = await Promise.race([
3684
+ authUrlPromise,
3685
+ oauthPromise.then(() => null)
3686
+ ]);
3687
+ if (authUrl) {
3688
+ sendControlResponseSuccess(msg, {
3689
+ authUrl,
3690
+ requiresUserAction: true
3691
+ });
3692
+ } else {
3693
+ sendControlResponseSuccess(msg, {
3694
+ requiresUserAction: false
3695
+ });
3696
+ }
3697
+ oauthAuthPromises.set(serverName, oauthPromise);
3698
+ const fullFlowPromise = oauthPromise.then(async () => {
3699
+ if (isMcpServerDisabled(serverName)) {
3700
+ return;
3701
+ }
3702
+ if (oauthManualCallbackUsed.has(serverName)) {
3703
+ return;
3704
+ }
3705
+ const result = await reconnectMcpServerImpl(serverName, config);
3706
+ const prefix = getMcpPrefix(serverName);
3707
+ setAppState((prev) => ({
3708
+ ...prev,
3709
+ mcp: {
3710
+ ...prev.mcp,
3711
+ clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
3712
+ tools: [
3713
+ ...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
3714
+ ...result.tools
3715
+ ],
3716
+ commands: [
3717
+ ...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
3718
+ ...result.commands
3719
+ ],
3720
+ resources: result.resources && result.resources.length > 0 ? {
3721
+ ...prev.mcp.resources,
3722
+ [serverName]: result.resources
3723
+ } : omit_default(prev.mcp.resources, serverName)
3724
+ }
3725
+ }));
3726
+ dynamicMcpState = {
3727
+ ...dynamicMcpState,
3728
+ clients: [
3729
+ ...dynamicMcpState.clients.filter((c) => c.name !== serverName),
3730
+ result.client
3731
+ ],
3732
+ tools: [
3733
+ ...dynamicMcpState.tools.filter((t) => !t.name?.startsWith(prefix)),
3734
+ ...result.tools
3735
+ ]
3736
+ };
3737
+ }).catch((error) => {
3738
+ logForDebugging(`MCP OAuth failed for ${serverName}: ${error}`, { level: "error" });
3739
+ }).finally(() => {
3740
+ if (activeOAuthFlows.get(serverName) === controller) {
3741
+ activeOAuthFlows.delete(serverName);
3742
+ oauthCallbackSubmitters.delete(serverName);
3743
+ oauthManualCallbackUsed.delete(serverName);
3744
+ oauthAuthPromises.delete(serverName);
3745
+ }
3746
+ });
3747
+ } catch (error) {
3748
+ sendControlResponseError(msg, errorMessage(error));
3749
+ }
3750
+ }
3751
+ } else if (req.subtype === "mcp_oauth_callback_url") {
3752
+ const { serverName, callbackUrl } = req;
3753
+ const submit = oauthCallbackSubmitters.get(serverName);
3754
+ if (submit) {
3755
+ let hasCodeOrError = false;
3756
+ try {
3757
+ const parsed = new URL(callbackUrl);
3758
+ hasCodeOrError = parsed.searchParams.has("code") || parsed.searchParams.has("error");
3759
+ } catch {}
3760
+ if (!hasCodeOrError) {
3761
+ sendControlResponseError(msg, "Invalid callback URL: missing authorization code. Please paste the full redirect URL including the code parameter.");
3762
+ } else {
3763
+ oauthManualCallbackUsed.add(serverName);
3764
+ submit(callbackUrl);
3765
+ const authPromise = oauthAuthPromises.get(serverName);
3766
+ if (authPromise) {
3767
+ try {
3768
+ await authPromise;
3769
+ sendControlResponseSuccess(msg);
3770
+ } catch (error) {
3771
+ sendControlResponseError(msg, error instanceof Error ? error.message : "OAuth authentication failed");
3772
+ }
3773
+ } else {
3774
+ sendControlResponseSuccess(msg);
3775
+ }
3776
+ }
3777
+ } else {
3778
+ sendControlResponseError(msg, `No active OAuth flow for server: ${serverName}`);
3779
+ }
3780
+ } else if (req.subtype === "claude_authenticate") {
3781
+ const { loginWithClaudeAi } = req;
3782
+ claudeOAuth?.service.cleanup();
3783
+ logEvent("tengu_oauth_flow_start", {
3784
+ loginWithClaudeAi: loginWithClaudeAi ?? true
3785
+ });
3786
+ const service = new OAuthService;
3787
+ let urlResolver;
3788
+ const urlPromise = new Promise((resolve) => {
3789
+ urlResolver = resolve;
3790
+ });
3791
+ const flow = service.startOAuthFlow(async (manualUrl, automaticUrl) => {
3792
+ urlResolver({ manualUrl, automaticUrl });
3793
+ }, {
3794
+ loginWithClaudeAi: loginWithClaudeAi ?? true,
3795
+ skipBrowserOpen: true
3796
+ }).then(async (tokens) => {
3797
+ await installOAuthTokens(tokens);
3798
+ logEvent("tengu_oauth_success", {
3799
+ loginWithClaudeAi: loginWithClaudeAi ?? true
3800
+ });
3801
+ }).finally(() => {
3802
+ service.cleanup();
3803
+ if (claudeOAuth?.service === service) {
3804
+ claudeOAuth = null;
3805
+ }
3806
+ });
3807
+ claudeOAuth = { service, flow };
3808
+ flow.catch((err) => logForDebugging(`claude_authenticate flow ended: ${err}`, {
3809
+ level: "info"
3810
+ }));
3811
+ try {
3812
+ const { manualUrl, automaticUrl } = await Promise.race([
3813
+ urlPromise,
3814
+ flow.then(() => {
3815
+ throw new Error("OAuth flow completed without producing auth URLs");
3816
+ })
3817
+ ]);
3818
+ sendControlResponseSuccess(msg, {
3819
+ manualUrl,
3820
+ automaticUrl
3821
+ });
3822
+ } catch (error) {
3823
+ sendControlResponseError(msg, errorMessage(error));
3824
+ }
3825
+ } else if (req.subtype === "claude_oauth_callback" || req.subtype === "claude_oauth_wait_for_completion") {
3826
+ if (!claudeOAuth) {
3827
+ sendControlResponseError(msg, "No active claude_authenticate flow");
3828
+ } else {
3829
+ if (req.subtype === "claude_oauth_callback") {
3830
+ claudeOAuth.service.handleManualAuthCodeInput({
3831
+ authorizationCode: req.authorizationCode,
3832
+ state: req.state
3833
+ });
3834
+ }
3835
+ const { flow } = claudeOAuth;
3836
+ flow.then(() => {
3837
+ const accountInfo = getAccountInformation();
3838
+ sendControlResponseSuccess(msg, {
3839
+ account: {
3840
+ email: accountInfo?.email,
3841
+ organization: accountInfo?.organization,
3842
+ subscriptionType: accountInfo?.subscription,
3843
+ tokenSource: accountInfo?.tokenSource,
3844
+ apiKeySource: accountInfo?.apiKeySource,
3845
+ apiProvider: getAPIProvider()
3846
+ }
3847
+ });
3848
+ }, (error) => sendControlResponseError(msg, errorMessage(error)));
3849
+ }
3850
+ } else if (req.subtype === "mcp_clear_auth") {
3851
+ const { serverName } = req;
3852
+ const currentAppState = getAppState();
3853
+ const config = getMcpConfigByName(serverName) ?? mcpClients.find((c) => c.name === serverName)?.config ?? currentAppState.mcp.clients.find((c) => c.name === serverName)?.config ?? null;
3854
+ if (!config) {
3855
+ sendControlResponseError(msg, `Server not found: ${serverName}`);
3856
+ } else if (config.type !== "sse" && config.type !== "http") {
3857
+ sendControlResponseError(msg, `Cannot clear auth for server type "${config.type}"`);
3858
+ } else {
3859
+ await revokeServerTokens(serverName, config);
3860
+ const result = await reconnectMcpServerImpl(serverName, config);
3861
+ const prefix = getMcpPrefix(serverName);
3862
+ setAppState((prev) => ({
3863
+ ...prev,
3864
+ mcp: {
3865
+ ...prev.mcp,
3866
+ clients: prev.mcp.clients.map((c) => c.name === serverName ? result.client : c),
3867
+ tools: [
3868
+ ...reject_default(prev.mcp.tools, (t) => t.name?.startsWith(prefix)),
3869
+ ...result.tools
3870
+ ],
3871
+ commands: [
3872
+ ...reject_default(prev.mcp.commands, (c) => commandBelongsToServer(c, serverName)),
3873
+ ...result.commands
3874
+ ],
3875
+ resources: result.resources && result.resources.length > 0 ? {
3876
+ ...prev.mcp.resources,
3877
+ [serverName]: result.resources
3878
+ } : omit_default(prev.mcp.resources, serverName)
3879
+ }
3880
+ }));
3881
+ sendControlResponseSuccess(msg, {});
3882
+ }
3883
+ } else if (msg.request.subtype === "apply_flag_settings") {
3884
+ const prevModel = getMainLoopModel();
3885
+ const existing = getFlagSettingsInline() ?? {};
3886
+ const incoming = msg.request.settings;
3887
+ const merged = { ...existing, ...incoming };
3888
+ for (const key of Object.keys(merged)) {
3889
+ if (merged[key] === null) {
3890
+ delete merged[key];
3891
+ }
3892
+ }
3893
+ setFlagSettingsInline(merged);
3894
+ settingsChangeDetector.notifyChange("flagSettings");
3895
+ if ("model" in incoming) {
3896
+ if (incoming.model != null) {
3897
+ setMainLoopModelOverride(String(incoming.model));
3898
+ } else {
3899
+ setMainLoopModelOverride(undefined);
3900
+ }
3901
+ }
3902
+ const newModel = getMainLoopModel();
3903
+ if (newModel !== prevModel) {
3904
+ activeUserSpecifiedModel = newModel;
3905
+ const modelArg = incoming.model ? String(incoming.model) : "default";
3906
+ notifySessionMetadataChanged({ model: newModel });
3907
+ injectModelSwitchBreadcrumbs(modelArg, newModel);
3908
+ }
3909
+ sendControlResponseSuccess(msg);
3910
+ } else if (msg.request.subtype === "get_settings") {
3911
+ const currentAppState = getAppState();
3912
+ const model = getMainLoopModel();
3913
+ const effort = modelSupportsEffort(model) ? resolveAppliedEffort(model, currentAppState.effortValue) : undefined;
3914
+ sendControlResponseSuccess(msg, {
3915
+ ...getSettingsWithSources(),
3916
+ applied: {
3917
+ model,
3918
+ effort: typeof effort === "string" ? effort : null
3919
+ }
3920
+ });
3921
+ } else if (msg.request.subtype === "stop_task") {
3922
+ const { task_id: taskId } = msg.request;
3923
+ try {
3924
+ await stopTask(taskId, {
3925
+ getAppState,
3926
+ setAppState
3927
+ });
3928
+ sendControlResponseSuccess(msg, {});
3929
+ } catch (error) {
3930
+ sendControlResponseError(msg, errorMessage(error));
3931
+ }
3932
+ } else if (req.subtype === "generate_session_title") {
3933
+ const { description, persist } = req;
3934
+ const titleSignal = (abortController && !abortController.signal.aborted ? abortController : createAbortController()).signal;
3935
+ (async () => {
3936
+ try {
3937
+ const title = await generateSessionTitle(description, titleSignal);
3938
+ if (title && persist) {
3939
+ try {
3940
+ saveAiGeneratedTitle(getSessionId(), title);
3941
+ } catch (e) {
3942
+ logError(e);
3943
+ }
3944
+ }
3945
+ sendControlResponseSuccess(msg, { title });
3946
+ } catch (e) {
3947
+ sendControlResponseError(msg, errorMessage(e));
3948
+ }
3949
+ })();
3950
+ } else if (req.subtype === "side_question") {
3951
+ const { question } = req;
3952
+ (async () => {
3953
+ try {
3954
+ const saved = getLastCacheSafeParams();
3955
+ const cacheSafeParams = saved ? {
3956
+ ...saved,
3957
+ toolUseContext: {
3958
+ ...saved.toolUseContext,
3959
+ abortController: createAbortController()
3960
+ }
3961
+ } : await buildSideQuestionFallbackParams({
3962
+ tools: buildAllTools(getAppState()),
3963
+ commands: currentCommands,
3964
+ mcpClients: [
3965
+ ...getAppState().mcp.clients,
3966
+ ...sdkClients,
3967
+ ...dynamicMcpState.clients
3968
+ ],
3969
+ messages: mutableMessages,
3970
+ readFileState,
3971
+ getAppState,
3972
+ setAppState,
3973
+ customSystemPrompt: options.systemPrompt,
3974
+ appendSystemPrompt: options.appendSystemPrompt,
3975
+ thinkingConfig: options.thinkingConfig,
3976
+ agents: currentAgents
3977
+ });
3978
+ const result = await runSideQuestion({
3979
+ question,
3980
+ cacheSafeParams
3981
+ });
3982
+ sendControlResponseSuccess(msg, { response: result.response });
3983
+ } catch (e) {
3984
+ sendControlResponseError(msg, errorMessage(e));
3985
+ }
3986
+ })();
3987
+ } else if (false) {} else if (req.subtype === "remote_control") {
3988
+ if (req.enabled) {
3989
+ if (bridgeHandle) {
3990
+ sendControlResponseSuccess(msg, {
3991
+ session_url: getRemoteSessionUrl(bridgeHandle.bridgeSessionId, bridgeHandle.sessionIngressUrl),
3992
+ connect_url: buildBridgeConnectUrl(bridgeHandle.environmentId, bridgeHandle.sessionIngressUrl),
3993
+ environment_id: bridgeHandle.environmentId
3994
+ });
3995
+ } else {
3996
+ let bridgeFailureDetail;
3997
+ try {
3998
+ const { initReplBridge } = await import("./chunk-8jprqan8.js");
3999
+ const handle = await initReplBridge({
4000
+ onInboundMessage(msg2) {
4001
+ const fields = extractInboundMessageFields(msg2);
4002
+ if (!fields)
4003
+ return;
4004
+ const { content, uuid } = fields;
4005
+ enqueue({
4006
+ value: content,
4007
+ mode: "prompt",
4008
+ uuid,
4009
+ skipSlashCommands: true
4010
+ });
4011
+ run();
4012
+ },
4013
+ onPermissionResponse(response) {
4014
+ structuredIO.injectControlResponse(response);
4015
+ },
4016
+ onInterrupt() {
4017
+ abortController?.abort();
4018
+ },
4019
+ onSetModel(model) {
4020
+ const resolved = model === "default" ? getDefaultMainLoopModel() : model;
4021
+ activeUserSpecifiedModel = resolved;
4022
+ setMainLoopModelOverride(resolved);
4023
+ },
4024
+ onSetMaxThinkingTokens(maxTokens) {
4025
+ if (maxTokens === null) {
4026
+ options.thinkingConfig = undefined;
4027
+ } else if (maxTokens === 0) {
4028
+ options.thinkingConfig = { type: "disabled" };
4029
+ } else {
4030
+ options.thinkingConfig = {
4031
+ type: "enabled",
4032
+ budgetTokens: maxTokens
4033
+ };
4034
+ }
4035
+ },
4036
+ onStateChange(state, detail) {
4037
+ if (state === "failed") {
4038
+ bridgeFailureDetail = detail;
4039
+ }
4040
+ logForDebugging(`[bridge:sdk] State change: ${state}${detail ? ` \u2014 ${detail}` : ""}`);
4041
+ output.enqueue({
4042
+ type: "system",
4043
+ subtype: "bridge_state",
4044
+ state,
4045
+ detail,
4046
+ uuid: randomUUID3(),
4047
+ session_id: getSessionId()
4048
+ });
4049
+ },
4050
+ initialMessages: mutableMessages.length > 0 ? mutableMessages : undefined
4051
+ });
4052
+ if (!handle) {
4053
+ sendControlResponseError(msg, bridgeFailureDetail ?? "Remote Control initialization failed");
4054
+ } else {
4055
+ bridgeHandle = handle;
4056
+ bridgeLastForwardedIndex = mutableMessages.length;
4057
+ structuredIO.setOnControlRequestSent((request) => {
4058
+ handle.sendControlRequest(request);
4059
+ });
4060
+ structuredIO.setOnControlRequestResolved((requestId) => {
4061
+ handle.sendControlCancelRequest(requestId);
4062
+ });
4063
+ sendControlResponseSuccess(msg, {
4064
+ session_url: getRemoteSessionUrl(handle.bridgeSessionId, handle.sessionIngressUrl),
4065
+ connect_url: buildBridgeConnectUrl(handle.environmentId, handle.sessionIngressUrl),
4066
+ environment_id: handle.environmentId
4067
+ });
4068
+ }
4069
+ } catch (err) {
4070
+ sendControlResponseError(msg, errorMessage(err));
4071
+ }
4072
+ }
4073
+ } else {
4074
+ if (bridgeHandle) {
4075
+ structuredIO.setOnControlRequestSent(undefined);
4076
+ structuredIO.setOnControlRequestResolved(undefined);
4077
+ await bridgeHandle.teardown();
4078
+ bridgeHandle = null;
4079
+ }
4080
+ sendControlResponseSuccess(msg);
4081
+ }
4082
+ } else {
4083
+ sendControlResponseError(msg, `Unsupported control request subtype: ${msg.request.subtype}`);
4084
+ }
4085
+ continue;
4086
+ } else if (message.type === "control_response") {
4087
+ if (options.replayUserMessages) {
4088
+ output.enqueue(message);
4089
+ }
4090
+ continue;
4091
+ } else if (message.type === "keep_alive") {
4092
+ continue;
4093
+ } else if (message.type === "update_environment_variables") {
4094
+ continue;
4095
+ } else if (message.type === "assistant" || message.type === "system") {
4096
+ const internalMsgs = toInternalMessages([message]);
4097
+ mutableMessages.push(...internalMsgs);
4098
+ if (message.type === "assistant" && options.replayUserMessages) {
4099
+ output.enqueue(message);
4100
+ }
4101
+ continue;
4102
+ }
4103
+ if (message.type !== "user") {
4104
+ continue;
4105
+ }
4106
+ const userMsg = message;
4107
+ initialized = true;
4108
+ if (userMsg.uuid) {
4109
+ const sessionId = getSessionId();
4110
+ const existsInSession = await doesMessageExistInSession(sessionId, userMsg.uuid);
4111
+ if (existsInSession || receivedMessageUuids.has(userMsg.uuid)) {
4112
+ logForDebugging(`Skipping duplicate user message: ${userMsg.uuid}`);
4113
+ if (options.replayUserMessages) {
4114
+ logForDebugging(`Sending acknowledgment for duplicate user message: ${userMsg.uuid}`);
4115
+ output.enqueue({
4116
+ type: "user",
4117
+ content: userMsg.message?.content ?? "",
4118
+ message: userMsg.message,
4119
+ session_id: sessionId,
4120
+ parent_tool_use_id: null,
4121
+ uuid: userMsg.uuid,
4122
+ timestamp: userMsg.timestamp,
4123
+ isReplay: true
4124
+ });
4125
+ }
4126
+ if (existsInSession) {
4127
+ notifyCommandLifecycle(userMsg.uuid, "completed");
4128
+ }
4129
+ continue;
4130
+ }
4131
+ trackReceivedMessageUuid(userMsg.uuid);
4132
+ }
4133
+ enqueue({
4134
+ mode: "prompt",
4135
+ value: await resolveAndPrepend(userMsg, userMsg.message.content),
4136
+ uuid: userMsg.uuid,
4137
+ priority: userMsg.priority
4138
+ });
4139
+ if (false) {}
4140
+ run();
4141
+ }
4142
+ inputClosed = true;
4143
+ cronScheduler?.stop();
4144
+ if (!running) {
4145
+ if (suggestionState.inflightPromise) {
4146
+ await Promise.race([suggestionState.inflightPromise, sleep(5000)]);
4147
+ }
4148
+ suggestionState.abortController?.abort();
4149
+ suggestionState.abortController = null;
4150
+ await finalizePendingAsyncHooks();
4151
+ unsubscribeSkillChanges();
4152
+ unsubscribeAuthStatus?.();
4153
+ statusListeners.delete(rateLimitListener);
4154
+ output.done();
4155
+ }
4156
+ })();
4157
+ return output;
4158
+ }
4159
+ function createCanUseToolWithPermissionPrompt(permissionPromptTool) {
4160
+ const canUseTool = async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
4161
+ const mainPermissionResult = forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId);
4162
+ if (mainPermissionResult.behavior === "allow" || mainPermissionResult.behavior === "deny") {
4163
+ return mainPermissionResult;
4164
+ }
4165
+ const { signal: combinedSignal, cleanup: cleanupAbortListener } = createCombinedAbortSignal(toolUseContext.abortController.signal);
4166
+ if (combinedSignal.aborted) {
4167
+ cleanupAbortListener();
4168
+ return {
4169
+ behavior: "deny",
4170
+ message: "Permission prompt was aborted.",
4171
+ decisionReason: {
4172
+ type: "permissionPromptTool",
4173
+ permissionPromptToolName: tool.name,
4174
+ toolResult: undefined
4175
+ }
4176
+ };
4177
+ }
4178
+ const abortPromise = new Promise((resolve) => {
4179
+ combinedSignal.addEventListener("abort", () => resolve("aborted"), {
4180
+ once: true
4181
+ });
4182
+ });
4183
+ const toolCallPromise = permissionPromptTool.call({
4184
+ tool_name: tool.name,
4185
+ input,
4186
+ tool_use_id: toolUseId
4187
+ }, toolUseContext, canUseTool, assistantMessage);
4188
+ const raceResult = await Promise.race([toolCallPromise, abortPromise]);
4189
+ cleanupAbortListener();
4190
+ if (raceResult === "aborted" || combinedSignal.aborted) {
4191
+ return {
4192
+ behavior: "deny",
4193
+ message: "Permission prompt was aborted.",
4194
+ decisionReason: {
4195
+ type: "permissionPromptTool",
4196
+ permissionPromptToolName: tool.name,
4197
+ toolResult: undefined
4198
+ }
4199
+ };
4200
+ }
4201
+ const result = raceResult;
4202
+ const permissionToolResultBlockParam = permissionPromptTool.mapToolResultToToolResultBlockParam(result.data, "1");
4203
+ if (!permissionToolResultBlockParam.content || !Array.isArray(permissionToolResultBlockParam.content) || !permissionToolResultBlockParam.content[0] || permissionToolResultBlockParam.content[0].type !== "text" || typeof permissionToolResultBlockParam.content[0].text !== "string") {
4204
+ throw new Error('Permission prompt tool returned an invalid result. Expected a single text block param with type="text" and a string text value.');
4205
+ }
4206
+ return permissionPromptToolResultToPermissionDecision(outputSchema().parse(safeParseJSON(permissionToolResultBlockParam.content[0].text)), permissionPromptTool, input, toolUseContext);
4207
+ };
4208
+ return canUseTool;
4209
+ }
4210
+ function getCanUseToolFn(permissionPromptToolName, structuredIO, getMcpTools, onPermissionPrompt) {
4211
+ if (permissionPromptToolName === "stdio") {
4212
+ return structuredIO.createCanUseTool(onPermissionPrompt);
4213
+ }
4214
+ if (!permissionPromptToolName) {
4215
+ return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => forceDecision ?? await hasPermissionsToUseTool(tool, input, toolUseContext, assistantMessage, toolUseId);
4216
+ }
4217
+ let resolved = null;
4218
+ return async (tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision) => {
4219
+ if (!resolved) {
4220
+ const mcpTools = getMcpTools();
4221
+ const permissionPromptTool = mcpTools.find((t) => toolMatchesName(t, permissionPromptToolName));
4222
+ if (!permissionPromptTool) {
4223
+ const error = `Error: MCP tool ${permissionPromptToolName} (passed via --permission-prompt-tool) not found. Available MCP tools: ${mcpTools.map((t) => t.name).join(", ") || "none"}`;
4224
+ process.stderr.write(`${error}
4225
+ `);
4226
+ gracefulShutdownSync(1);
4227
+ throw new Error(error);
4228
+ }
4229
+ if (!permissionPromptTool.inputJSONSchema) {
4230
+ const error = `Error: tool ${permissionPromptToolName} (passed via --permission-prompt-tool) must be an MCP tool`;
4231
+ process.stderr.write(`${error}
4232
+ `);
4233
+ gracefulShutdownSync(1);
4234
+ throw new Error(error);
4235
+ }
4236
+ resolved = createCanUseToolWithPermissionPrompt(permissionPromptTool);
4237
+ }
4238
+ return resolved(tool, input, toolUseContext, assistantMessage, toolUseId, forceDecision);
4239
+ };
4240
+ }
4241
+ async function handleInitializeRequest(request, requestId, initialized, output, commands, modelInfos, structuredIO, enableAuthStatus, options, agents, getAppState) {
4242
+ if (initialized) {
4243
+ output.enqueue({
4244
+ type: "control_response",
4245
+ response: {
4246
+ subtype: "error",
4247
+ error: "Already initialized",
4248
+ request_id: requestId,
4249
+ pending_permission_requests: structuredIO.getPendingPermissionRequests()
4250
+ }
4251
+ });
4252
+ return;
4253
+ }
4254
+ if (request.systemPrompt !== undefined) {
4255
+ options.systemPrompt = request.systemPrompt;
4256
+ }
4257
+ if (request.appendSystemPrompt !== undefined) {
4258
+ options.appendSystemPrompt = request.appendSystemPrompt;
4259
+ }
4260
+ if (request.promptSuggestions !== undefined) {
4261
+ options.promptSuggestions = request.promptSuggestions;
4262
+ }
4263
+ if (request.agents) {
4264
+ const stdinAgents = parseAgentsFromJson(request.agents, "flagSettings");
4265
+ agents.push(...stdinAgents);
4266
+ }
4267
+ if (options.agent) {
4268
+ const alreadyResolved = getMainThreadAgentType() === options.agent;
4269
+ const mainThreadAgent = agents.find((a) => a.agentType === options.agent);
4270
+ if (mainThreadAgent && !alreadyResolved) {
4271
+ setMainThreadAgentType(mainThreadAgent.agentType);
4272
+ if (!options.systemPrompt && !isBuiltInAgent(mainThreadAgent)) {
4273
+ const agentSystemPrompt = mainThreadAgent.getSystemPrompt();
4274
+ if (agentSystemPrompt) {
4275
+ options.systemPrompt = agentSystemPrompt;
4276
+ }
4277
+ }
4278
+ if (!options.userSpecifiedModel && mainThreadAgent.model && mainThreadAgent.model !== "inherit") {
4279
+ const agentModel = parseUserSpecifiedModel(mainThreadAgent.model);
4280
+ setMainLoopModelOverride(agentModel);
4281
+ }
4282
+ if (mainThreadAgent.initialPrompt) {
4283
+ structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
4284
+ }
4285
+ } else if (mainThreadAgent?.initialPrompt) {
4286
+ structuredIO.prependUserMessage(mainThreadAgent.initialPrompt);
4287
+ }
4288
+ }
4289
+ const settings = getSettings_DEPRECATED();
4290
+ const outputStyle = settings?.outputStyle || DEFAULT_OUTPUT_STYLE_NAME;
4291
+ const availableOutputStyles = await getAllOutputStyles(getCwd());
4292
+ const accountInfo = getAccountInformation();
4293
+ if (request.hooks) {
4294
+ const hooks = {};
4295
+ for (const [event, matchers] of Object.entries(request.hooks)) {
4296
+ hooks[event] = matchers.map((matcher) => {
4297
+ const callbacks = matcher.hookCallbackIds.map((callbackId) => {
4298
+ return structuredIO.createHookCallback(callbackId, matcher.timeout);
4299
+ });
4300
+ return {
4301
+ matcher: matcher.matcher,
4302
+ hooks: callbacks
4303
+ };
4304
+ });
4305
+ }
4306
+ registerHookCallbacks(hooks);
4307
+ }
4308
+ if (request.jsonSchema) {
4309
+ setInitJsonSchema(request.jsonSchema);
4310
+ }
4311
+ const initResponse = {
4312
+ commands: commands.filter((cmd) => cmd.userInvocable !== false).map((cmd) => ({
4313
+ name: getCommandName(cmd),
4314
+ description: formatDescriptionWithSource(cmd),
4315
+ argumentHint: cmd.argumentHint || ""
4316
+ })),
4317
+ agents: agents.map((agent) => ({
4318
+ name: agent.agentType,
4319
+ description: agent.whenToUse,
4320
+ model: agent.model === "inherit" ? undefined : agent.model
4321
+ })),
4322
+ output_style: outputStyle,
4323
+ available_output_styles: Object.keys(availableOutputStyles),
4324
+ models: modelInfos,
4325
+ account: {
4326
+ email: accountInfo?.email,
4327
+ organization: accountInfo?.organization,
4328
+ subscriptionType: accountInfo?.subscription,
4329
+ tokenSource: accountInfo?.tokenSource,
4330
+ apiKeySource: accountInfo?.apiKeySource,
4331
+ apiProvider: getAPIProvider()
4332
+ },
4333
+ pid: process.pid
4334
+ };
4335
+ if (isFastModeEnabled() && isFastModeAvailable()) {
4336
+ const appState = getAppState();
4337
+ initResponse.fast_mode_state = getFastModeState(options.userSpecifiedModel ?? null, appState.fastMode);
4338
+ }
4339
+ output.enqueue({
4340
+ type: "control_response",
4341
+ response: {
4342
+ subtype: "success",
4343
+ request_id: requestId,
4344
+ response: initResponse
4345
+ }
4346
+ });
4347
+ if (enableAuthStatus) {
4348
+ const authStatusManager = AwsAuthStatusManager.getInstance();
4349
+ const status = authStatusManager.getStatus();
4350
+ if (status) {
4351
+ output.enqueue({
4352
+ type: "auth_status",
4353
+ isAuthenticating: status.isAuthenticating,
4354
+ output: status.output,
4355
+ error: status.error,
4356
+ uuid: randomUUID3(),
4357
+ session_id: getSessionId()
4358
+ });
4359
+ }
4360
+ }
4361
+ }
4362
+ async function handleRewindFiles(userMessageId, appState, setAppState, dryRun) {
4363
+ if (!fileHistoryEnabled()) {
4364
+ return { canRewind: false, error: "File rewinding is not enabled.", filesChanged: [] };
4365
+ }
4366
+ if (!fileHistoryCanRestore(appState.fileHistory, userMessageId)) {
4367
+ return {
4368
+ canRewind: false,
4369
+ error: "No file checkpoint found for this message.",
4370
+ filesChanged: []
4371
+ };
4372
+ }
4373
+ if (dryRun) {
4374
+ const diffStats = await fileHistoryGetDiffStats(appState.fileHistory, userMessageId);
4375
+ return {
4376
+ canRewind: true,
4377
+ filesChanged: diffStats?.filesChanged,
4378
+ insertions: diffStats?.insertions,
4379
+ deletions: diffStats?.deletions
4380
+ };
4381
+ }
4382
+ try {
4383
+ await fileHistoryRewind((updater) => setAppState((prev) => ({
4384
+ ...prev,
4385
+ fileHistory: updater(prev.fileHistory)
4386
+ })), userMessageId);
4387
+ } catch (error) {
4388
+ return {
4389
+ canRewind: false,
4390
+ error: `Failed to rewind: ${errorMessage(error)}`,
4391
+ filesChanged: []
4392
+ };
4393
+ }
4394
+ return { canRewind: true, filesChanged: [] };
4395
+ }
4396
+ function handleSetPermissionMode(request, requestId, toolPermissionContext, output) {
4397
+ if (request.mode === "bypassPermissions") {
4398
+ if (isBypassPermissionsModeDisabled()) {
4399
+ output.enqueue({
4400
+ type: "control_response",
4401
+ response: {
4402
+ subtype: "error",
4403
+ request_id: requestId,
4404
+ error: "Cannot set permission mode to bypassPermissions because it is disabled by settings or configuration"
4405
+ }
4406
+ });
4407
+ return toolPermissionContext;
4408
+ }
4409
+ if (!toolPermissionContext.isBypassPermissionsModeAvailable) {
4410
+ output.enqueue({
4411
+ type: "control_response",
4412
+ response: {
4413
+ subtype: "error",
4414
+ request_id: requestId,
4415
+ error: "Cannot set permission mode to bypassPermissions because the session was not launched with --dangerously-skip-permissions"
4416
+ }
4417
+ });
4418
+ return toolPermissionContext;
4419
+ }
4420
+ }
4421
+ if (request.mode === "auto" && !isAutoModeGateEnabled()) {
4422
+ const reason = getAutoModeUnavailableReason();
4423
+ output.enqueue({
4424
+ type: "control_response",
4425
+ response: {
4426
+ subtype: "error",
4427
+ request_id: requestId,
4428
+ error: reason ? `Cannot set permission mode to auto: ${getAutoModeUnavailableNotification(reason)}` : "Cannot set permission mode to auto"
4429
+ }
4430
+ });
4431
+ return toolPermissionContext;
4432
+ }
4433
+ output.enqueue({
4434
+ type: "control_response",
4435
+ response: {
4436
+ subtype: "success",
4437
+ request_id: requestId,
4438
+ response: {
4439
+ mode: request.mode
4440
+ }
4441
+ }
4442
+ });
4443
+ return {
4444
+ ...transitionPermissionMode(toolPermissionContext.mode, request.mode, toolPermissionContext),
4445
+ mode: request.mode
4446
+ };
4447
+ }
4448
+ function handleChannelEnable(requestId, serverName, connectionPool, output) {
4449
+ const respondError = (error) => output.enqueue({
4450
+ type: "control_response",
4451
+ response: { subtype: "error", request_id: requestId, error }
4452
+ });
4453
+ if (true) {
4454
+ return respondError("channels feature not available in this build");
4455
+ }
4456
+ const connection = connectionPool.find((c) => c.name === serverName && c.type === "connected");
4457
+ if (!connection || connection.type !== "connected") {
4458
+ return respondError(`server ${serverName} is not connected`);
4459
+ }
4460
+ const pluginSource = connection.config.pluginSource;
4461
+ const parsed = pluginSource ? parsePluginIdentifier(pluginSource) : undefined;
4462
+ if (!parsed?.marketplace) {
4463
+ return respondError(`server ${serverName} is not plugin-sourced; channel_enable requires a marketplace plugin`);
4464
+ }
4465
+ const entry = {
4466
+ kind: "plugin",
4467
+ name: parsed.name,
4468
+ marketplace: parsed.marketplace
4469
+ };
4470
+ const prior = getAllowedChannels();
4471
+ const already = prior.some((e) => e.kind === "plugin" && e.name === entry.name && e.marketplace === entry.marketplace);
4472
+ if (!already)
4473
+ setAllowedChannels([...prior, entry]);
4474
+ const gate = gateChannelServer(serverName, connection.capabilities, pluginSource);
4475
+ if (gate.action === "skip") {
4476
+ if (!already)
4477
+ setAllowedChannels(prior);
4478
+ return respondError(gate.reason);
4479
+ }
4480
+ const pluginId = `${entry.name}@${entry.marketplace}`;
4481
+ logMCPDebug(serverName, "Channel notifications registered");
4482
+ logEvent("tengu_mcp_channel_enable", { plugin: pluginId });
4483
+ connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
4484
+ const { content, meta } = notification.params;
4485
+ logMCPDebug(serverName, `notifications/claude/channel: ${content.slice(0, 80)}`);
4486
+ logEvent("tengu_mcp_channel_message", {
4487
+ content_length: content.length,
4488
+ meta_key_count: Object.keys(meta ?? {}).length,
4489
+ entry_kind: "plugin",
4490
+ is_dev: false,
4491
+ plugin: pluginId
4492
+ });
4493
+ enqueue({
4494
+ mode: "prompt",
4495
+ value: wrapChannelMessage(serverName, content, meta),
4496
+ priority: "next",
4497
+ isMeta: true,
4498
+ origin: { kind: "channel", server: serverName },
4499
+ skipSlashCommands: true
4500
+ });
4501
+ });
4502
+ output.enqueue({
4503
+ type: "control_response",
4504
+ response: {
4505
+ subtype: "success",
4506
+ request_id: requestId,
4507
+ response: undefined
4508
+ }
4509
+ });
4510
+ }
4511
+ function reregisterChannelHandlerAfterReconnect(connection) {
4512
+ if (true)
4513
+ return;
4514
+ if (connection.type !== "connected")
4515
+ return;
4516
+ const gate = gateChannelServer(connection.name, connection.capabilities, connection.config.pluginSource);
4517
+ if (gate.action !== "register")
4518
+ return;
4519
+ const entry = findChannelEntry(connection.name, getAllowedChannels());
4520
+ const pluginId = entry?.kind === "plugin" ? `${entry.name}@${entry.marketplace}` : undefined;
4521
+ logMCPDebug(connection.name, "Channel notifications re-registered after reconnect");
4522
+ connection.client.setNotificationHandler(ChannelMessageNotificationSchema(), async (notification) => {
4523
+ const { content, meta } = notification.params;
4524
+ logMCPDebug(connection.name, `notifications/claude/channel: ${content.slice(0, 80)}`);
4525
+ logEvent("tengu_mcp_channel_message", {
4526
+ content_length: content.length,
4527
+ meta_key_count: Object.keys(meta ?? {}).length,
4528
+ entry_kind: entry?.kind,
4529
+ is_dev: entry?.dev ?? false,
4530
+ plugin: pluginId
4531
+ });
4532
+ enqueue({
4533
+ mode: "prompt",
4534
+ value: wrapChannelMessage(connection.name, content, meta),
4535
+ priority: "next",
4536
+ isMeta: true,
4537
+ origin: { kind: "channel", server: connection.name },
4538
+ skipSlashCommands: true
4539
+ });
4540
+ });
4541
+ }
4542
+ function emitLoadError(message, outputFormat) {
4543
+ if (outputFormat === "stream-json") {
4544
+ const errorResult = {
4545
+ type: "result",
4546
+ subtype: "error_during_execution",
4547
+ duration_ms: 0,
4548
+ duration_api_ms: 0,
4549
+ is_error: true,
4550
+ num_turns: 0,
4551
+ stop_reason: null,
4552
+ session_id: getSessionId(),
4553
+ total_cost_usd: 0,
4554
+ usage: EMPTY_USAGE,
4555
+ modelUsage: {},
4556
+ permission_denials: [],
4557
+ uuid: randomUUID3(),
4558
+ errors: [message]
4559
+ };
4560
+ process.stdout.write(jsonStringify(errorResult) + `
4561
+ `);
4562
+ } else {
4563
+ process.stderr.write(message + `
4564
+ `);
4565
+ }
4566
+ }
4567
+ function removeInterruptedMessage(messages, interruptedUserMessage) {
4568
+ const idx = messages.findIndex((m) => m.uuid === interruptedUserMessage.uuid);
4569
+ if (idx !== -1) {
4570
+ messages.splice(idx, 2);
4571
+ }
4572
+ }
4573
+ async function loadInitialMessages(setAppState, options) {
4574
+ const persistSession = !isSessionPersistenceDisabled();
4575
+ if (options.continue) {
4576
+ try {
4577
+ logEvent("tengu_continue_print", {});
4578
+ const result = await loadConversationForResume(undefined, undefined);
4579
+ if (result) {
4580
+ if (false) {}
4581
+ if (!options.forkSession) {
4582
+ if (result.sessionId) {
4583
+ switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
4584
+ if (persistSession) {
4585
+ await resetSessionFilePointer();
4586
+ }
4587
+ }
4588
+ }
4589
+ restoreSessionStateFromLog(result, setAppState);
4590
+ restoreSessionMetadata(options.forkSession ? { ...result, worktreeSession: undefined } : result);
4591
+ if (false) {}
4592
+ return {
4593
+ messages: result.messages,
4594
+ turnInterruptionState: result.turnInterruptionState,
4595
+ agentSetting: result.agentSetting
4596
+ };
4597
+ }
4598
+ } catch (error) {
4599
+ logError(error);
4600
+ gracefulShutdownSync(1);
4601
+ return { messages: [] };
4602
+ }
4603
+ }
4604
+ if (options.teleport) {
4605
+ try {
4606
+ if (!isPolicyAllowed("allow_remote_sessions")) {
4607
+ throw new Error("Remote sessions are disabled by your organization's policy.");
4608
+ }
4609
+ logEvent("tengu_teleport_print", {});
4610
+ if (typeof options.teleport !== "string") {
4611
+ throw new Error("No session ID provided for teleport");
4612
+ }
4613
+ const {
4614
+ checkOutTeleportedSessionBranch,
4615
+ processMessagesForTeleportResume,
4616
+ teleportResumeCodeSession,
4617
+ validateGitState
4618
+ } = await import("./chunk-bj6k61m9.js");
4619
+ await validateGitState();
4620
+ const teleportResult = await teleportResumeCodeSession(options.teleport);
4621
+ const { branchError } = await checkOutTeleportedSessionBranch(teleportResult.branch);
4622
+ return {
4623
+ messages: processMessagesForTeleportResume(teleportResult.log, branchError)
4624
+ };
4625
+ } catch (error) {
4626
+ logError(error);
4627
+ gracefulShutdownSync(1);
4628
+ return { messages: [] };
4629
+ }
4630
+ }
4631
+ if (options.resume) {
4632
+ try {
4633
+ logEvent("tengu_resume_print", {});
4634
+ const parsedSessionId = parseSessionIdentifier(typeof options.resume === "string" ? options.resume : "");
4635
+ if (!parsedSessionId) {
4636
+ let errorMessage2 = "Error: --resume requires a valid session ID when used with --print. Usage: claude -p --resume <session-id>";
4637
+ if (typeof options.resume === "string") {
4638
+ errorMessage2 += `. Session IDs must be in UUID format (e.g., 550e8400-e29b-41d4-a716-446655440000). Provided value "${options.resume}" is not a valid UUID`;
4639
+ }
4640
+ emitLoadError(errorMessage2, options.outputFormat);
4641
+ gracefulShutdownSync(1);
4642
+ return { messages: [] };
4643
+ }
4644
+ if (isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
4645
+ const [, metadata] = await Promise.all([
4646
+ hydrateFromCCRv2InternalEvents(parsedSessionId.sessionId),
4647
+ options.restoredWorkerState
4648
+ ]);
4649
+ if (metadata) {
4650
+ setAppState(externalMetadataToAppState(metadata));
4651
+ if (typeof metadata.model === "string") {
4652
+ setMainLoopModelOverride(metadata.model);
4653
+ }
4654
+ }
4655
+ } else if (parsedSessionId.isUrl && parsedSessionId.ingressUrl && isEnvTruthy(process.env.ENABLE_SESSION_PERSISTENCE)) {
4656
+ await hydrateRemoteSession(parsedSessionId.sessionId, parsedSessionId.ingressUrl);
4657
+ }
4658
+ const result = await loadConversationForResume(parsedSessionId.sessionId, parsedSessionId.jsonlFile || undefined);
4659
+ if (!result || result.messages.length === 0) {
4660
+ if (parsedSessionId.isUrl || isEnvTruthy(process.env.CLAUDE_CODE_USE_CCR_V2)) {
4661
+ return {
4662
+ messages: await (options.sessionStartHooksPromise ?? processSessionStartHooks("startup"))
4663
+ };
4664
+ } else {
4665
+ emitLoadError(`No conversation found with session ID: ${parsedSessionId.sessionId}`, options.outputFormat);
4666
+ gracefulShutdownSync(1);
4667
+ return { messages: [] };
4668
+ }
4669
+ }
4670
+ if (options.resumeSessionAt) {
4671
+ const index = result.messages.findIndex((m) => m.uuid === options.resumeSessionAt);
4672
+ if (index < 0) {
4673
+ emitLoadError(`No message found with message.uuid of: ${options.resumeSessionAt}`, options.outputFormat);
4674
+ gracefulShutdownSync(1);
4675
+ return { messages: [] };
4676
+ }
4677
+ result.messages = index >= 0 ? result.messages.slice(0, index + 1) : [];
4678
+ }
4679
+ if (false) {}
4680
+ if (!options.forkSession && result.sessionId) {
4681
+ switchSession(asSessionId(result.sessionId), result.fullPath ? dirname(result.fullPath) : null);
4682
+ if (persistSession) {
4683
+ await resetSessionFilePointer();
4684
+ }
4685
+ }
4686
+ restoreSessionStateFromLog(result, setAppState);
4687
+ restoreSessionMetadata(options.forkSession ? { ...result, worktreeSession: undefined } : result);
4688
+ if (false) {}
4689
+ return {
4690
+ messages: result.messages,
4691
+ turnInterruptionState: result.turnInterruptionState,
4692
+ agentSetting: result.agentSetting
4693
+ };
4694
+ } catch (error) {
4695
+ logError(error);
4696
+ const errorMessage2 = error instanceof Error ? `Failed to resume session: ${error.message}` : "Failed to resume session with --print mode";
4697
+ emitLoadError(errorMessage2, options.outputFormat);
4698
+ gracefulShutdownSync(1);
4699
+ return { messages: [] };
4700
+ }
4701
+ }
4702
+ return {
4703
+ messages: await (options.sessionStartHooksPromise ?? processSessionStartHooks("startup"))
4704
+ };
4705
+ }
4706
+ function getStructuredIO(inputPrompt, options) {
4707
+ let inputStream;
4708
+ if (typeof inputPrompt === "string") {
4709
+ if (inputPrompt.trim() !== "") {
4710
+ inputStream = fromArray([
4711
+ jsonStringify({
4712
+ type: "user",
4713
+ content: inputPrompt,
4714
+ uuid: "",
4715
+ session_id: "",
4716
+ message: {
4717
+ role: "user",
4718
+ content: inputPrompt
4719
+ },
4720
+ parent_tool_use_id: null
4721
+ })
4722
+ ]);
4723
+ } else {
4724
+ inputStream = fromArray([]);
4725
+ }
4726
+ } else {
4727
+ inputStream = inputPrompt;
4728
+ }
4729
+ return options.sdkUrl ? new RemoteIO(options.sdkUrl, inputStream, options.replayUserMessages) : new StructuredIO(inputStream, options.replayUserMessages);
4730
+ }
4731
+ async function handleOrphanedPermissionResponse({
4732
+ message,
4733
+ setAppState,
4734
+ onEnqueued,
4735
+ handledToolUseIds
4736
+ }) {
4737
+ const responseInner = message.response;
4738
+ if (responseInner?.subtype === "success" && responseInner.response?.toolUseID && typeof responseInner.response.toolUseID === "string") {
4739
+ const permissionResult = responseInner.response;
4740
+ const toolUseID = permissionResult.toolUseID;
4741
+ if (!toolUseID) {
4742
+ return false;
4743
+ }
4744
+ logForDebugging(`handleOrphanedPermissionResponse: received orphaned control_response for toolUseID=${toolUseID} request_id=${responseInner.request_id}`);
4745
+ if (handledToolUseIds.has(toolUseID)) {
4746
+ logForDebugging(`handleOrphanedPermissionResponse: skipping duplicate orphaned permission for toolUseID=${toolUseID} (already handled)`);
4747
+ return false;
4748
+ }
4749
+ const assistantMessage = await findUnresolvedToolUse(toolUseID);
4750
+ if (!assistantMessage) {
4751
+ logForDebugging(`handleOrphanedPermissionResponse: no unresolved tool_use found for toolUseID=${toolUseID} (already resolved in transcript)`);
4752
+ return false;
4753
+ }
4754
+ handledToolUseIds.add(toolUseID);
4755
+ logForDebugging(`handleOrphanedPermissionResponse: enqueuing orphaned permission for toolUseID=${toolUseID} messageID=${assistantMessage.message.id}`);
4756
+ enqueue({
4757
+ mode: "orphaned-permission",
4758
+ value: [],
4759
+ orphanedPermission: {
4760
+ permissionResult,
4761
+ assistantMessage
4762
+ }
4763
+ });
4764
+ onEnqueued?.();
4765
+ return true;
4766
+ }
4767
+ return false;
4768
+ }
4769
+ function toScopedConfig(config) {
4770
+ return { ...config, scope: "dynamic" };
4771
+ }
4772
+ async function handleMcpSetServers(servers, sdkState, dynamicState, setAppState) {
4773
+ const { allowed: allowedServers, blocked } = filterMcpServersByPolicy(servers);
4774
+ const policyErrors = {};
4775
+ for (const name of blocked) {
4776
+ policyErrors[name] = "Blocked by enterprise policy (allowedMcpServers/deniedMcpServers)";
4777
+ }
4778
+ const sdkServers = {};
4779
+ const processServers = {};
4780
+ for (const [name, config] of Object.entries(allowedServers)) {
4781
+ if (config.type === "sdk") {
4782
+ sdkServers[name] = config;
4783
+ } else {
4784
+ processServers[name] = config;
4785
+ }
4786
+ }
4787
+ const currentSdkNames = new Set(Object.keys(sdkState.configs));
4788
+ const newSdkNames = new Set(Object.keys(sdkServers));
4789
+ const sdkAdded = [];
4790
+ const sdkRemoved = [];
4791
+ const newSdkConfigs = { ...sdkState.configs };
4792
+ let newSdkClients = [...sdkState.clients];
4793
+ let newSdkTools = [...sdkState.tools];
4794
+ for (const name of currentSdkNames) {
4795
+ if (!newSdkNames.has(name)) {
4796
+ const client = newSdkClients.find((c) => c.name === name);
4797
+ if (client && client.type === "connected") {
4798
+ await client.cleanup();
4799
+ }
4800
+ newSdkClients = newSdkClients.filter((c) => c.name !== name);
4801
+ const prefix = `mcp__${name}__`;
4802
+ newSdkTools = newSdkTools.filter((t) => !t.name.startsWith(prefix));
4803
+ delete newSdkConfigs[name];
4804
+ sdkRemoved.push(name);
4805
+ }
4806
+ }
4807
+ for (const [name, config] of Object.entries(sdkServers)) {
4808
+ if (!currentSdkNames.has(name)) {
4809
+ newSdkConfigs[name] = config;
4810
+ const pendingClient = {
4811
+ type: "pending",
4812
+ name,
4813
+ config: { ...config, scope: "dynamic" }
4814
+ };
4815
+ newSdkClients = [...newSdkClients, pendingClient];
4816
+ sdkAdded.push(name);
4817
+ }
4818
+ }
4819
+ const processResult = await reconcileMcpServers(processServers, dynamicState, setAppState);
4820
+ return {
4821
+ response: {
4822
+ added: [...sdkAdded, ...processResult.response.added],
4823
+ removed: [...sdkRemoved, ...processResult.response.removed],
4824
+ errors: { ...policyErrors, ...processResult.response.errors }
4825
+ },
4826
+ newSdkState: {
4827
+ configs: newSdkConfigs,
4828
+ clients: newSdkClients,
4829
+ tools: newSdkTools
4830
+ },
4831
+ newDynamicState: processResult.newState,
4832
+ sdkServersChanged: sdkAdded.length > 0 || sdkRemoved.length > 0
4833
+ };
4834
+ }
4835
+ async function reconcileMcpServers(desiredConfigs, currentState, setAppState) {
4836
+ const currentNames = new Set(Object.keys(currentState.configs));
4837
+ const desiredNames = new Set(Object.keys(desiredConfigs));
4838
+ const toRemove = [...currentNames].filter((n) => !desiredNames.has(n));
4839
+ const toAdd = [...desiredNames].filter((n) => !currentNames.has(n));
4840
+ const toCheck = [...currentNames].filter((n) => desiredNames.has(n));
4841
+ const toReplace = toCheck.filter((name) => {
4842
+ const currentConfig = currentState.configs[name];
4843
+ const desiredConfigRaw = desiredConfigs[name];
4844
+ if (!currentConfig || !desiredConfigRaw)
4845
+ return true;
4846
+ const desiredConfig = toScopedConfig(desiredConfigRaw);
4847
+ return !areMcpConfigsEqual(currentConfig, desiredConfig);
4848
+ });
4849
+ const removed = [];
4850
+ const added = [];
4851
+ const errors = {};
4852
+ let newClients = [...currentState.clients];
4853
+ let newTools = [...currentState.tools];
4854
+ for (const name of [...toRemove, ...toReplace]) {
4855
+ const client = newClients.find((c) => c.name === name);
4856
+ const config = currentState.configs[name];
4857
+ if (client && config) {
4858
+ if (client.type === "connected") {
4859
+ try {
4860
+ await client.cleanup();
4861
+ } catch (e) {
4862
+ logError(e);
4863
+ }
4864
+ }
4865
+ await clearServerCache(name, config);
4866
+ }
4867
+ const prefix = `mcp__${name}__`;
4868
+ newTools = newTools.filter((t) => !t.name.startsWith(prefix));
4869
+ newClients = newClients.filter((c) => c.name !== name);
4870
+ if (toRemove.includes(name)) {
4871
+ removed.push(name);
4872
+ }
4873
+ }
4874
+ for (const name of [...toAdd, ...toReplace]) {
4875
+ const config = desiredConfigs[name];
4876
+ if (!config)
4877
+ continue;
4878
+ const scopedConfig = toScopedConfig(config);
4879
+ if (config.type === "sdk") {
4880
+ added.push(name);
4881
+ continue;
4882
+ }
4883
+ try {
4884
+ const client = await connectToServer(name, scopedConfig);
4885
+ newClients.push(client);
4886
+ if (client.type === "connected") {
4887
+ const serverTools = await fetchToolsForClient(client);
4888
+ newTools.push(...serverTools);
4889
+ } else if (client.type === "failed") {
4890
+ errors[name] = client.error || "Connection failed";
4891
+ }
4892
+ added.push(name);
4893
+ } catch (e) {
4894
+ const err = toError(e);
4895
+ errors[name] = err.message;
4896
+ logError(err);
4897
+ }
4898
+ }
4899
+ const newConfigs = {};
4900
+ for (const name of desiredNames) {
4901
+ const config = desiredConfigs[name];
4902
+ if (config) {
4903
+ newConfigs[name] = toScopedConfig(config);
4904
+ }
4905
+ }
4906
+ const newState = {
4907
+ clients: newClients,
4908
+ tools: newTools,
4909
+ configs: newConfigs
4910
+ };
4911
+ setAppState((prev) => {
4912
+ const allDynamicServerNames = new Set([
4913
+ ...Object.keys(currentState.configs),
4914
+ ...Object.keys(newConfigs)
4915
+ ]);
4916
+ const nonDynamicTools = prev.mcp.tools.filter((t) => {
4917
+ for (const serverName of allDynamicServerNames) {
4918
+ if (t.name.startsWith(`mcp__${serverName}__`)) {
4919
+ return false;
4920
+ }
4921
+ }
4922
+ return true;
4923
+ });
4924
+ const nonDynamicClients = prev.mcp.clients.filter((c) => {
4925
+ return !allDynamicServerNames.has(c.name);
4926
+ });
4927
+ return {
4928
+ ...prev,
4929
+ mcp: {
4930
+ ...prev.mcp,
4931
+ tools: [...nonDynamicTools, ...newTools],
4932
+ clients: [...nonDynamicClients, ...newClients]
4933
+ }
4934
+ };
4935
+ });
4936
+ return {
4937
+ response: { added, removed, errors },
4938
+ newState
4939
+ };
4940
+ }
4941
+ export {
4942
+ runHeadless,
4943
+ removeInterruptedMessage,
4944
+ reconcileMcpServers,
4945
+ joinPromptValues,
4946
+ handleOrphanedPermissionResponse,
4947
+ handleMcpSetServers,
4948
+ getCanUseToolFn,
4949
+ createCanUseToolWithPermissionPrompt,
4950
+ canBatchWith
4951
+ };