@rainhole/rain-code 1.1.0

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 (496) hide show
  1. package/README.md +172 -0
  2. package/dist/chunk-06b2745w.js +3583 -0
  3. package/dist/chunk-06saje2v.js +39 -0
  4. package/dist/chunk-07069jq1.js +30 -0
  5. package/dist/chunk-0731m51q.js +8 -0
  6. package/dist/chunk-0bs2528v.js +192 -0
  7. package/dist/chunk-0fj1d707.js +313 -0
  8. package/dist/chunk-0gdkvtx4.js +117 -0
  9. package/dist/chunk-0jd8rpt4.js +34257 -0
  10. package/dist/chunk-0paqc2yw.js +15 -0
  11. package/dist/chunk-0pk0w4j1.js +332 -0
  12. package/dist/chunk-0rpb2bdp.js +8 -0
  13. package/dist/chunk-0rvwew67.js +9300 -0
  14. package/dist/chunk-0sa1g8jf.js +318 -0
  15. package/dist/chunk-0vkfrmqm.js +690 -0
  16. package/dist/chunk-0xgxxqhr.js +708 -0
  17. package/dist/chunk-0xjaqda8.js +1124 -0
  18. package/dist/chunk-0zep39v0.js +81 -0
  19. package/dist/chunk-1141xmr4.js +8 -0
  20. package/dist/chunk-12hn2mhy.js +17 -0
  21. package/dist/chunk-12rjry89.js +81 -0
  22. package/dist/chunk-168xb8v1.js +436 -0
  23. package/dist/chunk-1cwdhk7a.js +969 -0
  24. package/dist/chunk-1cx0fd76.js +132 -0
  25. package/dist/chunk-1erfksyp.js +107 -0
  26. package/dist/chunk-1h1tc4mw.js +126 -0
  27. package/dist/chunk-1h2famwb.js +49 -0
  28. package/dist/chunk-1jnbys9f.js +1811 -0
  29. package/dist/chunk-1k4fp6ft.js +389 -0
  30. package/dist/chunk-1mjn8xxc.js +22 -0
  31. package/dist/chunk-1mn6r4y2.js +747 -0
  32. package/dist/chunk-1p8myfza.js +1568 -0
  33. package/dist/chunk-1vthytca.js +79 -0
  34. package/dist/chunk-1y32rx73.js +145 -0
  35. package/dist/chunk-200781fd.js +64 -0
  36. package/dist/chunk-205mmm67.js +100 -0
  37. package/dist/chunk-209eh6ak.js +9381 -0
  38. package/dist/chunk-21mfpnva.js +85 -0
  39. package/dist/chunk-238g70xa.js +36 -0
  40. package/dist/chunk-24k6t9fa.js +151 -0
  41. package/dist/chunk-29gg6hx0.js +2992 -0
  42. package/dist/chunk-2a42s11t.js +412 -0
  43. package/dist/chunk-2ekjxh7d.js +289 -0
  44. package/dist/chunk-2eykm0j0.js +20 -0
  45. package/dist/chunk-2fwze72g.js +24 -0
  46. package/dist/chunk-2gzv8nrw.js +205 -0
  47. package/dist/chunk-2k995y2x.js +880 -0
  48. package/dist/chunk-2nayx6q1.js +63 -0
  49. package/dist/chunk-2pg9pmvc.js +182 -0
  50. package/dist/chunk-2qp2hc02.js +36 -0
  51. package/dist/chunk-2rj0dnps.js +436 -0
  52. package/dist/chunk-2t0xa4dt.js +145 -0
  53. package/dist/chunk-2ym6tnww.js +216 -0
  54. package/dist/chunk-30bpz5m2.js +34 -0
  55. package/dist/chunk-30rst83v.js +168 -0
  56. package/dist/chunk-36b2q5fg.js +1299 -0
  57. package/dist/chunk-3c25bcsw.js +17 -0
  58. package/dist/chunk-3ewzhjyb.js +207 -0
  59. package/dist/chunk-3h8a89gy.js +46 -0
  60. package/dist/chunk-3nk79af8.js +8 -0
  61. package/dist/chunk-3sfr7j85.js +884 -0
  62. package/dist/chunk-3w6s9m5w.js +16 -0
  63. package/dist/chunk-3x52v1wb.js +660 -0
  64. package/dist/chunk-404qm8xt.js +1715 -0
  65. package/dist/chunk-42fjay4q.js +141 -0
  66. package/dist/chunk-48649h96.js +8590 -0
  67. package/dist/chunk-495d85x1.js +8066 -0
  68. package/dist/chunk-4anj5saq.js +111 -0
  69. package/dist/chunk-4asynmj4.js +259 -0
  70. package/dist/chunk-4ck9wve9.js +225 -0
  71. package/dist/chunk-4cp6193g.js +9076 -0
  72. package/dist/chunk-4g3v8y12.js +23 -0
  73. package/dist/chunk-4geyher8.js +244 -0
  74. package/dist/chunk-4hv90qcz.js +8 -0
  75. package/dist/chunk-4jhr03e7.js +61 -0
  76. package/dist/chunk-4jm600zv.js +13 -0
  77. package/dist/chunk-4nspekjp.js +69 -0
  78. package/dist/chunk-4ptqcw4p.js +16 -0
  79. package/dist/chunk-4qj8cqbh.js +173 -0
  80. package/dist/chunk-4wxsg6a0.js +122 -0
  81. package/dist/chunk-4zfkzkt6.js +37 -0
  82. package/dist/chunk-54dckh8a.js +1169 -0
  83. package/dist/chunk-54y13759.js +650 -0
  84. package/dist/chunk-54yf6e8d.js +91 -0
  85. package/dist/chunk-57qz90z8.js +154 -0
  86. package/dist/chunk-59k0mjnc.js +120 -0
  87. package/dist/chunk-59p9jye4.js +104 -0
  88. package/dist/chunk-5c753bd4.js +64 -0
  89. package/dist/chunk-5cw6zwep.js +106 -0
  90. package/dist/chunk-5eaf3j24.js +133 -0
  91. package/dist/chunk-5me7398b.js +81 -0
  92. package/dist/chunk-5pevjsyw.js +118 -0
  93. package/dist/chunk-5q3c2rf4.js +107 -0
  94. package/dist/chunk-5xwtnq4g.js +146 -0
  95. package/dist/chunk-5z28bqne.js +6748 -0
  96. package/dist/chunk-613f6fbv.js +63 -0
  97. package/dist/chunk-641hawvm.js +95 -0
  98. package/dist/chunk-64c1avct.js +13 -0
  99. package/dist/chunk-64hks9ax.js +456 -0
  100. package/dist/chunk-677as3nh.js +15 -0
  101. package/dist/chunk-6bd8brc4.js +48 -0
  102. package/dist/chunk-6cs6mmez.js +112 -0
  103. package/dist/chunk-6dj5t602.js +341 -0
  104. package/dist/chunk-6e8vht4y.js +780 -0
  105. package/dist/chunk-6gr3c3w9.js +378 -0
  106. package/dist/chunk-6hkd32eh.js +83 -0
  107. package/dist/chunk-6jqxvef0.js +198 -0
  108. package/dist/chunk-6mh3vfa4.js +115 -0
  109. package/dist/chunk-6mpw9h55.js +1071 -0
  110. package/dist/chunk-6p4cyhb3.js +16 -0
  111. package/dist/chunk-6qvgnepd.js +26 -0
  112. package/dist/chunk-6r2bhsvt.js +6956 -0
  113. package/dist/chunk-6tq2v3rk.js +186 -0
  114. package/dist/chunk-7316m01k.js +125 -0
  115. package/dist/chunk-73rpbt04.js +1947 -0
  116. package/dist/chunk-75zk7zr1.js +309 -0
  117. package/dist/chunk-760252na.js +101 -0
  118. package/dist/chunk-764ec4ja.js +173 -0
  119. package/dist/chunk-76vgnv24.js +108 -0
  120. package/dist/chunk-7739pg2c.js +4261 -0
  121. package/dist/chunk-7a7hxy3d.js +167 -0
  122. package/dist/chunk-7aw745vx.js +40175 -0
  123. package/dist/chunk-7b6bg1r4.js +16128 -0
  124. package/dist/chunk-7ca4qskp.js +99 -0
  125. package/dist/chunk-7deph26x.js +311 -0
  126. package/dist/chunk-7ds8zqar.js +108 -0
  127. package/dist/chunk-7fqxw3d2.js +479 -0
  128. package/dist/chunk-7nysf9yd.js +266 -0
  129. package/dist/chunk-7tascxe2.js +90 -0
  130. package/dist/chunk-7wm5s02e.js +216 -0
  131. package/dist/chunk-7xmw2tcz.js +277 -0
  132. package/dist/chunk-7xyswgjh.js +8 -0
  133. package/dist/chunk-7zkhadkb.js +220 -0
  134. package/dist/chunk-8225arm6.js +6374 -0
  135. package/dist/chunk-83hfzbx3.js +10 -0
  136. package/dist/chunk-85tag8nv.js +1391 -0
  137. package/dist/chunk-8bd8q5xw.js +359 -0
  138. package/dist/chunk-8bwqtasa.js +213 -0
  139. package/dist/chunk-8g5pe1gr.js +37 -0
  140. package/dist/chunk-8g747a8x.js +26 -0
  141. package/dist/chunk-8h6sdj66.js +447 -0
  142. package/dist/chunk-8mm8b6dd.js +19 -0
  143. package/dist/chunk-8ndwn6st.js +120 -0
  144. package/dist/chunk-8pn8tvgg.js +637 -0
  145. package/dist/chunk-8tnn9kcb.js +131 -0
  146. package/dist/chunk-8tnsngw2.js +31 -0
  147. package/dist/chunk-8x5w267y.js +112 -0
  148. package/dist/chunk-8y12jxg8.js +10 -0
  149. package/dist/chunk-8ymf4e6z.js +48 -0
  150. package/dist/chunk-90mt0m1w.js +102 -0
  151. package/dist/chunk-90wp6wez.js +10510 -0
  152. package/dist/chunk-91ew1d6f.js +2689 -0
  153. package/dist/chunk-97jsc1kn.js +231 -0
  154. package/dist/chunk-993pnm45.js +4521 -0
  155. package/dist/chunk-9a0rsdre.js +46 -0
  156. package/dist/chunk-9d7fmqkw.js +41 -0
  157. package/dist/chunk-9dgaq0g4.js +667 -0
  158. package/dist/chunk-9f52phb8.js +138 -0
  159. package/dist/chunk-9fbpqghc.js +105 -0
  160. package/dist/chunk-9hzxd5q3.js +122 -0
  161. package/dist/chunk-9kyrssch.js +28 -0
  162. package/dist/chunk-9q93n4w6.js +308 -0
  163. package/dist/chunk-9s0xs06y.js +581 -0
  164. package/dist/chunk-9x5zgy22.js +12 -0
  165. package/dist/chunk-9zdcb9jy.js +105 -0
  166. package/dist/chunk-a136cvvz.js +27 -0
  167. package/dist/chunk-a4psxnr1.js +224 -0
  168. package/dist/chunk-a4twdmhf.js +45 -0
  169. package/dist/chunk-a7rhvq9b.js +106 -0
  170. package/dist/chunk-a8ejc632.js +3094 -0
  171. package/dist/chunk-a9vdeb6y.js +258 -0
  172. package/dist/chunk-a9zh40sj.js +48 -0
  173. package/dist/chunk-aawg48hh.js +4102 -0
  174. package/dist/chunk-ad2f3890.js +65 -0
  175. package/dist/chunk-ae7ar1jk.js +105 -0
  176. package/dist/chunk-ak3hdbe4.js +234 -0
  177. package/dist/chunk-as4e9g8f.js +298 -0
  178. package/dist/chunk-ase86y73.js +15 -0
  179. package/dist/chunk-awb4vc41.js +69 -0
  180. package/dist/chunk-b4bep0aq.js +5041 -0
  181. package/dist/chunk-b4wg70y1.js +54 -0
  182. package/dist/chunk-b81hd3m6.js +32 -0
  183. package/dist/chunk-b9knmzt0.js +106 -0
  184. package/dist/chunk-besmz4ym.js +32 -0
  185. package/dist/chunk-bgpkemkg.js +65 -0
  186. package/dist/chunk-bj8x29tz.js +54 -0
  187. package/dist/chunk-bkqsnwrq.js +239 -0
  188. package/dist/chunk-bnf662he.js +359 -0
  189. package/dist/chunk-bq00fcsd.js +165 -0
  190. package/dist/chunk-brz2c4cq.js +275 -0
  191. package/dist/chunk-bsa118r4.js +502 -0
  192. package/dist/chunk-bsengrbt.js +2737 -0
  193. package/dist/chunk-bt64sq5y.js +19 -0
  194. package/dist/chunk-bxcfz5gy.js +56 -0
  195. package/dist/chunk-bxs2a71m.js +213 -0
  196. package/dist/chunk-byv2p9hn.js +397 -0
  197. package/dist/chunk-c03am3es.js +29 -0
  198. package/dist/chunk-c2ahb7yg.js +105 -0
  199. package/dist/chunk-c2qm0t6p.js +111 -0
  200. package/dist/chunk-c42h9gzx.js +71 -0
  201. package/dist/chunk-c47xbxqw.js +38 -0
  202. package/dist/chunk-c5vkve4j.js +68 -0
  203. package/dist/chunk-c6sjhj89.js +1284 -0
  204. package/dist/chunk-ca147npg.js +27 -0
  205. package/dist/chunk-caxx597g.js +71 -0
  206. package/dist/chunk-cbrt5vsb.js +31 -0
  207. package/dist/chunk-ce0z23ct.js +443 -0
  208. package/dist/chunk-cefsp8h1.js +155 -0
  209. package/dist/chunk-cfv996bs.js +22 -0
  210. package/dist/chunk-cgfdkzhb.js +12 -0
  211. package/dist/chunk-chsyvavm.js +3435 -0
  212. package/dist/chunk-cmsknj6n.js +28228 -0
  213. package/dist/chunk-cn8bkmvj.js +264 -0
  214. package/dist/chunk-crmjpsqe.js +68 -0
  215. package/dist/chunk-cthpw4pj.js +849 -0
  216. package/dist/chunk-cwy9nj4y.js +134 -0
  217. package/dist/chunk-cyagce56.js +155 -0
  218. package/dist/chunk-cynewytp.js +227 -0
  219. package/dist/chunk-cznf6k4g.js +46 -0
  220. package/dist/chunk-d0954t9j.js +267 -0
  221. package/dist/chunk-d1qhftze.js +118 -0
  222. package/dist/chunk-d4mdda98.js +94 -0
  223. package/dist/chunk-d4rnqevg.js +41 -0
  224. package/dist/chunk-d7886r6a.js +13870 -0
  225. package/dist/chunk-dd1qvamk.js +678 -0
  226. package/dist/chunk-dg4je8qj.js +183 -0
  227. package/dist/chunk-dggvswz1.js +104 -0
  228. package/dist/chunk-dgqrcy74.js +48 -0
  229. package/dist/chunk-dm3n2qgd.js +24 -0
  230. package/dist/chunk-dnh7jtpb.js +37 -0
  231. package/dist/chunk-dsenyfax.js +105 -0
  232. package/dist/chunk-dtf0a7rr.js +655 -0
  233. package/dist/chunk-dxdb7bs1.js +60 -0
  234. package/dist/chunk-e0pth8g7.js +79 -0
  235. package/dist/chunk-e36y0q82.js +109 -0
  236. package/dist/chunk-ef55cwrv.js +267 -0
  237. package/dist/chunk-efh644hv.js +915 -0
  238. package/dist/chunk-ehtwnxpg.js +1591 -0
  239. package/dist/chunk-ejahyhd8.js +120 -0
  240. package/dist/chunk-ejk1bpzz.js +472 -0
  241. package/dist/chunk-emef71ea.js +202 -0
  242. package/dist/chunk-en7v028t.js +333 -0
  243. package/dist/chunk-eqp1rfft.js +17 -0
  244. package/dist/chunk-ewadzrm8.js +103 -0
  245. package/dist/chunk-exh7z6tv.js +132 -0
  246. package/dist/chunk-f0npbgyf.js +340 -0
  247. package/dist/chunk-f2qkc8ce.js +229 -0
  248. package/dist/chunk-f49sb3q7.js +40 -0
  249. package/dist/chunk-f5ma3nh5.js +3436 -0
  250. package/dist/chunk-fbv4apne.js +51 -0
  251. package/dist/chunk-fday7sfg.js +269 -0
  252. package/dist/chunk-feyzykye.js +10 -0
  253. package/dist/chunk-fgqwr70t.js +241 -0
  254. package/dist/chunk-fhy7zs1w.js +943 -0
  255. package/dist/chunk-fmw3f68k.js +432 -0
  256. package/dist/chunk-fmwqvpqm.js +506 -0
  257. package/dist/chunk-fn1apgre.js +66 -0
  258. package/dist/chunk-fpy4nam9.js +21933 -0
  259. package/dist/chunk-fqy0erkw.js +908 -0
  260. package/dist/chunk-ftqwza3a.js +43 -0
  261. package/dist/chunk-fyc5fepv.js +10 -0
  262. package/dist/chunk-fz0ch109.js +329 -0
  263. package/dist/chunk-fzhn8z8j.js +253 -0
  264. package/dist/chunk-g12brv6y.js +321 -0
  265. package/dist/chunk-g338npwr.js +1061 -0
  266. package/dist/chunk-g5tpks28.js +795 -0
  267. package/dist/chunk-g63tgj4f.js +58 -0
  268. package/dist/chunk-g827r0mk.js +266 -0
  269. package/dist/chunk-g8wzsxgc.js +2534 -0
  270. package/dist/chunk-gey7mwcw.js +36 -0
  271. package/dist/chunk-gghb9pks.js +120 -0
  272. package/dist/chunk-grdpaf1p.js +606 -0
  273. package/dist/chunk-gx8016vp.js +125 -0
  274. package/dist/chunk-h0qngp9w.js +157 -0
  275. package/dist/chunk-h0rbjg6x.js +55 -0
  276. package/dist/chunk-h1mr3371.js +121 -0
  277. package/dist/chunk-h3xwdgpd.js +68 -0
  278. package/dist/chunk-h4b85amj.js +2331 -0
  279. package/dist/chunk-h6d137aa.js +20 -0
  280. package/dist/chunk-h9n7z00d.js +95 -0
  281. package/dist/chunk-hakdhagh.js +16606 -0
  282. package/dist/chunk-hd8531ec.js +685 -0
  283. package/dist/chunk-heq3rn8t.js +33068 -0
  284. package/dist/chunk-hfvxc9fd.js +542 -0
  285. package/dist/chunk-hgpd0qmm.js +371 -0
  286. package/dist/chunk-hh7cmy4k.js +20 -0
  287. package/dist/chunk-hhjs87wh.js +1407 -0
  288. package/dist/chunk-hjtvdvgj.js +208 -0
  289. package/dist/chunk-hk9xz7gk.js +118 -0
  290. package/dist/chunk-hknbjky3.js +160798 -0
  291. package/dist/chunk-htsbqyf9.js +338 -0
  292. package/dist/chunk-htx7jmxk.js +78 -0
  293. package/dist/chunk-hzhe8ygc.js +547 -0
  294. package/dist/chunk-j2k4p94p.js +55 -0
  295. package/dist/chunk-j3a4p81y.js +184 -0
  296. package/dist/chunk-j46rb9m9.js +544 -0
  297. package/dist/chunk-j5bth84e.js +97 -0
  298. package/dist/chunk-j64ga6ta.js +8035 -0
  299. package/dist/chunk-j6jh72hw.js +140 -0
  300. package/dist/chunk-j9gxwbe3.js +349 -0
  301. package/dist/chunk-jaaxk89e.js +113 -0
  302. package/dist/chunk-jd32zbps.js +15 -0
  303. package/dist/chunk-jdgeec04.js +4249 -0
  304. package/dist/chunk-jk826edv.js +174 -0
  305. package/dist/chunk-jnhkref0.js +30 -0
  306. package/dist/chunk-jsx72hep.js +208 -0
  307. package/dist/chunk-jx817w05.js +11 -0
  308. package/dist/chunk-jzmz18nn.js +65 -0
  309. package/dist/chunk-k0p9w03v.js +4957 -0
  310. package/dist/chunk-k3s4yk22.js +477 -0
  311. package/dist/chunk-kfd89dsd.js +21 -0
  312. package/dist/chunk-kgfz4522.js +126 -0
  313. package/dist/chunk-kn6zg6bd.js +524 -0
  314. package/dist/chunk-kp9vkzj6.js +120 -0
  315. package/dist/chunk-kraf793v.js +118 -0
  316. package/dist/chunk-kw0r30h3.js +208 -0
  317. package/dist/chunk-kwekc97v.js +18 -0
  318. package/dist/chunk-m2bcpk8j.js +30 -0
  319. package/dist/chunk-m2kp5f7p.js +4389 -0
  320. package/dist/chunk-m74w3187.js +164 -0
  321. package/dist/chunk-m88q4jmb.js +61 -0
  322. package/dist/chunk-man6wb4n.js +1456 -0
  323. package/dist/chunk-mdk3xgya.js +42 -0
  324. package/dist/chunk-mf4g439x.js +82 -0
  325. package/dist/chunk-mg8g0xqs.js +71 -0
  326. package/dist/chunk-mkwzrqvf.js +38 -0
  327. package/dist/chunk-mn61mk4v.js +351 -0
  328. package/dist/chunk-ms09sxcj.js +908 -0
  329. package/dist/chunk-mtn1anwe.js +2351 -0
  330. package/dist/chunk-mv0zm0qj.js +65 -0
  331. package/dist/chunk-mx28h61f.js +1147 -0
  332. package/dist/chunk-mxbf8ajn.js +1067 -0
  333. package/dist/chunk-n0qaeaa5.js +256 -0
  334. package/dist/chunk-n34z5cw8.js +74 -0
  335. package/dist/chunk-n55ehz77.js +120 -0
  336. package/dist/chunk-n7ttdtk0.js +641 -0
  337. package/dist/chunk-n9ktjngj.js +336 -0
  338. package/dist/chunk-nb2ntesh.js +149 -0
  339. package/dist/chunk-netzwgv1.js +154 -0
  340. package/dist/chunk-nh3cd07f.js +14358 -0
  341. package/dist/chunk-nka1g8f4.js +773 -0
  342. package/dist/chunk-nm97cw83.js +458 -0
  343. package/dist/chunk-nq0fxyxh.js +752 -0
  344. package/dist/chunk-nt837qt9.js +21 -0
  345. package/dist/chunk-nx87c0vw.js +250 -0
  346. package/dist/chunk-nxw6y6xm.js +862 -0
  347. package/dist/chunk-nzt717xg.js +32 -0
  348. package/dist/chunk-p2816w9z.js +1486 -0
  349. package/dist/chunk-p2d5nh3g.js +342 -0
  350. package/dist/chunk-p9cdykwf.js +72 -0
  351. package/dist/chunk-paxw1ryd.js +227 -0
  352. package/dist/chunk-ph5g4d1j.js +109 -0
  353. package/dist/chunk-pp42p8y3.js +574 -0
  354. package/dist/chunk-ppdn71n4.js +400 -0
  355. package/dist/chunk-ppwjyveh.js +8 -0
  356. package/dist/chunk-ps49ymvj.js +43 -0
  357. package/dist/chunk-pshjyzq4.js +17656 -0
  358. package/dist/chunk-pw8nf9rt.js +126 -0
  359. package/dist/chunk-pwwa7s62.js +11 -0
  360. package/dist/chunk-py3zxq5j.js +129 -0
  361. package/dist/chunk-pyz1qswz.js +300 -0
  362. package/dist/chunk-q50q8mc5.js +157 -0
  363. package/dist/chunk-q7tpyeb3.js +39 -0
  364. package/dist/chunk-q82r31er.js +151 -0
  365. package/dist/chunk-qajrkk97.js +298 -0
  366. package/dist/chunk-qcpxnyeh.js +110 -0
  367. package/dist/chunk-qeabchwr.js +132 -0
  368. package/dist/chunk-qm7nbd10.js +755 -0
  369. package/dist/chunk-qm8j7kxr.js +280 -0
  370. package/dist/chunk-qmwgg5zy.js +136 -0
  371. package/dist/chunk-qnfx3qtx.js +617 -0
  372. package/dist/chunk-qp2qdcda.js +100 -0
  373. package/dist/chunk-qphaajd7.js +305 -0
  374. package/dist/chunk-qt21xxgm.js +419 -0
  375. package/dist/chunk-qy2z2p0b.js +122 -0
  376. package/dist/chunk-qyz8q0dj.js +689 -0
  377. package/dist/chunk-qz2x630m.js +49145 -0
  378. package/dist/chunk-qzq5n1yn.js +76 -0
  379. package/dist/chunk-r0ya57xw.js +170 -0
  380. package/dist/chunk-r7j395t6.js +122 -0
  381. package/dist/chunk-r7trcrs7.js +62 -0
  382. package/dist/chunk-re4yh70t.js +1095 -0
  383. package/dist/chunk-rhte1r8g.js +272 -0
  384. package/dist/chunk-rhw4ayb1.js +6851 -0
  385. package/dist/chunk-rn0v1hk8.js +34 -0
  386. package/dist/chunk-rphakhme.js +281 -0
  387. package/dist/chunk-rrtzz2pv.js +32 -0
  388. package/dist/chunk-rtnjk8ge.js +726 -0
  389. package/dist/chunk-rwhswkma.js +87 -0
  390. package/dist/chunk-rxd4kn2g.js +308 -0
  391. package/dist/chunk-s083x8ry.js +2840 -0
  392. package/dist/chunk-s16sn02n.js +365 -0
  393. package/dist/chunk-s1s8qfdh.js +182 -0
  394. package/dist/chunk-s2bwz69v.js +473 -0
  395. package/dist/chunk-s3pzvdss.js +50 -0
  396. package/dist/chunk-s9y6t0mt.js +291 -0
  397. package/dist/chunk-sd36yzx8.js +954 -0
  398. package/dist/chunk-se8xzw8h.js +87 -0
  399. package/dist/chunk-sg66v252.js +1648 -0
  400. package/dist/chunk-sg7gf3hj.js +1585 -0
  401. package/dist/chunk-spx24x6j.js +98 -0
  402. package/dist/chunk-sybxpy18.js +73 -0
  403. package/dist/chunk-szj5wvdy.js +28 -0
  404. package/dist/chunk-t0gb304x.js +182 -0
  405. package/dist/chunk-t3fr4skc.js +165 -0
  406. package/dist/chunk-t58wfamm.js +5368 -0
  407. package/dist/chunk-t6s2kkm3.js +104 -0
  408. package/dist/chunk-t8hv0x81.js +116 -0
  409. package/dist/chunk-tezak8rx.js +6157 -0
  410. package/dist/chunk-th5y3hj5.js +189 -0
  411. package/dist/chunk-tj0d3870.js +180 -0
  412. package/dist/chunk-tjgsawpx.js +40 -0
  413. package/dist/chunk-ts2p6bv1.js +224 -0
  414. package/dist/chunk-ttk5dzz8.js +25 -0
  415. package/dist/chunk-tv9pcdnz.js +51 -0
  416. package/dist/chunk-ty99rgvw.js +122 -0
  417. package/dist/chunk-tzgp8av2.js +61 -0
  418. package/dist/chunk-v1kzp02e.js +785 -0
  419. package/dist/chunk-v2c9dq7t.js +275 -0
  420. package/dist/chunk-v3aq3heg.js +620 -0
  421. package/dist/chunk-v78fj8by.js +145 -0
  422. package/dist/chunk-v9smspw2.js +4301 -0
  423. package/dist/chunk-var1et7e.js +66 -0
  424. package/dist/chunk-vchrkvet.js +120 -0
  425. package/dist/chunk-vest0y6x.js +3830 -0
  426. package/dist/chunk-vf5sd1nq.js +12 -0
  427. package/dist/chunk-vf612n57.js +472 -0
  428. package/dist/chunk-vgpy9md6.js +339 -0
  429. package/dist/chunk-vkzt82ry.js +644 -0
  430. package/dist/chunk-vsh80y0c.js +100 -0
  431. package/dist/chunk-vxkdxhyk.js +103 -0
  432. package/dist/chunk-vxt6ywm9.js +485 -0
  433. package/dist/chunk-vyjeh50y.js +2149 -0
  434. package/dist/chunk-vytdzvqs.js +1181 -0
  435. package/dist/chunk-w0qks2ja.js +1030 -0
  436. package/dist/chunk-wfz0qffj.js +3939 -0
  437. package/dist/chunk-wp1568nt.js +828 -0
  438. package/dist/chunk-wpckhx7b.js +66 -0
  439. package/dist/chunk-wpvkvwvc.js +41 -0
  440. package/dist/chunk-ws5d6qs4.js +655 -0
  441. package/dist/chunk-wsnxrrb5.js +986 -0
  442. package/dist/chunk-wyavftcj.js +103 -0
  443. package/dist/chunk-wybh0bvv.js +121 -0
  444. package/dist/chunk-wzpdet3m.js +843 -0
  445. package/dist/chunk-x2dp18yj.js +74 -0
  446. package/dist/chunk-x6r4v44b.js +8 -0
  447. package/dist/chunk-x7r5k0hf.js +423 -0
  448. package/dist/chunk-xahk20z8.js +877 -0
  449. package/dist/chunk-xajwdaxm.js +295 -0
  450. package/dist/chunk-xkt36p6r.js +61 -0
  451. package/dist/chunk-xnav6j8h.js +490 -0
  452. package/dist/chunk-xrj294jg.js +440 -0
  453. package/dist/chunk-xsq9ae7x.js +90 -0
  454. package/dist/chunk-xt9z9t7b.js +40 -0
  455. package/dist/chunk-xv3era3s.js +8 -0
  456. package/dist/chunk-y1784krc.js +19 -0
  457. package/dist/chunk-y289fz8y.js +116 -0
  458. package/dist/chunk-y3r7v9pq.js +336 -0
  459. package/dist/chunk-y98z50mm.js +158 -0
  460. package/dist/chunk-yhce3x0q.js +64 -0
  461. package/dist/chunk-yhhf6n9p.js +338 -0
  462. package/dist/chunk-ykr34msh.js +411 -0
  463. package/dist/chunk-yks9ggzn.js +103 -0
  464. package/dist/chunk-ym5r3jnk.js +2007 -0
  465. package/dist/chunk-ypa349qq.js +148 -0
  466. package/dist/chunk-yzx3mhfd.js +110 -0
  467. package/dist/chunk-z1bs6d7k.js +24 -0
  468. package/dist/chunk-z2dp53wn.js +17 -0
  469. package/dist/chunk-z3k0k30d.js +882 -0
  470. package/dist/chunk-z42cqdtf.js +107 -0
  471. package/dist/chunk-z7asrz6j.js +259 -0
  472. package/dist/chunk-za09fhhh.js +716 -0
  473. package/dist/chunk-zae0t3p4.js +252 -0
  474. package/dist/chunk-zbsw794g.js +259 -0
  475. package/dist/chunk-ze6zvkg6.js +22820 -0
  476. package/dist/chunk-zejm280k.js +39 -0
  477. package/dist/chunk-zk2wsm7d.js +15 -0
  478. package/dist/chunk-znf2b75k.js +113 -0
  479. package/dist/chunk-zqpnvsdz.js +24 -0
  480. package/dist/chunk-zs2gdkj5.js +433 -0
  481. package/dist/chunk-zseb1639.js +37 -0
  482. package/dist/chunk-zsgha506.js +63 -0
  483. package/dist/chunk-zvsfgmq8.js +146 -0
  484. package/dist/chunk-zw5xd7m9.js +160 -0
  485. package/dist/chunk-zzm33q8x.js +8 -0
  486. package/dist/cli.js +97 -0
  487. package/dist/download-ripgrep.js +24821 -0
  488. package/dist/vendor/audio-capture/arm64-darwin/audio-capture.node +0 -0
  489. package/dist/vendor/audio-capture/arm64-linux/audio-capture.node +0 -0
  490. package/dist/vendor/audio-capture/arm64-win32/audio-capture.node +0 -0
  491. package/dist/vendor/audio-capture/x64-darwin/audio-capture.node +0 -0
  492. package/dist/vendor/audio-capture/x64-linux/audio-capture.node +0 -0
  493. package/dist/vendor/audio-capture/x64-win32/audio-capture.node +0 -0
  494. package/package.json +178 -0
  495. package/scripts/download-ripgrep.ts +335 -0
  496. package/scripts/postinstall.cjs +319 -0
@@ -0,0 +1,1568 @@
1
+ // @bun
2
+ import {
3
+ FlushGate,
4
+ buildCCRv2SdkUrl,
5
+ buildSdkUrl,
6
+ checkEnvLessBridgeMinVersion,
7
+ createV1ReplTransport,
8
+ createV2ReplTransport,
9
+ decodeWorkSecret,
10
+ sameSessionId
11
+ } from "./chunk-vgpy9md6.js";
12
+ import {
13
+ DEFAULT_POLL_CONFIG,
14
+ HybridTransport,
15
+ getPollIntervalConfig
16
+ } from "./chunk-1mn6r4y2.js";
17
+ import"./chunk-efh644hv.js";
18
+ import {
19
+ BoundedUUIDSet,
20
+ extractTitleText,
21
+ handleIngressMessage,
22
+ handleServerControlRequest,
23
+ isEligibleBridgeMessage,
24
+ makeResultMessage
25
+ } from "./chunk-7xmw2tcz.js";
26
+ import"./chunk-nt837qt9.js";
27
+ import"./chunk-2rj0dnps.js";
28
+ import {
29
+ init_mappers,
30
+ toSDKMessages
31
+ } from "./chunk-f2qkc8ce.js";
32
+ import {
33
+ archiveBridgeSession,
34
+ createBridgeSession,
35
+ init_createSession,
36
+ updateBridgeSessionTitle
37
+ } from "./chunk-nx87c0vw.js";
38
+ import {
39
+ getBridgeAccessToken,
40
+ getBridgeBaseUrl,
41
+ getBridgeTokenOverride,
42
+ init_bridgeConfig
43
+ } from "./chunk-nzt717xg.js";
44
+ import {
45
+ extractConversationText,
46
+ generateSessionTitle,
47
+ init_sessionTitle
48
+ } from "./chunk-1cx0fd76.js";
49
+ import {
50
+ checkBridgeMinVersion,
51
+ init_bridgeEnabled,
52
+ isBridgeEnabledBlocking,
53
+ isCseShimEnabled,
54
+ isEnvLessBridgeEnabled
55
+ } from "./chunk-f49sb3q7.js";
56
+ import {
57
+ BridgeFatalError,
58
+ clearBridgeDebugHandle,
59
+ createBridgeApiClient,
60
+ generateShortWordSlug,
61
+ getContentText,
62
+ getCurrentSessionTitle,
63
+ getMessagesAfterCompactBoundary,
64
+ init_bridgeApi,
65
+ init_bridgeDebug,
66
+ init_concurrentSessions,
67
+ init_messages1 as init_messages,
68
+ init_policyLimits,
69
+ init_sessionStorage,
70
+ init_words,
71
+ injectBridgeFault,
72
+ isExpiredErrorType,
73
+ isPolicyAllowed,
74
+ isSuppressible403,
75
+ isSyntheticMessage,
76
+ registerBridgeDebugHandle,
77
+ updateSessionBridgeId,
78
+ validateBridgeId,
79
+ waitForPolicyLimitsToLoad,
80
+ wrapApiForFaultInjection
81
+ } from "./chunk-hknbjky3.js";
82
+ import {
83
+ init_sessionIngressAuth,
84
+ updateSessionIngressAuthToken
85
+ } from "./chunk-a4psxnr1.js";
86
+ import"./chunk-613f6fbv.js";
87
+ import"./chunk-zejm280k.js";
88
+ import {
89
+ getTrustedDeviceToken,
90
+ init_trustedDevice
91
+ } from "./chunk-57qz90z8.js";
92
+ import"./chunk-4nspekjp.js";
93
+ import"./chunk-heq3rn8t.js";
94
+ import"./chunk-var1et7e.js";
95
+ import"./chunk-e0pth8g7.js";
96
+ import"./chunk-ws5d6qs4.js";
97
+ import"./chunk-bxcfz5gy.js";
98
+ import"./chunk-wp1568nt.js";
99
+ import"./chunk-2gzv8nrw.js";
100
+ import"./chunk-ehtwnxpg.js";
101
+ import"./chunk-cgfdkzhb.js";
102
+ import"./chunk-8h6sdj66.js";
103
+ import"./chunk-75zk7zr1.js";
104
+ import"./chunk-j5bth84e.js";
105
+ import"./chunk-qm7nbd10.js";
106
+ import {
107
+ describeAxiosError,
108
+ extractHttpStatus,
109
+ init_debugUtils,
110
+ init_sessionIdCompat,
111
+ logBridgeSkip,
112
+ setCseShimGate,
113
+ toCompatSessionId,
114
+ toInfraSessionId
115
+ } from "./chunk-5pevjsyw.js";
116
+ import"./chunk-xnav6j8h.js";
117
+ import"./chunk-ps49ymvj.js";
118
+ import"./chunk-zk2wsm7d.js";
119
+ import"./chunk-2t0xa4dt.js";
120
+ import"./chunk-bgpkemkg.js";
121
+ import"./chunk-rrtzz2pv.js";
122
+ import"./chunk-zsgha506.js";
123
+ import"./chunk-4jm600zv.js";
124
+ import"./chunk-xkt36p6r.js";
125
+ import"./chunk-2ekjxh7d.js";
126
+ import"./chunk-85tag8nv.js";
127
+ import"./chunk-mx28h61f.js";
128
+ import"./chunk-kraf793v.js";
129
+ import"./chunk-bj8x29tz.js";
130
+ import"./chunk-zae0t3p4.js";
131
+ import"./chunk-t58wfamm.js";
132
+ import"./chunk-chsyvavm.js";
133
+ import"./chunk-6mpw9h55.js";
134
+ import {
135
+ checkAndRefreshOAuthTokenIfNeeded,
136
+ getClaudeAIOAuthTokens,
137
+ getFeatureValue_CACHED_WITH_REFRESH,
138
+ getGlobalConfig,
139
+ getOrganizationUUID,
140
+ handleOAuth401Error,
141
+ init_auth,
142
+ init_client,
143
+ init_config1 as init_config,
144
+ init_growthbook,
145
+ saveGlobalConfig
146
+ } from "./chunk-7b6bg1r4.js";
147
+ import"./chunk-sg66v252.js";
148
+ import"./chunk-8bwqtasa.js";
149
+ import"./chunk-j9gxwbe3.js";
150
+ import"./chunk-1cwdhk7a.js";
151
+ import"./chunk-rtnjk8ge.js";
152
+ import"./chunk-64c1avct.js";
153
+ import {
154
+ init_sleep,
155
+ sleep
156
+ } from "./chunk-8g5pe1gr.js";
157
+ import"./chunk-gx8016vp.js";
158
+ import"./chunk-4cp6193g.js";
159
+ import"./chunk-8g747a8x.js";
160
+ import"./chunk-d7886r6a.js";
161
+ import"./chunk-f5ma3nh5.js";
162
+ import"./chunk-qz2x630m.js";
163
+ import"./chunk-r7j395t6.js";
164
+ import"./chunk-tv9pcdnz.js";
165
+ import"./chunk-3c25bcsw.js";
166
+ import"./chunk-n9ktjngj.js";
167
+ import"./chunk-q82r31er.js";
168
+ import"./chunk-p2816w9z.js";
169
+ import"./chunk-v9smspw2.js";
170
+ import"./chunk-v1kzp02e.js";
171
+ import"./chunk-64hks9ax.js";
172
+ import"./chunk-crmjpsqe.js";
173
+ import"./chunk-cmsknj6n.js";
174
+ import"./chunk-g338npwr.js";
175
+ import {
176
+ init_analytics,
177
+ logEvent
178
+ } from "./chunk-h0rbjg6x.js";
179
+ import"./chunk-0vkfrmqm.js";
180
+ import"./chunk-0xjaqda8.js";
181
+ import"./chunk-h1mr3371.js";
182
+ import {
183
+ getBranch,
184
+ getRemoteUrl,
185
+ init_diagLogs,
186
+ init_git,
187
+ logForDiagnosticsNoPII
188
+ } from "./chunk-36b2q5fg.js";
189
+ import"./chunk-a7rhvq9b.js";
190
+ import"./chunk-qnfx3qtx.js";
191
+ import"./chunk-m74w3187.js";
192
+ import"./chunk-b81hd3m6.js";
193
+ import {
194
+ init_displayTags,
195
+ stripDisplayTagsAllowEmpty
196
+ } from "./chunk-y3r7v9pq.js";
197
+ import"./chunk-8tnsngw2.js";
198
+ import"./chunk-awb4vc41.js";
199
+ import"./chunk-cbrt5vsb.js";
200
+ import"./chunk-5z28bqne.js";
201
+ import"./chunk-qajrkk97.js";
202
+ import {
203
+ errorMessage,
204
+ init_cleanupRegistry,
205
+ init_debug,
206
+ init_errors,
207
+ logForDebugging,
208
+ registerCleanup
209
+ } from "./chunk-404qm8xt.js";
210
+ import"./chunk-fbv4apne.js";
211
+ import {
212
+ init_envUtils,
213
+ isEnvTruthy,
214
+ isInProtectedNamespace
215
+ } from "./chunk-jaaxk89e.js";
216
+ import {
217
+ getOriginalCwd,
218
+ getSessionId,
219
+ init_state
220
+ } from "./chunk-h4b85amj.js";
221
+ import"./chunk-07069jq1.js";
222
+ import"./chunk-vf612n57.js";
223
+ import"./chunk-d4mdda98.js";
224
+ import"./chunk-7wm5s02e.js";
225
+ import"./chunk-4g3v8y12.js";
226
+ import"./chunk-7739pg2c.js";
227
+ import"./chunk-nh3cd07f.js";
228
+ import"./chunk-8pn8tvgg.js";
229
+ import"./chunk-netzwgv1.js";
230
+ import {
231
+ __require
232
+ } from "./chunk-qp2qdcda.js";
233
+
234
+ // src/bridge/initReplBridge.ts
235
+ init_state();
236
+ init_growthbook();
237
+ init_client();
238
+ init_policyLimits();
239
+ init_auth();
240
+ init_config();
241
+ init_debug();
242
+ init_displayTags();
243
+ init_errors();
244
+ init_git();
245
+ init_mappers();
246
+ init_messages();
247
+ init_sessionStorage();
248
+ init_sessionTitle();
249
+ init_words();
250
+ init_bridgeConfig();
251
+ init_bridgeEnabled();
252
+ init_createSession();
253
+ init_debugUtils();
254
+ import { hostname } from "os";
255
+
256
+ // src/bridge/replBridge.ts
257
+ init_bridgeApi();
258
+ init_debug();
259
+ init_diagLogs();
260
+ init_analytics();
261
+ init_cleanupRegistry();
262
+ import { randomUUID } from "crypto";
263
+ init_sessionIdCompat();
264
+ init_concurrentSessions();
265
+ init_trustedDevice();
266
+ init_sessionIngressAuth();
267
+ init_envUtils();
268
+ init_bridgeApi();
269
+ init_debugUtils();
270
+
271
+ // src/bridge/capacityWake.ts
272
+ function createCapacityWake(outerSignal) {
273
+ let wakeController = new AbortController;
274
+ function wake() {
275
+ wakeController.abort();
276
+ wakeController = new AbortController;
277
+ }
278
+ function signal() {
279
+ const merged = new AbortController;
280
+ const abort = () => merged.abort();
281
+ if (outerSignal.aborted || wakeController.signal.aborted) {
282
+ merged.abort();
283
+ return { signal: merged.signal, cleanup: () => {} };
284
+ }
285
+ outerSignal.addEventListener("abort", abort, { once: true });
286
+ const capSig = wakeController.signal;
287
+ capSig.addEventListener("abort", abort, { once: true });
288
+ return {
289
+ signal: merged.signal,
290
+ cleanup: () => {
291
+ outerSignal.removeEventListener("abort", abort);
292
+ capSig.removeEventListener("abort", abort);
293
+ }
294
+ };
295
+ }
296
+ return { signal, wake };
297
+ }
298
+
299
+ // src/bridge/replBridge.ts
300
+ init_errors();
301
+ init_sleep();
302
+ init_bridgeDebug();
303
+ var POLL_ERROR_INITIAL_DELAY_MS = 2000;
304
+ var POLL_ERROR_MAX_DELAY_MS = 60000;
305
+ var POLL_ERROR_GIVE_UP_MS = 15 * 60 * 1000;
306
+ var initSequence = 0;
307
+ async function initBridgeCore(params) {
308
+ const {
309
+ dir,
310
+ machineName,
311
+ branch,
312
+ gitRepoUrl,
313
+ title,
314
+ baseUrl,
315
+ sessionIngressUrl,
316
+ workerType,
317
+ getAccessToken,
318
+ createSession,
319
+ archiveSession,
320
+ getCurrentTitle = () => title,
321
+ toSDKMessages: toSDKMessages2 = () => {
322
+ throw new Error("BridgeCoreParams.toSDKMessages not provided. Pass it if you use writeMessages() or initialMessages \u2014 daemon callers that only use writeSdkMessages() never hit this path.");
323
+ },
324
+ onAuth401,
325
+ getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG,
326
+ initialHistoryCap = 200,
327
+ initialMessages,
328
+ previouslyFlushedUUIDs,
329
+ onInboundMessage,
330
+ onPermissionResponse,
331
+ onInterrupt,
332
+ onSetModel,
333
+ onSetMaxThinkingTokens,
334
+ onSetPermissionMode,
335
+ onStateChange,
336
+ onUserMessage,
337
+ perpetual,
338
+ initialSSESequenceNum = 0
339
+ } = params;
340
+ const seq = ++initSequence;
341
+ const { writeBridgePointer, clearBridgePointer, readBridgePointer } = await import("./chunk-nb2ntesh.js");
342
+ const rawPrior = perpetual ? await readBridgePointer(dir) : null;
343
+ const prior = rawPrior?.source === "repl" ? rawPrior : null;
344
+ logForDebugging(`[bridge:repl] initBridgeCore #${seq} starting (initialMessages=${initialMessages?.length ?? 0}${prior ? ` perpetual prior=env:${prior.environmentId}` : ""})`);
345
+ const rawApi = createBridgeApiClient({
346
+ baseUrl,
347
+ getAccessToken,
348
+ runnerVersion: "2.1.888",
349
+ onDebug: logForDebugging,
350
+ onAuth401,
351
+ getTrustedDeviceToken
352
+ });
353
+ const api = process.env.USER_TYPE === "ant" ? wrapApiForFaultInjection(rawApi) : rawApi;
354
+ const bridgeConfig = {
355
+ dir,
356
+ machineName,
357
+ branch,
358
+ gitRepoUrl,
359
+ maxSessions: 1,
360
+ spawnMode: "single-session",
361
+ verbose: false,
362
+ sandbox: false,
363
+ bridgeId: randomUUID(),
364
+ workerType,
365
+ environmentId: randomUUID(),
366
+ reuseEnvironmentId: prior?.environmentId,
367
+ apiBaseUrl: baseUrl,
368
+ sessionIngressUrl
369
+ };
370
+ let environmentId;
371
+ let environmentSecret;
372
+ try {
373
+ const reg = await api.registerBridgeEnvironment(bridgeConfig);
374
+ environmentId = reg.environment_id;
375
+ environmentSecret = reg.environment_secret;
376
+ } catch (err) {
377
+ logBridgeSkip("registration_failed", `[bridge:repl] Environment registration failed: ${errorMessage(err)}`);
378
+ if (prior) {
379
+ await clearBridgePointer(dir);
380
+ }
381
+ onStateChange?.("failed", errorMessage(err));
382
+ return null;
383
+ }
384
+ logForDebugging(`[bridge:repl] Environment registered: ${environmentId}`);
385
+ logForDiagnosticsNoPII("info", "bridge_repl_env_registered");
386
+ logEvent("tengu_bridge_repl_env_registered", {});
387
+ async function tryReconnectInPlace(requestedEnvId, sessionId) {
388
+ if (environmentId !== requestedEnvId) {
389
+ logForDebugging(`[bridge:repl] Env mismatch (requested ${requestedEnvId}, got ${environmentId}) \u2014 cannot reconnect in place`);
390
+ return false;
391
+ }
392
+ const infraId = toInfraSessionId(sessionId);
393
+ const candidates = infraId === sessionId ? [sessionId] : [sessionId, infraId];
394
+ for (const id of candidates) {
395
+ try {
396
+ await api.reconnectSession(environmentId, id);
397
+ logForDebugging(`[bridge:repl] Reconnected session ${id} in place on env ${environmentId}`);
398
+ return true;
399
+ } catch (err) {
400
+ logForDebugging(`[bridge:repl] reconnectSession(${id}) failed: ${errorMessage(err)}`);
401
+ }
402
+ }
403
+ logForDebugging("[bridge:repl] reconnectSession exhausted \u2014 falling through to fresh session");
404
+ return false;
405
+ }
406
+ const reusedPriorSession = prior ? await tryReconnectInPlace(prior.environmentId, prior.sessionId) : false;
407
+ if (prior && !reusedPriorSession) {
408
+ await clearBridgePointer(dir);
409
+ }
410
+ let currentSessionId;
411
+ if (reusedPriorSession && prior) {
412
+ currentSessionId = prior.sessionId;
413
+ logForDebugging(`[bridge:repl] Perpetual session reused: ${currentSessionId}`);
414
+ if (initialMessages && previouslyFlushedUUIDs) {
415
+ for (const msg of initialMessages) {
416
+ previouslyFlushedUUIDs.add(msg.uuid);
417
+ }
418
+ }
419
+ } else {
420
+ const createdSessionId = await createSession({
421
+ environmentId,
422
+ title,
423
+ gitRepoUrl,
424
+ branch,
425
+ signal: AbortSignal.timeout(15000)
426
+ });
427
+ if (!createdSessionId) {
428
+ logForDebugging("[bridge:repl] Session creation failed, deregistering environment");
429
+ logEvent("tengu_bridge_repl_session_failed", {});
430
+ await api.deregisterEnvironment(environmentId).catch(() => {});
431
+ onStateChange?.("failed", "Session creation failed");
432
+ return null;
433
+ }
434
+ currentSessionId = createdSessionId;
435
+ logForDebugging(`[bridge:repl] Session created: ${currentSessionId}`);
436
+ }
437
+ await writeBridgePointer(dir, {
438
+ sessionId: currentSessionId,
439
+ environmentId,
440
+ source: "repl"
441
+ });
442
+ logForDiagnosticsNoPII("info", "bridge_repl_session_created");
443
+ logEvent("tengu_bridge_repl_started", {
444
+ has_initial_messages: !!(initialMessages && initialMessages.length > 0),
445
+ inProtectedNamespace: isInProtectedNamespace()
446
+ });
447
+ const initialMessageUUIDs = new Set;
448
+ if (initialMessages) {
449
+ for (const msg of initialMessages) {
450
+ initialMessageUUIDs.add(msg.uuid);
451
+ }
452
+ }
453
+ const recentPostedUUIDs = new BoundedUUIDSet(2000);
454
+ for (const uuid of initialMessageUUIDs) {
455
+ recentPostedUUIDs.add(uuid);
456
+ }
457
+ const recentInboundUUIDs = new BoundedUUIDSet(2000);
458
+ const pollController = new AbortController;
459
+ let transport = null;
460
+ let v2Generation = 0;
461
+ let lastTransportSequenceNum = reusedPriorSession ? initialSSESequenceNum : 0;
462
+ let currentWorkId = null;
463
+ let currentIngressToken = null;
464
+ const capacityWake = createCapacityWake(pollController.signal);
465
+ const wakePollLoop = capacityWake.wake;
466
+ const capacitySignal = capacityWake.signal;
467
+ const flushGate = new FlushGate;
468
+ let userMessageCallbackDone = !onUserMessage;
469
+ const MAX_ENVIRONMENT_RECREATIONS = 3;
470
+ let environmentRecreations = 0;
471
+ let reconnectPromise = null;
472
+ async function reconnectEnvironmentWithSession() {
473
+ if (reconnectPromise) {
474
+ return reconnectPromise;
475
+ }
476
+ reconnectPromise = doReconnect();
477
+ try {
478
+ return await reconnectPromise;
479
+ } finally {
480
+ reconnectPromise = null;
481
+ }
482
+ }
483
+ async function doReconnect() {
484
+ environmentRecreations++;
485
+ v2Generation++;
486
+ logForDebugging(`[bridge:repl] Reconnecting after env lost (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`);
487
+ if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) {
488
+ logForDebugging(`[bridge:repl] Environment reconnect limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`);
489
+ return false;
490
+ }
491
+ if (transport) {
492
+ const seq2 = transport.getLastSequenceNum();
493
+ if (seq2 > lastTransportSequenceNum) {
494
+ lastTransportSequenceNum = seq2;
495
+ }
496
+ transport.close();
497
+ transport = null;
498
+ }
499
+ wakePollLoop();
500
+ flushGate.drop();
501
+ if (currentWorkId) {
502
+ const workIdBeingCleared = currentWorkId;
503
+ await api.stopWork(environmentId, workIdBeingCleared, false).catch(() => {});
504
+ if (currentWorkId !== workIdBeingCleared) {
505
+ logForDebugging("[bridge:repl] Poll loop recovered during stopWork await \u2014 deferring to it");
506
+ environmentRecreations = 0;
507
+ return true;
508
+ }
509
+ currentWorkId = null;
510
+ currentIngressToken = null;
511
+ }
512
+ if (pollController.signal.aborted) {
513
+ logForDebugging("[bridge:repl] Reconnect aborted by teardown");
514
+ return false;
515
+ }
516
+ const requestedEnvId = environmentId;
517
+ bridgeConfig.reuseEnvironmentId = requestedEnvId;
518
+ try {
519
+ const reg = await api.registerBridgeEnvironment(bridgeConfig);
520
+ environmentId = reg.environment_id;
521
+ environmentSecret = reg.environment_secret;
522
+ } catch (err) {
523
+ bridgeConfig.reuseEnvironmentId = undefined;
524
+ logForDebugging(`[bridge:repl] Environment re-registration failed: ${errorMessage(err)}`);
525
+ return false;
526
+ }
527
+ bridgeConfig.reuseEnvironmentId = undefined;
528
+ logForDebugging(`[bridge:repl] Re-registered: requested=${requestedEnvId} got=${environmentId}`);
529
+ if (pollController.signal.aborted) {
530
+ logForDebugging("[bridge:repl] Reconnect aborted after env registration, cleaning up");
531
+ await api.deregisterEnvironment(environmentId).catch(() => {});
532
+ return false;
533
+ }
534
+ if (transport !== null) {
535
+ logForDebugging("[bridge:repl] Poll loop recovered during registerBridgeEnvironment await \u2014 deferring to it");
536
+ environmentRecreations = 0;
537
+ return true;
538
+ }
539
+ if (await tryReconnectInPlace(requestedEnvId, currentSessionId)) {
540
+ logEvent("tengu_bridge_repl_reconnected_in_place", {});
541
+ environmentRecreations = 0;
542
+ return true;
543
+ }
544
+ if (environmentId !== requestedEnvId) {
545
+ logEvent("tengu_bridge_repl_env_expired_fresh_session", {});
546
+ }
547
+ await archiveSession(currentSessionId);
548
+ if (pollController.signal.aborted) {
549
+ logForDebugging("[bridge:repl] Reconnect aborted after archive, cleaning up");
550
+ await api.deregisterEnvironment(environmentId).catch(() => {});
551
+ return false;
552
+ }
553
+ const currentTitle = getCurrentTitle();
554
+ const newSessionId = await createSession({
555
+ environmentId,
556
+ title: currentTitle,
557
+ gitRepoUrl,
558
+ branch,
559
+ signal: AbortSignal.timeout(15000)
560
+ });
561
+ if (!newSessionId) {
562
+ logForDebugging("[bridge:repl] Session creation failed during reconnection");
563
+ return false;
564
+ }
565
+ if (pollController.signal.aborted) {
566
+ logForDebugging("[bridge:repl] Reconnect aborted after session creation, cleaning up");
567
+ await archiveSession(newSessionId);
568
+ return false;
569
+ }
570
+ currentSessionId = newSessionId;
571
+ updateSessionBridgeId(toCompatSessionId(newSessionId)).catch(() => {});
572
+ lastTransportSequenceNum = 0;
573
+ recentInboundUUIDs.clear();
574
+ userMessageCallbackDone = !onUserMessage;
575
+ logForDebugging(`[bridge:repl] Re-created session: ${currentSessionId}`);
576
+ await writeBridgePointer(dir, {
577
+ sessionId: currentSessionId,
578
+ environmentId,
579
+ source: "repl"
580
+ });
581
+ previouslyFlushedUUIDs?.clear();
582
+ environmentRecreations = 0;
583
+ return true;
584
+ }
585
+ function getOAuthToken() {
586
+ return getAccessToken();
587
+ }
588
+ function drainFlushGate() {
589
+ const msgs = flushGate.end();
590
+ if (msgs.length === 0)
591
+ return;
592
+ if (!transport) {
593
+ logForDebugging(`[bridge:repl] Cannot drain ${msgs.length} pending message(s): no transport`);
594
+ return;
595
+ }
596
+ for (const msg of msgs) {
597
+ recentPostedUUIDs.add(msg.uuid);
598
+ }
599
+ const sdkMessages = toSDKMessages2(msgs);
600
+ const events = sdkMessages.map((sdkMsg) => ({
601
+ ...sdkMsg,
602
+ session_id: currentSessionId
603
+ }));
604
+ logForDebugging(`[bridge:repl] Drained ${msgs.length} pending message(s) after flush`);
605
+ transport.writeBatch(events);
606
+ }
607
+ let doTeardownImpl = null;
608
+ function triggerTeardown() {
609
+ doTeardownImpl?.();
610
+ }
611
+ function handleTransportPermanentClose(closeCode) {
612
+ logForDebugging(`[bridge:repl] Transport permanently closed: code=${closeCode}`);
613
+ logEvent("tengu_bridge_repl_ws_closed", {
614
+ code: closeCode
615
+ });
616
+ if (transport) {
617
+ const closedSeq = transport.getLastSequenceNum();
618
+ if (closedSeq > lastTransportSequenceNum) {
619
+ lastTransportSequenceNum = closedSeq;
620
+ }
621
+ transport = null;
622
+ }
623
+ wakePollLoop();
624
+ const dropped = flushGate.drop();
625
+ if (dropped > 0) {
626
+ logForDebugging(`[bridge:repl] Dropping ${dropped} pending message(s) on transport close (code=${closeCode})`, { level: "warn" });
627
+ }
628
+ if (closeCode === 1000) {
629
+ onStateChange?.("failed", "session ended");
630
+ pollController.abort();
631
+ triggerTeardown();
632
+ return;
633
+ }
634
+ onStateChange?.("reconnecting", `Remote Control connection lost (code ${closeCode})`);
635
+ logForDebugging(`[bridge:repl] Transport reconnect budget exhausted (code=${closeCode}), attempting env reconnect`);
636
+ reconnectEnvironmentWithSession().then((success) => {
637
+ if (success)
638
+ return;
639
+ if (pollController.signal.aborted)
640
+ return;
641
+ logForDebugging("[bridge:repl] reconnectEnvironmentWithSession resolved false \u2014 tearing down");
642
+ logEvent("tengu_bridge_repl_reconnect_failed", {
643
+ close_code: closeCode
644
+ });
645
+ onStateChange?.("failed", "reconnection failed");
646
+ triggerTeardown();
647
+ });
648
+ }
649
+ let sigusr2Handler;
650
+ if (process.env.USER_TYPE === "ant" && process.platform !== "win32") {
651
+ sigusr2Handler = () => {
652
+ logForDebugging("[bridge:repl] SIGUSR2 received \u2014 forcing doReconnect() for testing");
653
+ reconnectEnvironmentWithSession();
654
+ };
655
+ process.on("SIGUSR2", sigusr2Handler);
656
+ }
657
+ let debugFireClose = null;
658
+ if (process.env.USER_TYPE === "ant") {
659
+ registerBridgeDebugHandle({
660
+ fireClose: (code) => {
661
+ if (!debugFireClose) {
662
+ logForDebugging("[bridge:debug] fireClose: no transport wired yet");
663
+ return;
664
+ }
665
+ logForDebugging(`[bridge:debug] fireClose(${code}) \u2014 injecting`);
666
+ debugFireClose(code);
667
+ },
668
+ forceReconnect: () => {
669
+ logForDebugging("[bridge:debug] forceReconnect \u2014 injecting");
670
+ reconnectEnvironmentWithSession();
671
+ },
672
+ injectFault: injectBridgeFault,
673
+ wakePollLoop,
674
+ describe: () => `env=${environmentId} session=${currentSessionId} transport=${transport?.getStateLabel() ?? "null"} workId=${currentWorkId ?? "null"}`
675
+ });
676
+ }
677
+ const pollOpts = {
678
+ api,
679
+ getCredentials: () => ({ environmentId, environmentSecret }),
680
+ signal: pollController.signal,
681
+ getPollIntervalConfig: getPollIntervalConfig2,
682
+ onStateChange,
683
+ getWsState: () => transport?.getStateLabel() ?? "null",
684
+ isAtCapacity: () => transport !== null,
685
+ capacitySignal,
686
+ onFatalError: triggerTeardown,
687
+ getHeartbeatInfo: () => {
688
+ if (!currentWorkId || !currentIngressToken) {
689
+ return null;
690
+ }
691
+ return {
692
+ environmentId,
693
+ workId: currentWorkId,
694
+ sessionToken: currentIngressToken
695
+ };
696
+ },
697
+ onHeartbeatFatal: (err) => {
698
+ logForDebugging(`[bridge:repl] heartbeatWork fatal (status=${err.status}) \u2014 tearing down work item for fast re-dispatch`);
699
+ if (transport) {
700
+ const seq2 = transport.getLastSequenceNum();
701
+ if (seq2 > lastTransportSequenceNum) {
702
+ lastTransportSequenceNum = seq2;
703
+ }
704
+ transport.close();
705
+ transport = null;
706
+ }
707
+ flushGate.drop();
708
+ if (currentWorkId) {
709
+ api.stopWork(environmentId, currentWorkId, false).catch((e) => {
710
+ logForDebugging(`[bridge:repl] stopWork after heartbeat fatal: ${errorMessage(e)}`);
711
+ });
712
+ }
713
+ currentWorkId = null;
714
+ currentIngressToken = null;
715
+ wakePollLoop();
716
+ onStateChange?.("reconnecting", "Work item lease expired, fetching fresh token");
717
+ },
718
+ async onEnvironmentLost() {
719
+ const success = await reconnectEnvironmentWithSession();
720
+ if (!success) {
721
+ return null;
722
+ }
723
+ return { environmentId, environmentSecret };
724
+ },
725
+ onWorkReceived: (workSessionId, ingressToken, workId, serverUseCcrV2) => {
726
+ if (transport?.isConnectedStatus()) {
727
+ logForDebugging(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${workId})`);
728
+ }
729
+ logForDebugging(`[bridge:repl] Work received: workId=${workId} workSessionId=${workSessionId} currentSessionId=${currentSessionId} match=${sameSessionId(workSessionId, currentSessionId)}`);
730
+ writeBridgePointer(dir, {
731
+ sessionId: currentSessionId,
732
+ environmentId,
733
+ source: "repl"
734
+ });
735
+ if (!sameSessionId(workSessionId, currentSessionId)) {
736
+ logForDebugging(`[bridge:repl] Rejecting foreign session: expected=${currentSessionId} got=${workSessionId}`);
737
+ return;
738
+ }
739
+ currentWorkId = workId;
740
+ currentIngressToken = ingressToken;
741
+ const useCcrV2 = serverUseCcrV2 || isEnvTruthy(process.env.CLAUDE_BRIDGE_USE_CCR_V2);
742
+ let v1OauthToken;
743
+ if (!useCcrV2) {
744
+ v1OauthToken = getOAuthToken();
745
+ if (!v1OauthToken) {
746
+ logForDebugging("[bridge:repl] No OAuth token available for session ingress, skipping work");
747
+ return;
748
+ }
749
+ updateSessionIngressAuthToken(v1OauthToken);
750
+ }
751
+ logEvent("tengu_bridge_repl_work_received", {});
752
+ if (transport) {
753
+ const oldTransport = transport;
754
+ transport = null;
755
+ const oldSeq = oldTransport.getLastSequenceNum();
756
+ if (oldSeq > lastTransportSequenceNum) {
757
+ lastTransportSequenceNum = oldSeq;
758
+ }
759
+ oldTransport.close();
760
+ }
761
+ flushGate.deactivate();
762
+ const onServerControlRequest = (request) => handleServerControlRequest(request, {
763
+ transport,
764
+ sessionId: currentSessionId,
765
+ onInterrupt,
766
+ onSetModel,
767
+ onSetMaxThinkingTokens,
768
+ onSetPermissionMode
769
+ });
770
+ let initialFlushDone = false;
771
+ const wireTransport = (newTransport) => {
772
+ transport = newTransport;
773
+ newTransport.setOnConnect(() => {
774
+ if (transport !== newTransport)
775
+ return;
776
+ logForDebugging("[bridge:repl] Ingress transport connected");
777
+ logEvent("tengu_bridge_repl_ws_connected", {});
778
+ if (!useCcrV2) {
779
+ const freshToken = getOAuthToken();
780
+ if (freshToken) {
781
+ updateSessionIngressAuthToken(freshToken);
782
+ }
783
+ }
784
+ teardownStarted = false;
785
+ if (!initialFlushDone && initialMessages && initialMessages.length > 0) {
786
+ initialFlushDone = true;
787
+ const historyCap = initialHistoryCap;
788
+ const eligibleMessages = initialMessages.filter((m) => isEligibleBridgeMessage(m) && !previouslyFlushedUUIDs?.has(m.uuid));
789
+ const cappedMessages = historyCap > 0 && eligibleMessages.length > historyCap ? eligibleMessages.slice(-historyCap) : eligibleMessages;
790
+ if (cappedMessages.length < eligibleMessages.length) {
791
+ logForDebugging(`[bridge:repl] Capped initial flush: ${eligibleMessages.length} -> ${cappedMessages.length} (cap=${historyCap})`);
792
+ logEvent("tengu_bridge_repl_history_capped", {
793
+ eligible_count: eligibleMessages.length,
794
+ capped_count: cappedMessages.length
795
+ });
796
+ }
797
+ const sdkMessages = toSDKMessages2(cappedMessages);
798
+ if (sdkMessages.length > 0) {
799
+ logForDebugging(`[bridge:repl] Flushing ${sdkMessages.length} initial message(s) via transport`);
800
+ const events = sdkMessages.map((sdkMsg) => ({
801
+ ...sdkMsg,
802
+ session_id: currentSessionId
803
+ }));
804
+ const dropsBefore = newTransport.droppedBatchCount;
805
+ newTransport.writeBatch(events).then(() => {
806
+ if (newTransport.droppedBatchCount > dropsBefore) {
807
+ logForDebugging(`[bridge:repl] Initial flush dropped ${newTransport.droppedBatchCount - dropsBefore} batch(es) \u2014 not marking ${sdkMessages.length} UUID(s) as flushed`);
808
+ return;
809
+ }
810
+ if (previouslyFlushedUUIDs) {
811
+ for (const sdkMsg of sdkMessages) {
812
+ if (sdkMsg.uuid) {
813
+ previouslyFlushedUUIDs.add(sdkMsg.uuid);
814
+ }
815
+ }
816
+ }
817
+ }).catch((e) => logForDebugging(`[bridge:repl] Initial flush failed: ${e}`)).finally(() => {
818
+ if (transport !== newTransport)
819
+ return;
820
+ drainFlushGate();
821
+ onStateChange?.("connected");
822
+ });
823
+ } else {
824
+ drainFlushGate();
825
+ onStateChange?.("connected");
826
+ }
827
+ } else if (!flushGate.active) {
828
+ onStateChange?.("connected");
829
+ }
830
+ });
831
+ newTransport.setOnData((data) => {
832
+ handleIngressMessage(data, recentPostedUUIDs, recentInboundUUIDs, onInboundMessage, onPermissionResponse, onServerControlRequest);
833
+ });
834
+ debugFireClose = handleTransportPermanentClose;
835
+ newTransport.setOnClose((closeCode) => {
836
+ if (transport !== newTransport)
837
+ return;
838
+ handleTransportPermanentClose(closeCode);
839
+ });
840
+ if (!initialFlushDone && initialMessages && initialMessages.length > 0) {
841
+ flushGate.start();
842
+ }
843
+ newTransport.connect();
844
+ };
845
+ v2Generation++;
846
+ if (useCcrV2) {
847
+ const sessionUrl = buildCCRv2SdkUrl(baseUrl, workSessionId);
848
+ const thisGen = v2Generation;
849
+ logForDebugging(`[bridge:repl] CCR v2: sessionUrl=${sessionUrl} session=${workSessionId} gen=${thisGen}`);
850
+ createV2ReplTransport({
851
+ sessionUrl,
852
+ ingressToken,
853
+ sessionId: workSessionId,
854
+ initialSequenceNum: lastTransportSequenceNum
855
+ }).then((t) => {
856
+ if (pollController.signal.aborted) {
857
+ t.close();
858
+ return;
859
+ }
860
+ if (thisGen !== v2Generation) {
861
+ logForDebugging(`[bridge:repl] CCR v2: discarding stale handshake gen=${thisGen} current=${v2Generation}`);
862
+ t.close();
863
+ return;
864
+ }
865
+ wireTransport(t);
866
+ }, (err) => {
867
+ logForDebugging(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${errorMessage(err)}`, { level: "error" });
868
+ logEvent("tengu_bridge_repl_ccr_v2_init_failed", {});
869
+ if (thisGen !== v2Generation)
870
+ return;
871
+ if (currentWorkId) {
872
+ api.stopWork(environmentId, currentWorkId, false).catch((e) => {
873
+ logForDebugging(`[bridge:repl] stopWork after v2 init failure: ${errorMessage(e)}`);
874
+ });
875
+ currentWorkId = null;
876
+ currentIngressToken = null;
877
+ }
878
+ wakePollLoop();
879
+ });
880
+ } else {
881
+ const wsUrl = buildSdkUrl(sessionIngressUrl, workSessionId);
882
+ logForDebugging(`[bridge:repl] Ingress URL: ${wsUrl}`);
883
+ logForDebugging(`[bridge:repl] Creating HybridTransport: session=${workSessionId}`);
884
+ const oauthToken = v1OauthToken ?? "";
885
+ wireTransport(createV1ReplTransport(new HybridTransport(new URL(wsUrl), {
886
+ Authorization: `Bearer ${oauthToken}`,
887
+ "anthropic-version": "2023-06-01"
888
+ }, workSessionId, () => ({
889
+ Authorization: `Bearer ${getOAuthToken() ?? oauthToken}`,
890
+ "anthropic-version": "2023-06-01"
891
+ }), {
892
+ maxConsecutiveFailures: 50,
893
+ isBridge: true,
894
+ onBatchDropped: () => {
895
+ onStateChange?.("reconnecting", "Lost sync with Remote Control \u2014 events could not be delivered");
896
+ wakePollLoop();
897
+ }
898
+ })));
899
+ }
900
+ }
901
+ };
902
+ startWorkPollLoop(pollOpts);
903
+ const pointerRefreshTimer = perpetual ? setInterval(() => {
904
+ if (reconnectPromise)
905
+ return;
906
+ writeBridgePointer(dir, {
907
+ sessionId: currentSessionId,
908
+ environmentId,
909
+ source: "repl"
910
+ });
911
+ }, 3600000) : null;
912
+ pointerRefreshTimer?.unref?.();
913
+ const keepAliveIntervalMs = getPollIntervalConfig2().session_keepalive_interval_v2_ms;
914
+ const keepAliveTimer = keepAliveIntervalMs > 0 ? setInterval(() => {
915
+ if (!transport)
916
+ return;
917
+ logForDebugging("[bridge:repl] keep_alive sent");
918
+ transport.write({ type: "keep_alive" }).catch((err) => {
919
+ logForDebugging(`[bridge:repl] keep_alive write failed: ${errorMessage(err)}`);
920
+ });
921
+ }, keepAliveIntervalMs) : null;
922
+ keepAliveTimer?.unref?.();
923
+ let teardownStarted = false;
924
+ doTeardownImpl = async () => {
925
+ if (teardownStarted) {
926
+ logForDebugging(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${environmentId} session=${currentSessionId}`);
927
+ return;
928
+ }
929
+ teardownStarted = true;
930
+ const teardownStart = Date.now();
931
+ logForDebugging(`[bridge:repl] Teardown starting: env=${environmentId} session=${currentSessionId} workId=${currentWorkId ?? "none"} transportState=${transport?.getStateLabel() ?? "null"}`);
932
+ if (pointerRefreshTimer !== null) {
933
+ clearInterval(pointerRefreshTimer);
934
+ }
935
+ if (keepAliveTimer !== null) {
936
+ clearInterval(keepAliveTimer);
937
+ }
938
+ if (sigusr2Handler) {
939
+ process.off("SIGUSR2", sigusr2Handler);
940
+ }
941
+ if (process.env.USER_TYPE === "ant") {
942
+ clearBridgeDebugHandle();
943
+ debugFireClose = null;
944
+ }
945
+ pollController.abort();
946
+ logForDebugging("[bridge:repl] Teardown: poll loop aborted");
947
+ if (transport) {
948
+ const finalSeq = transport.getLastSequenceNum();
949
+ if (finalSeq > lastTransportSequenceNum) {
950
+ lastTransportSequenceNum = finalSeq;
951
+ }
952
+ }
953
+ if (perpetual) {
954
+ transport = null;
955
+ flushGate.drop();
956
+ await writeBridgePointer(dir, {
957
+ sessionId: currentSessionId,
958
+ environmentId,
959
+ source: "repl"
960
+ });
961
+ logForDebugging(`[bridge:repl] Teardown (perpetual): leaving env=${environmentId} session=${currentSessionId} alive on server, duration=${Date.now() - teardownStart}ms`);
962
+ return;
963
+ }
964
+ const teardownTransport = transport;
965
+ transport = null;
966
+ flushGate.drop();
967
+ if (teardownTransport) {
968
+ teardownTransport.write(makeResultMessage(currentSessionId));
969
+ }
970
+ const stopWorkP = currentWorkId ? api.stopWork(environmentId, currentWorkId, true).then(() => {
971
+ logForDebugging("[bridge:repl] Teardown: stopWork completed");
972
+ }).catch((err) => {
973
+ logForDebugging(`[bridge:repl] Teardown stopWork failed: ${errorMessage(err)}`);
974
+ }) : Promise.resolve();
975
+ await Promise.all([stopWorkP, archiveSession(currentSessionId)]);
976
+ teardownTransport?.close();
977
+ logForDebugging("[bridge:repl] Teardown: transport closed");
978
+ await api.deregisterEnvironment(environmentId).catch((err) => {
979
+ logForDebugging(`[bridge:repl] Teardown deregister failed: ${errorMessage(err)}`);
980
+ });
981
+ await clearBridgePointer(dir);
982
+ logForDebugging(`[bridge:repl] Teardown complete: env=${environmentId} duration=${Date.now() - teardownStart}ms`);
983
+ };
984
+ const unregister = registerCleanup(() => doTeardownImpl?.());
985
+ logForDebugging(`[bridge:repl] Ready: env=${environmentId} session=${currentSessionId}`);
986
+ onStateChange?.("ready");
987
+ return {
988
+ get bridgeSessionId() {
989
+ return currentSessionId;
990
+ },
991
+ get environmentId() {
992
+ return environmentId;
993
+ },
994
+ getSSESequenceNum() {
995
+ const live = transport?.getLastSequenceNum() ?? 0;
996
+ return Math.max(lastTransportSequenceNum, live);
997
+ },
998
+ sessionIngressUrl,
999
+ writeMessages(messages) {
1000
+ const filtered = messages.filter((m) => isEligibleBridgeMessage(m) && !initialMessageUUIDs.has(m.uuid) && !recentPostedUUIDs.has(m.uuid));
1001
+ if (filtered.length === 0)
1002
+ return;
1003
+ if (!userMessageCallbackDone) {
1004
+ for (const m of filtered) {
1005
+ const text = extractTitleText(m);
1006
+ if (text !== undefined && onUserMessage?.(text, currentSessionId)) {
1007
+ userMessageCallbackDone = true;
1008
+ break;
1009
+ }
1010
+ }
1011
+ }
1012
+ if (flushGate.enqueue(...filtered)) {
1013
+ logForDebugging(`[bridge:repl] Queued ${filtered.length} message(s) during initial flush`);
1014
+ return;
1015
+ }
1016
+ if (!transport) {
1017
+ const types = filtered.map((m) => m.type).join(",");
1018
+ logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} message(s) [${types}] for session=${currentSessionId}`, { level: "warn" });
1019
+ return;
1020
+ }
1021
+ for (const msg of filtered) {
1022
+ recentPostedUUIDs.add(msg.uuid);
1023
+ }
1024
+ logForDebugging(`[bridge:repl] Sending ${filtered.length} message(s) via transport`);
1025
+ const sdkMessages = toSDKMessages2(filtered);
1026
+ const events = sdkMessages.map((sdkMsg) => ({
1027
+ ...sdkMsg,
1028
+ session_id: currentSessionId
1029
+ }));
1030
+ transport.writeBatch(events);
1031
+ },
1032
+ writeSdkMessages(messages) {
1033
+ const filtered = messages.filter((m) => !m.uuid || !recentPostedUUIDs.has(m.uuid));
1034
+ if (filtered.length === 0)
1035
+ return;
1036
+ if (!transport) {
1037
+ logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} SDK message(s) for session=${currentSessionId}`, { level: "warn" });
1038
+ return;
1039
+ }
1040
+ for (const msg of filtered) {
1041
+ if (msg.uuid)
1042
+ recentPostedUUIDs.add(msg.uuid);
1043
+ }
1044
+ const events = filtered.map((m) => ({ ...m, session_id: currentSessionId }));
1045
+ transport.writeBatch(events);
1046
+ },
1047
+ sendControlRequest(request) {
1048
+ if (!transport) {
1049
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_request");
1050
+ return;
1051
+ }
1052
+ const event = { ...request, session_id: currentSessionId };
1053
+ transport.write(event);
1054
+ logForDebugging(`[bridge:repl] Sent control_request request_id=${request.request_id}`);
1055
+ },
1056
+ sendControlResponse(response) {
1057
+ if (!transport) {
1058
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_response");
1059
+ return;
1060
+ }
1061
+ const event = { ...response, session_id: currentSessionId };
1062
+ transport.write(event);
1063
+ logForDebugging("[bridge:repl] Sent control_response");
1064
+ },
1065
+ sendControlCancelRequest(requestId) {
1066
+ if (!transport) {
1067
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_cancel_request");
1068
+ return;
1069
+ }
1070
+ const event = {
1071
+ type: "control_cancel_request",
1072
+ request_id: requestId,
1073
+ session_id: currentSessionId
1074
+ };
1075
+ transport.write(event);
1076
+ logForDebugging(`[bridge:repl] Sent control_cancel_request request_id=${requestId}`);
1077
+ },
1078
+ sendResult() {
1079
+ if (!transport) {
1080
+ logForDebugging(`[bridge:repl] sendResult: skipping, transport not configured session=${currentSessionId}`);
1081
+ return;
1082
+ }
1083
+ transport.write(makeResultMessage(currentSessionId));
1084
+ logForDebugging(`[bridge:repl] Sent result for session=${currentSessionId}`);
1085
+ },
1086
+ async teardown() {
1087
+ unregister();
1088
+ await doTeardownImpl?.();
1089
+ logForDebugging("[bridge:repl] Torn down");
1090
+ logEvent("tengu_bridge_repl_teardown", {});
1091
+ }
1092
+ };
1093
+ }
1094
+ async function startWorkPollLoop({
1095
+ api,
1096
+ getCredentials,
1097
+ signal,
1098
+ onStateChange,
1099
+ onWorkReceived,
1100
+ onEnvironmentLost,
1101
+ getWsState,
1102
+ isAtCapacity,
1103
+ capacitySignal,
1104
+ onFatalError,
1105
+ getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG,
1106
+ getHeartbeatInfo,
1107
+ onHeartbeatFatal
1108
+ }) {
1109
+ const MAX_ENVIRONMENT_RECREATIONS = 3;
1110
+ logForDebugging(`[bridge:repl] Starting work poll loop for env=${getCredentials().environmentId}`);
1111
+ let consecutiveErrors = 0;
1112
+ let firstErrorTime = null;
1113
+ let lastPollErrorTime = null;
1114
+ let environmentRecreations = 0;
1115
+ let suspensionDetected = false;
1116
+ while (!signal.aborted) {
1117
+ const { environmentId: envId, environmentSecret: envSecret } = getCredentials();
1118
+ const pollConfig = getPollIntervalConfig2();
1119
+ try {
1120
+ const work = await api.pollForWork(envId, envSecret, signal, pollConfig.reclaim_older_than_ms);
1121
+ environmentRecreations = 0;
1122
+ if (consecutiveErrors > 0) {
1123
+ logForDebugging(`[bridge:repl] Poll recovered after ${consecutiveErrors} consecutive error(s)`);
1124
+ consecutiveErrors = 0;
1125
+ firstErrorTime = null;
1126
+ lastPollErrorTime = null;
1127
+ onStateChange?.("ready");
1128
+ }
1129
+ if (!work) {
1130
+ const skipAtCapacityOnce = suspensionDetected;
1131
+ suspensionDetected = false;
1132
+ if (isAtCapacity?.() && capacitySignal && !skipAtCapacityOnce) {
1133
+ const atCapMs = pollConfig.poll_interval_ms_at_capacity;
1134
+ if (pollConfig.non_exclusive_heartbeat_interval_ms > 0 && getHeartbeatInfo) {
1135
+ logEvent("tengu_bridge_heartbeat_mode_entered", {
1136
+ heartbeat_interval_ms: pollConfig.non_exclusive_heartbeat_interval_ms
1137
+ });
1138
+ const pollDeadline = atCapMs > 0 ? Date.now() + atCapMs : null;
1139
+ let needsBackoff = false;
1140
+ let hbCycles = 0;
1141
+ while (!signal.aborted && isAtCapacity() && (pollDeadline === null || Date.now() < pollDeadline)) {
1142
+ const hbConfig = getPollIntervalConfig2();
1143
+ if (hbConfig.non_exclusive_heartbeat_interval_ms <= 0)
1144
+ break;
1145
+ const info = getHeartbeatInfo();
1146
+ if (!info)
1147
+ break;
1148
+ const cap = capacitySignal();
1149
+ try {
1150
+ await api.heartbeatWork(info.environmentId, info.workId, info.sessionToken);
1151
+ } catch (err) {
1152
+ logForDebugging(`[bridge:repl:heartbeat] Failed: ${errorMessage(err)}`);
1153
+ if (err instanceof BridgeFatalError) {
1154
+ cap.cleanup();
1155
+ logEvent("tengu_bridge_heartbeat_error", {
1156
+ status: err.status,
1157
+ error_type: err.status === 401 || err.status === 403 ? "auth_failed" : "fatal"
1158
+ });
1159
+ if (onHeartbeatFatal) {
1160
+ onHeartbeatFatal(err);
1161
+ logForDebugging(`[bridge:repl:heartbeat] Fatal (status=${err.status}), work state cleared \u2014 fast-polling for re-dispatch`);
1162
+ } else {
1163
+ needsBackoff = true;
1164
+ }
1165
+ break;
1166
+ }
1167
+ }
1168
+ hbCycles++;
1169
+ await sleep(hbConfig.non_exclusive_heartbeat_interval_ms, cap.signal);
1170
+ cap.cleanup();
1171
+ }
1172
+ const exitReason = needsBackoff ? "error" : signal.aborted ? "shutdown" : !isAtCapacity() ? "capacity_changed" : pollDeadline !== null && Date.now() >= pollDeadline ? "poll_due" : "config_disabled";
1173
+ logEvent("tengu_bridge_heartbeat_mode_exited", {
1174
+ reason: exitReason,
1175
+ heartbeat_cycles: hbCycles
1176
+ });
1177
+ if (!needsBackoff) {
1178
+ if (exitReason === "poll_due") {
1179
+ logForDebugging(`[bridge:repl] Heartbeat poll_due after ${hbCycles} cycles \u2014 falling through to pollForWork`);
1180
+ }
1181
+ continue;
1182
+ }
1183
+ }
1184
+ const sleepMs = atCapMs > 0 ? atCapMs : pollConfig.non_exclusive_heartbeat_interval_ms;
1185
+ if (sleepMs > 0) {
1186
+ const cap = capacitySignal();
1187
+ const sleepStart = Date.now();
1188
+ await sleep(sleepMs, cap.signal);
1189
+ cap.cleanup();
1190
+ const overrun = Date.now() - sleepStart - sleepMs;
1191
+ if (overrun > 60000) {
1192
+ logForDebugging(`[bridge:repl] At-capacity sleep overran by ${Math.round(overrun / 1000)}s \u2014 process suspension detected, forcing one fast-poll cycle`);
1193
+ logEvent("tengu_bridge_repl_suspension_detected", {
1194
+ overrun_ms: overrun
1195
+ });
1196
+ suspensionDetected = true;
1197
+ }
1198
+ }
1199
+ } else {
1200
+ await sleep(pollConfig.poll_interval_ms_not_at_capacity, signal);
1201
+ }
1202
+ continue;
1203
+ }
1204
+ let secret;
1205
+ try {
1206
+ secret = decodeWorkSecret(work.secret);
1207
+ } catch (err) {
1208
+ logForDebugging(`[bridge:repl] Failed to decode work secret: ${errorMessage(err)}`);
1209
+ logEvent("tengu_bridge_repl_work_secret_failed", {});
1210
+ await api.stopWork(envId, work.id, false).catch(() => {});
1211
+ continue;
1212
+ }
1213
+ logForDebugging(`[bridge:repl] Acknowledging workId=${work.id}`);
1214
+ try {
1215
+ await api.acknowledgeWork(envId, work.id, secret.session_ingress_token);
1216
+ } catch (err) {
1217
+ logForDebugging(`[bridge:repl] Acknowledge failed workId=${work.id}: ${errorMessage(err)}`);
1218
+ }
1219
+ if (work.data.type === "healthcheck") {
1220
+ logForDebugging("[bridge:repl] Healthcheck received");
1221
+ continue;
1222
+ }
1223
+ if (work.data.type === "session") {
1224
+ const workSessionId = work.data.id;
1225
+ try {
1226
+ validateBridgeId(workSessionId, "session_id");
1227
+ } catch {
1228
+ logForDebugging(`[bridge:repl] Invalid session_id in work: ${workSessionId}`);
1229
+ continue;
1230
+ }
1231
+ onWorkReceived(workSessionId, secret.session_ingress_token, work.id, secret.use_code_sessions === true);
1232
+ logForDebugging("[bridge:repl] Work accepted, continuing poll loop");
1233
+ }
1234
+ } catch (err) {
1235
+ if (signal.aborted)
1236
+ break;
1237
+ if (err instanceof BridgeFatalError && err.status === 404 && onEnvironmentLost) {
1238
+ const currentEnvId = getCredentials().environmentId;
1239
+ if (envId !== currentEnvId) {
1240
+ logForDebugging(`[bridge:repl] Stale poll error for old env=${envId}, current env=${currentEnvId} \u2014 skipping onEnvironmentLost`);
1241
+ consecutiveErrors = 0;
1242
+ firstErrorTime = null;
1243
+ continue;
1244
+ }
1245
+ environmentRecreations++;
1246
+ logForDebugging(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`);
1247
+ logEvent("tengu_bridge_repl_env_lost", {
1248
+ attempt: environmentRecreations
1249
+ });
1250
+ if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) {
1251
+ logForDebugging(`[bridge:repl] Environment re-registration limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`);
1252
+ onStateChange?.("failed", "Environment deleted and re-registration limit reached");
1253
+ onFatalError?.();
1254
+ break;
1255
+ }
1256
+ onStateChange?.("reconnecting", "environment lost, recreating session");
1257
+ const newCreds = await onEnvironmentLost();
1258
+ if (signal.aborted)
1259
+ break;
1260
+ if (newCreds) {
1261
+ consecutiveErrors = 0;
1262
+ firstErrorTime = null;
1263
+ onStateChange?.("ready");
1264
+ logForDebugging(`[bridge:repl] Re-registered environment: ${newCreds.environmentId}`);
1265
+ continue;
1266
+ }
1267
+ onStateChange?.("failed", "Environment deleted and re-registration failed");
1268
+ onFatalError?.();
1269
+ break;
1270
+ }
1271
+ if (err instanceof BridgeFatalError) {
1272
+ const isExpiry = isExpiredErrorType(err.errorType);
1273
+ const isSuppressible = isSuppressible403(err);
1274
+ logForDebugging(`[bridge:repl] Fatal poll error: ${err.message} (status=${err.status}, type=${err.errorType ?? "unknown"})${isSuppressible ? " (suppressed)" : ""}`);
1275
+ logEvent("tengu_bridge_repl_fatal_error", {
1276
+ status: err.status,
1277
+ error_type: err.errorType
1278
+ });
1279
+ logForDiagnosticsNoPII(isExpiry ? "info" : "error", "bridge_repl_fatal_error", { status: err.status, error_type: err.errorType });
1280
+ if (!isSuppressible) {
1281
+ onStateChange?.("failed", isExpiry ? "session expired \xB7 /remote-control to reconnect" : err.message);
1282
+ }
1283
+ onFatalError?.();
1284
+ break;
1285
+ }
1286
+ const now = Date.now();
1287
+ if (lastPollErrorTime !== null && now - lastPollErrorTime > POLL_ERROR_MAX_DELAY_MS * 2) {
1288
+ logForDebugging(`[bridge:repl] Detected system sleep (${Math.round((now - lastPollErrorTime) / 1000)}s gap), resetting poll error budget`);
1289
+ logForDiagnosticsNoPII("info", "bridge_repl_poll_sleep_detected", {
1290
+ gapMs: now - lastPollErrorTime
1291
+ });
1292
+ consecutiveErrors = 0;
1293
+ firstErrorTime = null;
1294
+ }
1295
+ lastPollErrorTime = now;
1296
+ consecutiveErrors++;
1297
+ if (firstErrorTime === null) {
1298
+ firstErrorTime = now;
1299
+ }
1300
+ const elapsed = now - firstErrorTime;
1301
+ const httpStatus = extractHttpStatus(err);
1302
+ const errMsg = describeAxiosError(err);
1303
+ const wsLabel = getWsState?.() ?? "unknown";
1304
+ logForDebugging(`[bridge:repl] Poll error (attempt ${consecutiveErrors}, elapsed ${Math.round(elapsed / 1000)}s, ws=${wsLabel}): ${errMsg}`);
1305
+ logEvent("tengu_bridge_repl_poll_error", {
1306
+ status: httpStatus,
1307
+ consecutiveErrors,
1308
+ elapsedMs: elapsed
1309
+ });
1310
+ if (consecutiveErrors === 1) {
1311
+ onStateChange?.("reconnecting", errMsg);
1312
+ }
1313
+ if (elapsed >= POLL_ERROR_GIVE_UP_MS) {
1314
+ logForDebugging(`[bridge:repl] Poll failures exceeded ${POLL_ERROR_GIVE_UP_MS / 1000}s (${consecutiveErrors} errors), giving up`);
1315
+ logForDiagnosticsNoPII("info", "bridge_repl_poll_give_up");
1316
+ logEvent("tengu_bridge_repl_poll_give_up", {
1317
+ consecutiveErrors,
1318
+ elapsedMs: elapsed,
1319
+ lastStatus: httpStatus
1320
+ });
1321
+ onStateChange?.("failed", "connection to server lost");
1322
+ break;
1323
+ }
1324
+ const backoff = Math.min(POLL_ERROR_INITIAL_DELAY_MS * 2 ** (consecutiveErrors - 1), POLL_ERROR_MAX_DELAY_MS);
1325
+ if (getPollIntervalConfig2().non_exclusive_heartbeat_interval_ms > 0) {
1326
+ const info = getHeartbeatInfo?.();
1327
+ if (info) {
1328
+ try {
1329
+ await api.heartbeatWork(info.environmentId, info.workId, info.sessionToken);
1330
+ } catch {}
1331
+ }
1332
+ }
1333
+ await sleep(backoff, signal);
1334
+ }
1335
+ }
1336
+ logForDebugging(`[bridge:repl] Work poll loop ended (aborted=${signal.aborted}) env=${getCredentials().environmentId}`);
1337
+ }
1338
+
1339
+ // src/bridge/initReplBridge.ts
1340
+ init_sessionIdCompat();
1341
+ async function initReplBridge(options) {
1342
+ const {
1343
+ onInboundMessage,
1344
+ onPermissionResponse,
1345
+ onInterrupt,
1346
+ onSetModel,
1347
+ onSetMaxThinkingTokens,
1348
+ onSetPermissionMode,
1349
+ onStateChange,
1350
+ initialMessages,
1351
+ getMessages,
1352
+ previouslyFlushedUUIDs,
1353
+ initialName,
1354
+ perpetual,
1355
+ outboundOnly,
1356
+ tags
1357
+ } = options ?? {};
1358
+ setCseShimGate(isCseShimEnabled);
1359
+ if (!await isBridgeEnabledBlocking()) {
1360
+ logBridgeSkip("not_enabled", "[bridge:repl] Skipping: bridge not enabled");
1361
+ return null;
1362
+ }
1363
+ if (!getBridgeAccessToken()) {
1364
+ logBridgeSkip("no_oauth", "[bridge:repl] Skipping: no OAuth tokens");
1365
+ onStateChange?.("failed", "/login");
1366
+ return null;
1367
+ }
1368
+ await waitForPolicyLimitsToLoad();
1369
+ if (!isPolicyAllowed("allow_remote_control")) {
1370
+ logBridgeSkip("policy_denied", "[bridge:repl] Skipping: allow_remote_control policy not allowed");
1371
+ onStateChange?.("failed", "disabled by your organization's policy");
1372
+ return null;
1373
+ }
1374
+ if (!getBridgeTokenOverride()) {
1375
+ const cfg = getGlobalConfig();
1376
+ if (cfg.bridgeOauthDeadExpiresAt != null && (cfg.bridgeOauthDeadFailCount ?? 0) >= 3 && getClaudeAIOAuthTokens()?.expiresAt === cfg.bridgeOauthDeadExpiresAt) {
1377
+ logForDebugging(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${cfg.bridgeOauthDeadFailCount} times)`);
1378
+ return null;
1379
+ }
1380
+ await checkAndRefreshOAuthTokenIfNeeded();
1381
+ const tokens = getClaudeAIOAuthTokens();
1382
+ if (tokens && tokens.expiresAt !== null && tokens.expiresAt <= Date.now()) {
1383
+ logBridgeSkip("oauth_expired_unrefreshable", "[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)");
1384
+ onStateChange?.("failed", "/login");
1385
+ const deadExpiresAt = tokens.expiresAt;
1386
+ saveGlobalConfig((c) => ({
1387
+ ...c,
1388
+ bridgeOauthDeadExpiresAt: deadExpiresAt,
1389
+ bridgeOauthDeadFailCount: c.bridgeOauthDeadExpiresAt === deadExpiresAt ? (c.bridgeOauthDeadFailCount ?? 0) + 1 : 1
1390
+ }));
1391
+ return null;
1392
+ }
1393
+ }
1394
+ const baseUrl = getBridgeBaseUrl();
1395
+ let title = `remote-control-${generateShortWordSlug()}`;
1396
+ let hasTitle = false;
1397
+ let hasExplicitTitle = false;
1398
+ if (initialName) {
1399
+ title = initialName;
1400
+ hasTitle = true;
1401
+ hasExplicitTitle = true;
1402
+ } else {
1403
+ const sessionId = getSessionId();
1404
+ const customTitle = sessionId ? getCurrentSessionTitle(sessionId) : undefined;
1405
+ if (customTitle) {
1406
+ title = customTitle;
1407
+ hasTitle = true;
1408
+ hasExplicitTitle = true;
1409
+ } else if (initialMessages && initialMessages.length > 0) {
1410
+ for (let i = initialMessages.length - 1;i >= 0; i--) {
1411
+ const msg = initialMessages[i];
1412
+ if (msg.type !== "user" || msg.isMeta || msg.toolUseResult || msg.isCompactSummary || msg.origin && msg.origin.kind !== "human" || isSyntheticMessage(msg))
1413
+ continue;
1414
+ const rawContent = getContentText(msg.message.content);
1415
+ if (!rawContent)
1416
+ continue;
1417
+ const derived = deriveTitle(rawContent);
1418
+ if (!derived)
1419
+ continue;
1420
+ title = derived;
1421
+ hasTitle = true;
1422
+ break;
1423
+ }
1424
+ }
1425
+ }
1426
+ let userMessageCount = 0;
1427
+ let lastBridgeSessionId;
1428
+ let genSeq = 0;
1429
+ const patch = (derived, bridgeSessionId, atCount) => {
1430
+ hasTitle = true;
1431
+ title = derived;
1432
+ logForDebugging(`[bridge:repl] derived title from message ${atCount}: ${derived}`);
1433
+ updateBridgeSessionTitle(bridgeSessionId, derived, {
1434
+ baseUrl,
1435
+ getAccessToken: getBridgeAccessToken
1436
+ }).catch(() => {});
1437
+ };
1438
+ const generateAndPatch = (input, bridgeSessionId) => {
1439
+ const gen = ++genSeq;
1440
+ const atCount = userMessageCount;
1441
+ generateSessionTitle(input, AbortSignal.timeout(15000)).then((generated) => {
1442
+ if (generated && gen === genSeq && lastBridgeSessionId === bridgeSessionId && !getCurrentSessionTitle(getSessionId())) {
1443
+ patch(generated, bridgeSessionId, atCount);
1444
+ }
1445
+ });
1446
+ };
1447
+ const onUserMessage = (text, bridgeSessionId) => {
1448
+ if (hasExplicitTitle || getCurrentSessionTitle(getSessionId())) {
1449
+ return true;
1450
+ }
1451
+ if (lastBridgeSessionId !== undefined && lastBridgeSessionId !== bridgeSessionId) {
1452
+ userMessageCount = 0;
1453
+ }
1454
+ lastBridgeSessionId = bridgeSessionId;
1455
+ userMessageCount++;
1456
+ if (userMessageCount === 1 && !hasTitle) {
1457
+ const placeholder = deriveTitle(text);
1458
+ if (placeholder)
1459
+ patch(placeholder, bridgeSessionId, userMessageCount);
1460
+ generateAndPatch(text, bridgeSessionId);
1461
+ } else if (userMessageCount === 3) {
1462
+ const msgs = getMessages?.();
1463
+ const input = msgs ? extractConversationText(getMessagesAfterCompactBoundary(msgs)) : text;
1464
+ generateAndPatch(input, bridgeSessionId);
1465
+ }
1466
+ return userMessageCount >= 3;
1467
+ };
1468
+ const initialHistoryCap = getFeatureValue_CACHED_WITH_REFRESH("tengu_bridge_initial_history_cap", 200, 5 * 60 * 1000);
1469
+ const orgUUID = await getOrganizationUUID();
1470
+ if (!orgUUID) {
1471
+ logBridgeSkip("no_org_uuid", "[bridge:repl] Skipping: no org UUID");
1472
+ onStateChange?.("failed", "/login");
1473
+ return null;
1474
+ }
1475
+ if (isEnvLessBridgeEnabled() && !perpetual) {
1476
+ const versionError2 = await checkEnvLessBridgeMinVersion();
1477
+ if (versionError2) {
1478
+ logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError2}`, true);
1479
+ onStateChange?.("failed", "run `claude update` to upgrade");
1480
+ return null;
1481
+ }
1482
+ logForDebugging("[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)");
1483
+ const { initEnvLessBridgeCore } = await import("./chunk-hd8531ec.js");
1484
+ return initEnvLessBridgeCore({
1485
+ baseUrl,
1486
+ orgUUID,
1487
+ title,
1488
+ getAccessToken: getBridgeAccessToken,
1489
+ onAuth401: handleOAuth401Error,
1490
+ toSDKMessages,
1491
+ initialHistoryCap,
1492
+ initialMessages,
1493
+ onInboundMessage,
1494
+ onUserMessage,
1495
+ onPermissionResponse,
1496
+ onInterrupt,
1497
+ onSetModel,
1498
+ onSetMaxThinkingTokens,
1499
+ onSetPermissionMode,
1500
+ onStateChange,
1501
+ outboundOnly,
1502
+ tags
1503
+ });
1504
+ }
1505
+ const versionError = checkBridgeMinVersion();
1506
+ if (versionError) {
1507
+ logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError}`);
1508
+ onStateChange?.("failed", "run `claude update` to upgrade");
1509
+ return null;
1510
+ }
1511
+ const branch = await getBranch();
1512
+ const gitRepoUrl = await getRemoteUrl();
1513
+ const sessionIngressUrl = process.env.USER_TYPE === "ant" && process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL ? process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL : baseUrl;
1514
+ let workerType = "claude_code";
1515
+ if (false) {}
1516
+ return initBridgeCore({
1517
+ dir: getOriginalCwd(),
1518
+ machineName: hostname(),
1519
+ branch,
1520
+ gitRepoUrl,
1521
+ title,
1522
+ baseUrl,
1523
+ sessionIngressUrl,
1524
+ workerType,
1525
+ getAccessToken: getBridgeAccessToken,
1526
+ createSession: (opts) => createBridgeSession({
1527
+ ...opts,
1528
+ events: [],
1529
+ baseUrl,
1530
+ getAccessToken: getBridgeAccessToken
1531
+ }),
1532
+ archiveSession: (sessionId) => archiveBridgeSession(sessionId, {
1533
+ baseUrl,
1534
+ getAccessToken: getBridgeAccessToken,
1535
+ timeoutMs: 1500
1536
+ }).catch((err) => {
1537
+ logForDebugging(`[bridge:repl] archiveBridgeSession threw: ${errorMessage(err)}`, { level: "error" });
1538
+ }),
1539
+ getCurrentTitle: () => getCurrentSessionTitle(getSessionId()) ?? title,
1540
+ onUserMessage,
1541
+ toSDKMessages,
1542
+ onAuth401: handleOAuth401Error,
1543
+ getPollIntervalConfig,
1544
+ initialHistoryCap,
1545
+ initialMessages,
1546
+ previouslyFlushedUUIDs,
1547
+ onInboundMessage,
1548
+ onPermissionResponse,
1549
+ onInterrupt,
1550
+ onSetModel,
1551
+ onSetMaxThinkingTokens,
1552
+ onSetPermissionMode,
1553
+ onStateChange,
1554
+ perpetual
1555
+ });
1556
+ }
1557
+ var TITLE_MAX_LEN = 50;
1558
+ function deriveTitle(raw) {
1559
+ const clean = stripDisplayTagsAllowEmpty(raw);
1560
+ const firstSentence = /^(.*?[.!?])\s/.exec(clean)?.[1] ?? clean;
1561
+ const flat = firstSentence.replace(/\s+/g, " ").trim();
1562
+ if (!flat)
1563
+ return;
1564
+ return flat.length > TITLE_MAX_LEN ? flat.slice(0, TITLE_MAX_LEN - 1) + "\u2026" : flat;
1565
+ }
1566
+ export {
1567
+ initReplBridge
1568
+ };