gong-code 0.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 (374) hide show
  1. package/README.md +38 -0
  2. package/dist/SKILL-22jccbka.md +1 -0
  3. package/dist/chunk-01wdn84e.js +8 -0
  4. package/dist/chunk-04bc74vz.js +243 -0
  5. package/dist/chunk-05t2vqsb.js +490 -0
  6. package/dist/chunk-0727wret.js +159 -0
  7. package/dist/chunk-07rervty.js +200 -0
  8. package/dist/chunk-0b9nxvyg.js +478 -0
  9. package/dist/chunk-0e428b73.js +600 -0
  10. package/dist/chunk-0hqfheht.js +3439 -0
  11. package/dist/chunk-0pnk52c2.js +116 -0
  12. package/dist/chunk-0sbddf6m.js +68 -0
  13. package/dist/chunk-0vf7xb84.js +176 -0
  14. package/dist/chunk-0yz17yjy.js +1061 -0
  15. package/dist/chunk-0zscb6c7.js +10 -0
  16. package/dist/chunk-10p21kq6.js +378 -0
  17. package/dist/chunk-17k78pmz.js +120 -0
  18. package/dist/chunk-19jvvqzp.js +1390 -0
  19. package/dist/chunk-1d5czqnr.js +173 -0
  20. package/dist/chunk-1gjysfnf.js +13876 -0
  21. package/dist/chunk-1jjfv0wd.js +467 -0
  22. package/dist/chunk-1jjzp2pa.js +617 -0
  23. package/dist/chunk-1m38dj2k.js +155 -0
  24. package/dist/chunk-1pgttway.js +211 -0
  25. package/dist/chunk-1vvnx0gb.js +8035 -0
  26. package/dist/chunk-1ztm9yps.js +49145 -0
  27. package/dist/chunk-208x1t0m.js +88 -0
  28. package/dist/chunk-20xqs3yk.js +843 -0
  29. package/dist/chunk-2b2c0wnn.js +584 -0
  30. package/dist/chunk-2g07117j.js +541 -0
  31. package/dist/chunk-2g6p2t3w.js +780 -0
  32. package/dist/chunk-2kjeaeg7.js +28 -0
  33. package/dist/chunk-2n0s2dhc.js +12 -0
  34. package/dist/chunk-2p0hvt8k.js +785 -0
  35. package/dist/chunk-2qmxg9y7.js +40174 -0
  36. package/dist/chunk-2qpy8kne.js +28 -0
  37. package/dist/chunk-2rgbf62a.js +40 -0
  38. package/dist/chunk-2tx0s41y.js +150 -0
  39. package/dist/chunk-2x8zk5cz.js +101 -0
  40. package/dist/chunk-2yqy25z4.js +48 -0
  41. package/dist/chunk-318g78ty.js +552 -0
  42. package/dist/chunk-31gfg8tz.js +290 -0
  43. package/dist/chunk-32n0s532.js +1317 -0
  44. package/dist/chunk-35dw2r9g.js +137 -0
  45. package/dist/chunk-36b5zqvn.js +1865 -0
  46. package/dist/chunk-38kpx69j.js +97 -0
  47. package/dist/chunk-3b01vp8p.js +815 -0
  48. package/dist/chunk-3f76a1ek.js +317 -0
  49. package/dist/chunk-3fd1hkhh.js +4254 -0
  50. package/dist/chunk-3ffxa7zj.js +8 -0
  51. package/dist/chunk-3gcj7w95.js +8 -0
  52. package/dist/chunk-3jf3k40v.js +970 -0
  53. package/dist/chunk-3k51qfp9.js +9301 -0
  54. package/dist/chunk-3mhygd2v.js +1180 -0
  55. package/dist/chunk-3p6y0gvb.js +117 -0
  56. package/dist/chunk-3r60xdt5.js +93 -0
  57. package/dist/chunk-43agf6xv.js +8 -0
  58. package/dist/chunk-46zr418r.js +15 -0
  59. package/dist/chunk-48k2bs4w.js +118 -0
  60. package/dist/chunk-4p987a4z.js +84 -0
  61. package/dist/chunk-4px25pe0.js +776 -0
  62. package/dist/chunk-4s93jyky.js +113 -0
  63. package/dist/chunk-4xv8bedf.js +58 -0
  64. package/dist/chunk-4y382mzd.js +346 -0
  65. package/dist/chunk-52dzw4bc.js +246 -0
  66. package/dist/chunk-52qqmh5g.js +110 -0
  67. package/dist/chunk-53grnhp7.js +8 -0
  68. package/dist/chunk-59craaxx.js +4249 -0
  69. package/dist/chunk-5b833jqs.js +96 -0
  70. package/dist/chunk-5cp2q9sh.js +58 -0
  71. package/dist/chunk-5dbaxmts.js +87 -0
  72. package/dist/chunk-5f5sxgp0.js +96 -0
  73. package/dist/chunk-5mkfderj.js +195 -0
  74. package/dist/chunk-5qw0mpvq.js +389 -0
  75. package/dist/chunk-5rxmszm8.js +48 -0
  76. package/dist/chunk-5ygxa3hr.js +65 -0
  77. package/dist/chunk-61d5dqq2.js +71 -0
  78. package/dist/chunk-6350958y.js +272 -0
  79. package/dist/chunk-65z8hg8j.js +1337 -0
  80. package/dist/chunk-6aq85gdq.js +8 -0
  81. package/dist/chunk-6cjh9exg.js +40751 -0
  82. package/dist/chunk-6e41p5m6.js +187 -0
  83. package/dist/chunk-6jb6xcnq.js +10511 -0
  84. package/dist/chunk-6jta29r1.js +20 -0
  85. package/dist/chunk-6q7f2rrv.js +4757 -0
  86. package/dist/chunk-6sg0ec6v.js +41 -0
  87. package/dist/chunk-6v0rhx4e.js +328 -0
  88. package/dist/chunk-6x5mz95v.js +751 -0
  89. package/dist/chunk-6xqp51qr.js +87 -0
  90. package/dist/chunk-6xvyx1s9.js +6957 -0
  91. package/dist/chunk-6ywh7wgp.js +468 -0
  92. package/dist/chunk-75ne77gm.js +1920 -0
  93. package/dist/chunk-77cb06js.js +602 -0
  94. package/dist/chunk-78n9kfp8.js +1645 -0
  95. package/dist/chunk-7be87rww.js +277 -0
  96. package/dist/chunk-7e1qjk3s.js +125 -0
  97. package/dist/chunk-7e7nxnss.js +360 -0
  98. package/dist/chunk-7g8156qp.js +55 -0
  99. package/dist/chunk-7nz71s42.js +3353 -0
  100. package/dist/chunk-7r078t2x.js +113 -0
  101. package/dist/chunk-7shx41hj.js +3094 -0
  102. package/dist/chunk-7yexhdjs.js +216 -0
  103. package/dist/chunk-83kmfcjv.js +256 -0
  104. package/dist/chunk-846rr9n1.js +107 -0
  105. package/dist/chunk-84ncsm1r.js +183 -0
  106. package/dist/chunk-867x8aq0.js +8936 -0
  107. package/dist/chunk-8byh30kb.js +1947 -0
  108. package/dist/chunk-8c8f6gnt.js +432 -0
  109. package/dist/chunk-8gtdseev.js +454 -0
  110. package/dist/chunk-8jfh9rq6.js +642 -0
  111. package/dist/chunk-8n4n4m67.js +800 -0
  112. package/dist/chunk-8za61tze.js +847 -0
  113. package/dist/chunk-9029sbq1.js +57 -0
  114. package/dist/chunk-94dm5rrm.js +673 -0
  115. package/dist/chunk-9bs8n985.js +329 -0
  116. package/dist/chunk-9c23776j.js +763 -0
  117. package/dist/chunk-9e93g81n.js +298 -0
  118. package/dist/chunk-9f3d61y7.js +548 -0
  119. package/dist/chunk-9gc3andd.js +422 -0
  120. package/dist/chunk-9kn3tgpb.js +130 -0
  121. package/dist/chunk-9m5rn7hk.js +61 -0
  122. package/dist/chunk-9p4hsd6a.js +50 -0
  123. package/dist/chunk-9qasfk8n.js +758 -0
  124. package/dist/chunk-9snp5mn2.js +533 -0
  125. package/dist/chunk-9tcvras3.js +2331 -0
  126. package/dist/chunk-a0186ngk.js +57 -0
  127. package/dist/chunk-a2m8f0aj.js +268 -0
  128. package/dist/chunk-a2rcafav.js +716 -0
  129. package/dist/chunk-a9hjdzar.js +160 -0
  130. package/dist/chunk-aak6ts5n.js +526 -0
  131. package/dist/chunk-aca3w84n.js +267 -0
  132. package/dist/chunk-ae76ded0.js +30 -0
  133. package/dist/chunk-afnjhn3j.js +21933 -0
  134. package/dist/chunk-ahj70tf0.js +880 -0
  135. package/dist/chunk-apjsxssq.js +169 -0
  136. package/dist/chunk-av49wjj1.js +43 -0
  137. package/dist/chunk-axggebfy.js +206 -0
  138. package/dist/chunk-az7jpbv8.js +16 -0
  139. package/dist/chunk-azz7sep6.js +328 -0
  140. package/dist/chunk-b4tpz2g1.js +93 -0
  141. package/dist/chunk-bczf2eyq.js +115 -0
  142. package/dist/chunk-bd95f637.js +208 -0
  143. package/dist/chunk-bdhdmkya.js +10 -0
  144. package/dist/chunk-bp0ynk17.js +32 -0
  145. package/dist/chunk-bq75gxjs.js +90 -0
  146. package/dist/chunk-btk5jaq6.js +10464 -0
  147. package/dist/chunk-bv4c48a5.js +120 -0
  148. package/dist/chunk-byfb105n.js +341 -0
  149. package/dist/chunk-c0bdmy7w.js +4223 -0
  150. package/dist/chunk-c20aqkz8.js +641 -0
  151. package/dist/chunk-c4jg3s2c.js +163 -0
  152. package/dist/chunk-c61q5cer.js +258 -0
  153. package/dist/chunk-c9f761sy.js +386 -0
  154. package/dist/chunk-ca6jkz06.js +157 -0
  155. package/dist/chunk-ccyg9ap9.js +171374 -0
  156. package/dist/chunk-cfej8cc7.js +371 -0
  157. package/dist/chunk-cjqxdnf9.js +23 -0
  158. package/dist/chunk-ckrs789w.js +8 -0
  159. package/dist/chunk-cqeq13wg.js +48 -0
  160. package/dist/chunk-crfj3w5e.js +22821 -0
  161. package/dist/chunk-ct5x6z7g.js +8066 -0
  162. package/dist/chunk-cv5h8n8c.js +101 -0
  163. package/dist/chunk-cwe8h159.js +1563 -0
  164. package/dist/chunk-cwm234zz.js +908 -0
  165. package/dist/chunk-d1jkfp45.js +1580 -0
  166. package/dist/chunk-d3hb1qdr.js +126 -0
  167. package/dist/chunk-d70d0zer.js +713 -0
  168. package/dist/chunk-d91tx29f.js +105 -0
  169. package/dist/chunk-d952pymh.js +20 -0
  170. package/dist/chunk-d9af3z8k.js +720 -0
  171. package/dist/chunk-da1n53c2.js +47 -0
  172. package/dist/chunk-df5c1x8m.js +732 -0
  173. package/dist/chunk-dkv64xys.js +71 -0
  174. package/dist/chunk-dm7166v6.js +251 -0
  175. package/dist/chunk-dr0y5a61.js +258 -0
  176. package/dist/chunk-drzb0rrd.js +306 -0
  177. package/dist/chunk-dw1v1q7w.js +37 -0
  178. package/dist/chunk-e224qet4.js +348 -0
  179. package/dist/chunk-e50ckbv0.js +1099 -0
  180. package/dist/chunk-e5gn6by6.js +1165 -0
  181. package/dist/chunk-e7m3f74m.js +37 -0
  182. package/dist/chunk-e8ghgwaj.js +295 -0
  183. package/dist/chunk-ed8k4ya2.js +41 -0
  184. package/dist/chunk-eh0vnqdz.js +76 -0
  185. package/dist/chunk-epwrzr35.js +4301 -0
  186. package/dist/chunk-er9h6sw5.js +5379 -0
  187. package/dist/chunk-eta5aekm.js +79 -0
  188. package/dist/chunk-ev5gxscq.js +63 -0
  189. package/dist/chunk-evp72hv5.js +212 -0
  190. package/dist/chunk-ex41stfq.js +127 -0
  191. package/dist/chunk-ezpa510h.js +62 -0
  192. package/dist/chunk-f0fm6dey.js +477 -0
  193. package/dist/chunk-f239sbhc.js +152 -0
  194. package/dist/chunk-f2bj47xf.js +109 -0
  195. package/dist/chunk-f4t24rq4.js +258 -0
  196. package/dist/chunk-f9ghvzy8.js +106 -0
  197. package/dist/chunk-f9rahzgr.js +99 -0
  198. package/dist/chunk-ff75qzty.js +521 -0
  199. package/dist/chunk-fj0ctt6q.js +264 -0
  200. package/dist/chunk-fj7wxdt3.js +221 -0
  201. package/dist/chunk-fnnpqv92.js +714 -0
  202. package/dist/chunk-fpd3zzx1.js +26696 -0
  203. package/dist/chunk-fqv2cn76.js +227 -0
  204. package/dist/chunk-fqw9j3bj.js +439 -0
  205. package/dist/chunk-frbcqhz0.js +4984 -0
  206. package/dist/chunk-fzkj59sg.js +174 -0
  207. package/dist/chunk-fzpzbpbw.js +248 -0
  208. package/dist/chunk-g52cpmd1.js +686 -0
  209. package/dist/chunk-g98m2qe6.js +31 -0
  210. package/dist/chunk-g9zgq4vy.js +715 -0
  211. package/dist/chunk-gbpt7tm8.js +687 -0
  212. package/dist/chunk-gg52jka8.js +373 -0
  213. package/dist/chunk-gjttphax.js +5793 -0
  214. package/dist/chunk-gs7vjaas.js +65 -0
  215. package/dist/chunk-gv8n85j2.js +8 -0
  216. package/dist/chunk-gxdwm6pt.js +650 -0
  217. package/dist/chunk-gy8wajg2.js +1014 -0
  218. package/dist/chunk-gz3647m0.js +200 -0
  219. package/dist/chunk-gzg07mqh.js +16 -0
  220. package/dist/chunk-h3zc60tq.js +44 -0
  221. package/dist/chunk-h4p1qt16.js +74 -0
  222. package/dist/chunk-h8219f18.js +282 -0
  223. package/dist/chunk-h9agq92v.js +331 -0
  224. package/dist/chunk-hhjtpwbj.js +16 -0
  225. package/dist/chunk-hpgpwzra.js +548 -0
  226. package/dist/chunk-hsnjvn19.js +80 -0
  227. package/dist/chunk-hsp9qrry.js +417 -0
  228. package/dist/chunk-hwz6aq2m.js +3939 -0
  229. package/dist/chunk-hzph0hbh.js +272 -0
  230. package/dist/chunk-hzqkss6v.js +153 -0
  231. package/dist/chunk-j0t31f39.js +1149 -0
  232. package/dist/chunk-j1qm6n1v.js +30 -0
  233. package/dist/chunk-j6e4b522.js +81 -0
  234. package/dist/chunk-j7qfbvxk.js +84 -0
  235. package/dist/chunk-j7qv3hvm.js +1635 -0
  236. package/dist/chunk-j8mxc6k6.js +213 -0
  237. package/dist/chunk-jevj87jn.js +224 -0
  238. package/dist/chunk-jk2ps88q.js +815 -0
  239. package/dist/chunk-jz7tbdyv.js +1599 -0
  240. package/dist/chunk-k36jpjvh.js +300 -0
  241. package/dist/chunk-k4nmrt3w.js +61 -0
  242. package/dist/chunk-kavn03r9.js +16606 -0
  243. package/dist/chunk-kkgav8dm.js +54 -0
  244. package/dist/chunk-kkq26g5c.js +33 -0
  245. package/dist/chunk-kp6nepx4.js +106 -0
  246. package/dist/chunk-ksefybc8.js +1551 -0
  247. package/dist/chunk-kv147680.js +3436 -0
  248. package/dist/chunk-kya46axt.js +833 -0
  249. package/dist/chunk-kyz233ny.js +227 -0
  250. package/dist/chunk-kzs75xmj.js +143 -0
  251. package/dist/chunk-m0vrez9w.js +266 -0
  252. package/dist/chunk-m1wadav3.js +118 -0
  253. package/dist/chunk-m4rfx3cj.js +221 -0
  254. package/dist/chunk-mc9zaggs.js +6374 -0
  255. package/dist/chunk-mcg5ttj4.js +105 -0
  256. package/dist/chunk-mf4r7918.js +63 -0
  257. package/dist/chunk-mh9khrt4.js +286 -0
  258. package/dist/chunk-mhc4szw7.js +22 -0
  259. package/dist/chunk-mkq0yzp0.js +38 -0
  260. package/dist/chunk-mr58jv4w.js +256 -0
  261. package/dist/chunk-mrrx3bmt.js +168 -0
  262. package/dist/chunk-mtyk3zz6.js +87 -0
  263. package/dist/chunk-mvgxntv6.js +62 -0
  264. package/dist/chunk-mwnjydcm.js +102 -0
  265. package/dist/chunk-mwxt0m3f.js +862 -0
  266. package/dist/chunk-mz1pxck8.js +998 -0
  267. package/dist/chunk-n3agghys.js +214 -0
  268. package/dist/chunk-n6q02ya9.js +442 -0
  269. package/dist/chunk-nt3y91vh.js +443 -0
  270. package/dist/chunk-nt837qt9.js +21 -0
  271. package/dist/chunk-ntgmegfs.js +39 -0
  272. package/dist/chunk-nwk16bbd.js +30 -0
  273. package/dist/chunk-p367ay90.js +672 -0
  274. package/dist/chunk-p7m3x9qk.js +48 -0
  275. package/dist/chunk-pagmjwp5.js +132 -0
  276. package/dist/chunk-pbd4r8ek.js +161 -0
  277. package/dist/chunk-pdkpssgv.js +2422 -0
  278. package/dist/chunk-pf6z1e35.js +32 -0
  279. package/dist/chunk-pfzejvpt.js +213 -0
  280. package/dist/chunk-pktxyhvk.js +400 -0
  281. package/dist/chunk-pp5xhveq.js +124 -0
  282. package/dist/chunk-ppnd7a8x.js +38 -0
  283. package/dist/chunk-pqh2w7dr.js +2202 -0
  284. package/dist/chunk-pr878d0z.js +240 -0
  285. package/dist/chunk-psf0y7hy.js +140 -0
  286. package/dist/chunk-pz2zz2f7.js +1586 -0
  287. package/dist/chunk-q0xkrxy8.js +890 -0
  288. package/dist/chunk-q5b0kpr3.js +14369 -0
  289. package/dist/chunk-q7z3t531.js +334 -0
  290. package/dist/chunk-qdjjtgwt.js +3183 -0
  291. package/dist/chunk-qezv7msv.js +26 -0
  292. package/dist/chunk-qmxn7f86.js +2643 -0
  293. package/dist/chunk-qqc3b97c.js +15 -0
  294. package/dist/chunk-qwrp63wh.js +145 -0
  295. package/dist/chunk-qyvqbst3.js +537 -0
  296. package/dist/chunk-qztvd4hd.js +465 -0
  297. package/dist/chunk-r0bvez4y.js +235 -0
  298. package/dist/chunk-r3z0896k.js +2831 -0
  299. package/dist/chunk-r4cxb6t7.js +32 -0
  300. package/dist/chunk-rb8k68m7.js +118 -0
  301. package/dist/chunk-rdprgm4t.js +42 -0
  302. package/dist/chunk-rex82hys.js +1710 -0
  303. package/dist/chunk-rjjakkw2.js +2560 -0
  304. package/dist/chunk-rka6gcv3.js +304 -0
  305. package/dist/chunk-rkz12ghm.js +144 -0
  306. package/dist/chunk-rnc7m1qs.js +436 -0
  307. package/dist/chunk-rx6z23h0.js +165 -0
  308. package/dist/chunk-s76582j1.js +28 -0
  309. package/dist/chunk-sez03qd9.js +7140 -0
  310. package/dist/chunk-sjvdn2ep.js +130 -0
  311. package/dist/chunk-smwhyy8p.js +115 -0
  312. package/dist/chunk-snw7nh0d.js +695 -0
  313. package/dist/chunk-sqx9c057.js +193 -0
  314. package/dist/chunk-sscms68s.js +16 -0
  315. package/dist/chunk-stknnmsb.js +272 -0
  316. package/dist/chunk-sywdxbs6.js +853 -0
  317. package/dist/chunk-syxy4pf2.js +782 -0
  318. package/dist/chunk-t0hpqsqn.js +6157 -0
  319. package/dist/chunk-tjm70vnw.js +123 -0
  320. package/dist/chunk-trzh0msn.js +154 -0
  321. package/dist/chunk-v1z17cpg.js +723 -0
  322. package/dist/chunk-vsfj449x.js +333 -0
  323. package/dist/chunk-vvkq20tt.js +287 -0
  324. package/dist/chunk-vxgdzx6p.js +338 -0
  325. package/dist/chunk-vxqhjyfz.js +15 -0
  326. package/dist/chunk-vzsstfmb.js +80 -0
  327. package/dist/chunk-w1jew5sn.js +69 -0
  328. package/dist/chunk-w3kwr76v.js +789 -0
  329. package/dist/chunk-w40netr9.js +59 -0
  330. package/dist/chunk-w99cpfdg.js +559 -0
  331. package/dist/chunk-wacn14d2.js +271 -0
  332. package/dist/chunk-wbhrqrq3.js +3033 -0
  333. package/dist/chunk-wfg9g0p7.js +17612 -0
  334. package/dist/chunk-wj3vjsbx.js +93 -0
  335. package/dist/chunk-wjhq855a.js +372 -0
  336. package/dist/chunk-wr06gqxh.js +114 -0
  337. package/dist/chunk-ws0z2y1g.js +195 -0
  338. package/dist/chunk-wt62wqcj.js +98 -0
  339. package/dist/chunk-wx4v7ddx.js +42 -0
  340. package/dist/chunk-wy0t3vb2.js +6101 -0
  341. package/dist/chunk-wysz7qk4.js +280 -0
  342. package/dist/chunk-x63fx1vd.js +192 -0
  343. package/dist/chunk-x8b7vft8.js +132 -0
  344. package/dist/chunk-x8jhkgxb.js +346 -0
  345. package/dist/chunk-x9z4q5k5.js +275 -0
  346. package/dist/chunk-xjd7e9jq.js +126 -0
  347. package/dist/chunk-xjr0n27e.js +42 -0
  348. package/dist/chunk-xpwyw7cd.js +24 -0
  349. package/dist/chunk-xw4ycnyz.js +37 -0
  350. package/dist/chunk-y66bqywr.js +17303 -0
  351. package/dist/chunk-ycarry7d.js +157 -0
  352. package/dist/chunk-ycr0hp6v.js +1486 -0
  353. package/dist/chunk-yqmaw6hf.js +496 -0
  354. package/dist/chunk-yrtm7d23.js +602 -0
  355. package/dist/chunk-yts879rw.js +48 -0
  356. package/dist/chunk-yvmhx96e.js +347 -0
  357. package/dist/chunk-ywq00rg4.js +246 -0
  358. package/dist/chunk-yygeg5mj.js +752 -0
  359. package/dist/chunk-z0exw850.js +726 -0
  360. package/dist/chunk-z2dp53wn.js +17 -0
  361. package/dist/chunk-z4rzc9nd.js +103 -0
  362. package/dist/chunk-zb0akt77.js +684 -0
  363. package/dist/chunk-zb2xrj5t.js +1789 -0
  364. package/dist/chunk-zbptn0ky.js +423 -0
  365. package/dist/chunk-zd45wbmf.js +1090 -0
  366. package/dist/chunk-zjkvspz9.js +2050 -0
  367. package/dist/chunk-zke1sp3x.js +1524 -0
  368. package/dist/chunk-zv2cvfsv.js +58 -0
  369. package/dist/chunk-zy4tmqst.js +644 -0
  370. package/dist/chunk-zygzzzvk.js +192 -0
  371. package/dist/cli-21v3v6ny.md +1 -0
  372. package/dist/cli.js +246 -0
  373. package/dist/server-n5f2q89z.md +1 -0
  374. package/package.json +161 -0
@@ -0,0 +1,1524 @@
1
+ // @bun
2
+ import {
3
+ FlushGate,
4
+ checkEnvLessBridgeMinVersion,
5
+ createV1ReplTransport,
6
+ createV2ReplTransport
7
+ } from "./chunk-6350958y.js";
8
+ import {
9
+ HybridTransport
10
+ } from "./chunk-g52cpmd1.js";
11
+ import"./chunk-3mhygd2v.js";
12
+ import {
13
+ BoundedUUIDSet,
14
+ extractTitleText,
15
+ handleIngressMessage,
16
+ handleServerControlRequest,
17
+ isEligibleBridgeMessage,
18
+ makeResultMessage
19
+ } from "./chunk-7be87rww.js";
20
+ import"./chunk-nt837qt9.js";
21
+ import {
22
+ createCapacityWake
23
+ } from "./chunk-ae76ded0.js";
24
+ import {
25
+ buildCCRv2SdkUrl,
26
+ buildSdkUrl,
27
+ decodeWorkSecret,
28
+ sameSessionId
29
+ } from "./chunk-gs7vjaas.js";
30
+ import {
31
+ DEFAULT_POLL_CONFIG,
32
+ getPollIntervalConfig
33
+ } from "./chunk-w40netr9.js";
34
+ import"./chunk-f239sbhc.js";
35
+ import {
36
+ init_mappers,
37
+ toSDKMessages
38
+ } from "./chunk-fqv2cn76.js";
39
+ import {
40
+ extractConversationText,
41
+ generateSessionTitle,
42
+ init_sessionTitle
43
+ } from "./chunk-xjd7e9jq.js";
44
+ import {
45
+ init_sessionIngressAuth,
46
+ updateSessionIngressAuthToken
47
+ } from "./chunk-jevj87jn.js";
48
+ import"./chunk-qztvd4hd.js";
49
+ import"./chunk-q0xkrxy8.js";
50
+ import"./chunk-52dzw4bc.js";
51
+ import"./chunk-n6q02ya9.js";
52
+ import"./chunk-b4tpz2g1.js";
53
+ import"./chunk-n3agghys.js";
54
+ import"./chunk-f9rahzgr.js";
55
+ import {
56
+ describeAxiosError,
57
+ extractHttpStatus,
58
+ init_debugUtils,
59
+ logBridgeSkip,
60
+ setCseShimGate,
61
+ toCompatSessionId,
62
+ toInfraSessionId
63
+ } from "./chunk-ex41stfq.js";
64
+ import"./chunk-8n4n4m67.js";
65
+ import"./chunk-xjr0n27e.js";
66
+ import"./chunk-0yz17yjy.js";
67
+ import"./chunk-9m5rn7hk.js";
68
+ import"./chunk-19jvvqzp.js";
69
+ import"./chunk-2n0s2dhc.js";
70
+ import"./chunk-epwrzr35.js";
71
+ import"./chunk-1ztm9yps.js";
72
+ import"./chunk-78n9kfp8.js";
73
+ import"./chunk-j8mxc6k6.js";
74
+ import"./chunk-z0exw850.js";
75
+ import"./chunk-3jf3k40v.js";
76
+ import"./chunk-yvmhx96e.js";
77
+ import"./chunk-qezv7msv.js";
78
+ import"./chunk-sscms68s.js";
79
+ import"./chunk-7e1qjk3s.js";
80
+ import"./chunk-1gjysfnf.js";
81
+ import"./chunk-vxgdzx6p.js";
82
+ import"./chunk-kv147680.js";
83
+ import"./chunk-2p0hvt8k.js";
84
+ import"./chunk-ycr0hp6v.js";
85
+ import"./chunk-zb2xrj5t.js";
86
+ import"./chunk-9029sbq1.js";
87
+ import {
88
+ init_analytics,
89
+ logEvent
90
+ } from "./chunk-ezpa510h.js";
91
+ import"./chunk-kp6nepx4.js";
92
+ import"./chunk-1jjzp2pa.js";
93
+ import"./chunk-w1jew5sn.js";
94
+ import"./chunk-g98m2qe6.js";
95
+ import"./chunk-sez03qd9.js";
96
+ import {
97
+ init_displayTags,
98
+ stripDisplayTagsAllowEmpty
99
+ } from "./chunk-vsfj449x.js";
100
+ import"./chunk-r4cxb6t7.js";
101
+ import"./chunk-bp0ynk17.js";
102
+ import"./chunk-7yexhdjs.js";
103
+ import {
104
+ errorMessage,
105
+ init_cleanupRegistry,
106
+ init_debug,
107
+ init_errors,
108
+ logForDebugging,
109
+ registerCleanup
110
+ } from "./chunk-rex82hys.js";
111
+ import {
112
+ init_envUtils,
113
+ isEnvTruthy,
114
+ isInProtectedNamespace
115
+ } from "./chunk-4s93jyky.js";
116
+ import"./chunk-318g78ty.js";
117
+ import"./chunk-c0bdmy7w.js";
118
+ import"./chunk-syxy4pf2.js";
119
+ import {
120
+ __require,
121
+ __toESM
122
+ } from "./chunk-eta5aekm.js";
123
+ import {
124
+ archiveBridgeSession,
125
+ createBridgeSession,
126
+ init_createSession,
127
+ updateBridgeSessionTitle
128
+ } from "./chunk-fj0ctt6q.js";
129
+ import {
130
+ getBridgeAccessToken,
131
+ getBridgeBaseUrl,
132
+ getBridgeTokenOverride,
133
+ init_bridgeConfig
134
+ } from "./chunk-eh0vnqdz.js";
135
+ import {
136
+ checkBridgeMinVersion,
137
+ init_bridgeEnabled,
138
+ isBridgeEnabledBlocking,
139
+ isCseShimEnabled,
140
+ isEnvLessBridgeEnabled
141
+ } from "./chunk-5f5sxgp0.js";
142
+ import {
143
+ BridgeFatalError,
144
+ clearBridgeDebugHandle,
145
+ createBridgeApiClient,
146
+ generateShortWordSlug,
147
+ getContentText,
148
+ getCurrentSessionTitle,
149
+ getMessagesAfterCompactBoundary,
150
+ init_bridgeApi,
151
+ init_bridgeDebug,
152
+ init_concurrentSessions,
153
+ init_messages,
154
+ init_policyLimits,
155
+ init_sessionStorage,
156
+ init_words,
157
+ injectBridgeFault,
158
+ isExpiredErrorType,
159
+ isPolicyAllowed,
160
+ isSuppressible403,
161
+ isSyntheticMessage,
162
+ registerBridgeDebugHandle,
163
+ updateSessionBridgeId,
164
+ validateBridgeId,
165
+ waitForPolicyLimitsToLoad,
166
+ wrapApiForFaultInjection
167
+ } from "./chunk-ccyg9ap9.js";
168
+ import"./chunk-846rr9n1.js";
169
+ import"./chunk-fnnpqv92.js";
170
+ import"./chunk-2yqy25z4.js";
171
+ import {
172
+ getTrustedDeviceToken,
173
+ init_trustedDevice
174
+ } from "./chunk-zygzzzvk.js";
175
+ import"./chunk-evp72hv5.js";
176
+ import"./chunk-jz7tbdyv.js";
177
+ import"./chunk-vxqhjyfz.js";
178
+ import"./chunk-mf4r7918.js";
179
+ import"./chunk-sywdxbs6.js";
180
+ import"./chunk-cjqxdnf9.js";
181
+ import"./chunk-9qasfk8n.js";
182
+ import"./chunk-fpd3zzx1.js";
183
+ import"./chunk-bv4c48a5.js";
184
+ import"./chunk-6jta29r1.js";
185
+ import"./chunk-z4rzc9nd.js";
186
+ import"./chunk-9bs8n985.js";
187
+ import"./chunk-6xqp51qr.js";
188
+ import"./chunk-35dw2r9g.js";
189
+ import {
190
+ checkAndRefreshOAuthTokenIfNeeded,
191
+ getClaudeAIOAuthTokens,
192
+ getFeatureValue_CACHED_WITH_REFRESH,
193
+ getGlobalConfig,
194
+ getOrganizationUUID,
195
+ handleOAuth401Error,
196
+ init_auth,
197
+ init_client,
198
+ init_config1 as init_config,
199
+ init_growthbook,
200
+ saveGlobalConfig,
201
+ sleep
202
+ } from "./chunk-y66bqywr.js";
203
+ import"./chunk-nwk16bbd.js";
204
+ import"./chunk-rx6z23h0.js";
205
+ import"./chunk-df5c1x8m.js";
206
+ import"./chunk-qwrp63wh.js";
207
+ import {
208
+ getBranch,
209
+ getRemoteUrl,
210
+ init_diagLogs,
211
+ init_git,
212
+ logForDiagnosticsNoPII
213
+ } from "./chunk-65z8hg8j.js";
214
+ import"./chunk-5cp2q9sh.js";
215
+ import {
216
+ getOriginalCwd,
217
+ getSessionId,
218
+ init_state
219
+ } from "./chunk-rjjakkw2.js";
220
+ import"./chunk-0sbddf6m.js";
221
+ import"./chunk-q5b0kpr3.js";
222
+
223
+ // src/bridge/initReplBridge.ts
224
+ init_state();
225
+ init_growthbook();
226
+ init_client();
227
+ init_policyLimits();
228
+ init_auth();
229
+ init_config();
230
+ init_debug();
231
+ init_displayTags();
232
+ init_errors();
233
+ init_git();
234
+ init_mappers();
235
+ init_messages();
236
+ init_sessionStorage();
237
+ init_sessionTitle();
238
+ init_words();
239
+ init_bridgeConfig();
240
+ init_bridgeEnabled();
241
+ init_createSession();
242
+ init_debugUtils();
243
+ import { hostname } from "os";
244
+
245
+ // src/bridge/replBridge.ts
246
+ init_bridgeApi();
247
+ init_debug();
248
+ init_diagLogs();
249
+ init_analytics();
250
+ init_cleanupRegistry();
251
+ import { randomUUID } from "crypto";
252
+ init_concurrentSessions();
253
+ init_trustedDevice();
254
+ init_sessionIngressAuth();
255
+ init_envUtils();
256
+ init_bridgeApi();
257
+ init_debugUtils();
258
+ init_errors();
259
+ init_bridgeDebug();
260
+ var POLL_ERROR_INITIAL_DELAY_MS = 2000;
261
+ var POLL_ERROR_MAX_DELAY_MS = 60000;
262
+ var POLL_ERROR_GIVE_UP_MS = 15 * 60 * 1000;
263
+ var initSequence = 0;
264
+ async function initBridgeCore(params) {
265
+ const {
266
+ dir,
267
+ machineName,
268
+ branch,
269
+ gitRepoUrl,
270
+ title,
271
+ baseUrl,
272
+ sessionIngressUrl,
273
+ workerType,
274
+ getAccessToken,
275
+ createSession,
276
+ archiveSession,
277
+ getCurrentTitle = () => title,
278
+ toSDKMessages: toSDKMessages2 = () => {
279
+ 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.");
280
+ },
281
+ onAuth401,
282
+ getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG,
283
+ initialHistoryCap = 200,
284
+ initialMessages,
285
+ previouslyFlushedUUIDs,
286
+ onInboundMessage,
287
+ onPermissionResponse,
288
+ onInterrupt,
289
+ onSetModel,
290
+ onSetMaxThinkingTokens,
291
+ onSetPermissionMode,
292
+ onStateChange,
293
+ onUserMessage,
294
+ perpetual,
295
+ initialSSESequenceNum = 0
296
+ } = params;
297
+ const seq = ++initSequence;
298
+ const { writeBridgePointer, clearBridgePointer, readBridgePointer } = await import("./chunk-kzs75xmj.js");
299
+ const rawPrior = perpetual ? await readBridgePointer(dir) : null;
300
+ const prior = rawPrior?.source === "repl" ? rawPrior : null;
301
+ logForDebugging(`[bridge:repl] initBridgeCore #${seq} starting (initialMessages=${initialMessages?.length ?? 0}${prior ? ` perpetual prior=env:${prior.environmentId}` : ""})`);
302
+ const rawApi = createBridgeApiClient({
303
+ baseUrl,
304
+ getAccessToken,
305
+ runnerVersion: MACRO.VERSION,
306
+ onDebug: logForDebugging,
307
+ onAuth401,
308
+ getTrustedDeviceToken
309
+ });
310
+ const api = process.env.USER_TYPE === "ant" ? wrapApiForFaultInjection(rawApi) : rawApi;
311
+ const bridgeConfig = {
312
+ dir,
313
+ machineName,
314
+ branch,
315
+ gitRepoUrl,
316
+ maxSessions: 1,
317
+ spawnMode: "single-session",
318
+ verbose: false,
319
+ sandbox: false,
320
+ bridgeId: randomUUID(),
321
+ workerType,
322
+ environmentId: randomUUID(),
323
+ reuseEnvironmentId: prior?.environmentId,
324
+ apiBaseUrl: baseUrl,
325
+ sessionIngressUrl
326
+ };
327
+ let environmentId;
328
+ let environmentSecret;
329
+ try {
330
+ const reg = await api.registerBridgeEnvironment(bridgeConfig);
331
+ environmentId = reg.environment_id;
332
+ environmentSecret = reg.environment_secret;
333
+ } catch (err) {
334
+ logBridgeSkip("registration_failed", `[bridge:repl] Environment registration failed: ${errorMessage(err)}`);
335
+ if (prior) {
336
+ await clearBridgePointer(dir);
337
+ }
338
+ onStateChange?.("failed", errorMessage(err));
339
+ return null;
340
+ }
341
+ logForDebugging(`[bridge:repl] Environment registered: ${environmentId}`);
342
+ logForDiagnosticsNoPII("info", "bridge_repl_env_registered");
343
+ logEvent("tengu_bridge_repl_env_registered", {});
344
+ async function tryReconnectInPlace(requestedEnvId, sessionId) {
345
+ if (environmentId !== requestedEnvId) {
346
+ logForDebugging(`[bridge:repl] Env mismatch (requested ${requestedEnvId}, got ${environmentId}) \u2014 cannot reconnect in place`);
347
+ return false;
348
+ }
349
+ const infraId = toInfraSessionId(sessionId);
350
+ const candidates = infraId === sessionId ? [sessionId] : [sessionId, infraId];
351
+ for (const id of candidates) {
352
+ try {
353
+ await api.reconnectSession(environmentId, id);
354
+ logForDebugging(`[bridge:repl] Reconnected session ${id} in place on env ${environmentId}`);
355
+ return true;
356
+ } catch (err) {
357
+ logForDebugging(`[bridge:repl] reconnectSession(${id}) failed: ${errorMessage(err)}`);
358
+ }
359
+ }
360
+ logForDebugging("[bridge:repl] reconnectSession exhausted \u2014 falling through to fresh session");
361
+ return false;
362
+ }
363
+ const reusedPriorSession = prior ? await tryReconnectInPlace(prior.environmentId, prior.sessionId) : false;
364
+ if (prior && !reusedPriorSession) {
365
+ await clearBridgePointer(dir);
366
+ }
367
+ let currentSessionId;
368
+ if (reusedPriorSession && prior) {
369
+ currentSessionId = prior.sessionId;
370
+ logForDebugging(`[bridge:repl] Perpetual session reused: ${currentSessionId}`);
371
+ if (initialMessages && previouslyFlushedUUIDs) {
372
+ for (const msg of initialMessages) {
373
+ previouslyFlushedUUIDs.add(msg.uuid);
374
+ }
375
+ }
376
+ } else {
377
+ const createdSessionId = await createSession({
378
+ environmentId,
379
+ title,
380
+ gitRepoUrl,
381
+ branch,
382
+ signal: AbortSignal.timeout(15000)
383
+ });
384
+ if (!createdSessionId) {
385
+ logForDebugging("[bridge:repl] Session creation failed, deregistering environment");
386
+ logEvent("tengu_bridge_repl_session_failed", {});
387
+ await api.deregisterEnvironment(environmentId).catch(() => {});
388
+ onStateChange?.("failed", "Session creation failed");
389
+ return null;
390
+ }
391
+ currentSessionId = createdSessionId;
392
+ logForDebugging(`[bridge:repl] Session created: ${currentSessionId}`);
393
+ }
394
+ await writeBridgePointer(dir, {
395
+ sessionId: currentSessionId,
396
+ environmentId,
397
+ source: "repl"
398
+ });
399
+ logForDiagnosticsNoPII("info", "bridge_repl_session_created");
400
+ logEvent("tengu_bridge_repl_started", {
401
+ has_initial_messages: !!(initialMessages && initialMessages.length > 0),
402
+ inProtectedNamespace: isInProtectedNamespace()
403
+ });
404
+ const initialMessageUUIDs = new Set;
405
+ if (initialMessages) {
406
+ for (const msg of initialMessages) {
407
+ initialMessageUUIDs.add(msg.uuid);
408
+ }
409
+ }
410
+ const recentPostedUUIDs = new BoundedUUIDSet(2000);
411
+ for (const uuid of initialMessageUUIDs) {
412
+ recentPostedUUIDs.add(uuid);
413
+ }
414
+ const recentInboundUUIDs = new BoundedUUIDSet(2000);
415
+ const pollController = new AbortController;
416
+ let transport = null;
417
+ let v2Generation = 0;
418
+ let lastTransportSequenceNum = reusedPriorSession ? initialSSESequenceNum : 0;
419
+ let currentWorkId = null;
420
+ let currentIngressToken = null;
421
+ const capacityWake = createCapacityWake(pollController.signal);
422
+ const wakePollLoop = capacityWake.wake;
423
+ const capacitySignal = capacityWake.signal;
424
+ const flushGate = new FlushGate;
425
+ let userMessageCallbackDone = !onUserMessage;
426
+ const MAX_ENVIRONMENT_RECREATIONS = 3;
427
+ let environmentRecreations = 0;
428
+ let reconnectPromise = null;
429
+ async function reconnectEnvironmentWithSession() {
430
+ if (reconnectPromise) {
431
+ return reconnectPromise;
432
+ }
433
+ reconnectPromise = doReconnect();
434
+ try {
435
+ return await reconnectPromise;
436
+ } finally {
437
+ reconnectPromise = null;
438
+ }
439
+ }
440
+ async function doReconnect() {
441
+ environmentRecreations++;
442
+ v2Generation++;
443
+ logForDebugging(`[bridge:repl] Reconnecting after env lost (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`);
444
+ if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) {
445
+ logForDebugging(`[bridge:repl] Environment reconnect limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`);
446
+ return false;
447
+ }
448
+ if (transport) {
449
+ const seq2 = transport.getLastSequenceNum();
450
+ if (seq2 > lastTransportSequenceNum) {
451
+ lastTransportSequenceNum = seq2;
452
+ }
453
+ transport.close();
454
+ transport = null;
455
+ }
456
+ wakePollLoop();
457
+ flushGate.drop();
458
+ if (currentWorkId) {
459
+ const workIdBeingCleared = currentWorkId;
460
+ await api.stopWork(environmentId, workIdBeingCleared, false).catch(() => {});
461
+ if (currentWorkId !== workIdBeingCleared) {
462
+ logForDebugging("[bridge:repl] Poll loop recovered during stopWork await \u2014 deferring to it");
463
+ environmentRecreations = 0;
464
+ return true;
465
+ }
466
+ currentWorkId = null;
467
+ currentIngressToken = null;
468
+ }
469
+ if (pollController.signal.aborted) {
470
+ logForDebugging("[bridge:repl] Reconnect aborted by teardown");
471
+ return false;
472
+ }
473
+ const requestedEnvId = environmentId;
474
+ bridgeConfig.reuseEnvironmentId = requestedEnvId;
475
+ try {
476
+ const reg = await api.registerBridgeEnvironment(bridgeConfig);
477
+ environmentId = reg.environment_id;
478
+ environmentSecret = reg.environment_secret;
479
+ } catch (err) {
480
+ bridgeConfig.reuseEnvironmentId = undefined;
481
+ logForDebugging(`[bridge:repl] Environment re-registration failed: ${errorMessage(err)}`);
482
+ return false;
483
+ }
484
+ bridgeConfig.reuseEnvironmentId = undefined;
485
+ logForDebugging(`[bridge:repl] Re-registered: requested=${requestedEnvId} got=${environmentId}`);
486
+ if (pollController.signal.aborted) {
487
+ logForDebugging("[bridge:repl] Reconnect aborted after env registration, cleaning up");
488
+ await api.deregisterEnvironment(environmentId).catch(() => {});
489
+ return false;
490
+ }
491
+ if (transport !== null) {
492
+ logForDebugging("[bridge:repl] Poll loop recovered during registerBridgeEnvironment await \u2014 deferring to it");
493
+ environmentRecreations = 0;
494
+ return true;
495
+ }
496
+ if (await tryReconnectInPlace(requestedEnvId, currentSessionId)) {
497
+ logEvent("tengu_bridge_repl_reconnected_in_place", {});
498
+ environmentRecreations = 0;
499
+ return true;
500
+ }
501
+ if (environmentId !== requestedEnvId) {
502
+ logEvent("tengu_bridge_repl_env_expired_fresh_session", {});
503
+ }
504
+ await archiveSession(currentSessionId);
505
+ if (pollController.signal.aborted) {
506
+ logForDebugging("[bridge:repl] Reconnect aborted after archive, cleaning up");
507
+ await api.deregisterEnvironment(environmentId).catch(() => {});
508
+ return false;
509
+ }
510
+ const currentTitle = getCurrentTitle();
511
+ const newSessionId = await createSession({
512
+ environmentId,
513
+ title: currentTitle,
514
+ gitRepoUrl,
515
+ branch,
516
+ signal: AbortSignal.timeout(15000)
517
+ });
518
+ if (!newSessionId) {
519
+ logForDebugging("[bridge:repl] Session creation failed during reconnection");
520
+ return false;
521
+ }
522
+ if (pollController.signal.aborted) {
523
+ logForDebugging("[bridge:repl] Reconnect aborted after session creation, cleaning up");
524
+ await archiveSession(newSessionId);
525
+ return false;
526
+ }
527
+ currentSessionId = newSessionId;
528
+ updateSessionBridgeId(toCompatSessionId(newSessionId)).catch(() => {});
529
+ lastTransportSequenceNum = 0;
530
+ recentInboundUUIDs.clear();
531
+ userMessageCallbackDone = !onUserMessage;
532
+ logForDebugging(`[bridge:repl] Re-created session: ${currentSessionId}`);
533
+ await writeBridgePointer(dir, {
534
+ sessionId: currentSessionId,
535
+ environmentId,
536
+ source: "repl"
537
+ });
538
+ previouslyFlushedUUIDs?.clear();
539
+ environmentRecreations = 0;
540
+ return true;
541
+ }
542
+ function getOAuthToken() {
543
+ return getAccessToken();
544
+ }
545
+ function drainFlushGate() {
546
+ const msgs = flushGate.end();
547
+ if (msgs.length === 0)
548
+ return;
549
+ if (!transport) {
550
+ logForDebugging(`[bridge:repl] Cannot drain ${msgs.length} pending message(s): no transport`);
551
+ return;
552
+ }
553
+ for (const msg of msgs) {
554
+ recentPostedUUIDs.add(msg.uuid);
555
+ }
556
+ const sdkMessages = toSDKMessages2(msgs);
557
+ const events = sdkMessages.map((sdkMsg) => ({
558
+ ...sdkMsg,
559
+ session_id: currentSessionId
560
+ }));
561
+ logForDebugging(`[bridge:repl] Drained ${msgs.length} pending message(s) after flush`);
562
+ transport.writeBatch(events);
563
+ }
564
+ let doTeardownImpl = null;
565
+ function triggerTeardown() {
566
+ doTeardownImpl?.();
567
+ }
568
+ function handleTransportPermanentClose(closeCode) {
569
+ logForDebugging(`[bridge:repl] Transport permanently closed: code=${closeCode}`);
570
+ logEvent("tengu_bridge_repl_ws_closed", {
571
+ code: closeCode
572
+ });
573
+ if (transport) {
574
+ const closedSeq = transport.getLastSequenceNum();
575
+ if (closedSeq > lastTransportSequenceNum) {
576
+ lastTransportSequenceNum = closedSeq;
577
+ }
578
+ transport = null;
579
+ }
580
+ wakePollLoop();
581
+ const dropped = flushGate.drop();
582
+ if (dropped > 0) {
583
+ logForDebugging(`[bridge:repl] Dropping ${dropped} pending message(s) on transport close (code=${closeCode})`, { level: "warn" });
584
+ }
585
+ if (closeCode === 1000) {
586
+ onStateChange?.("failed", "session ended");
587
+ pollController.abort();
588
+ triggerTeardown();
589
+ return;
590
+ }
591
+ onStateChange?.("reconnecting", `Remote Control connection lost (code ${closeCode})`);
592
+ logForDebugging(`[bridge:repl] Transport reconnect budget exhausted (code=${closeCode}), attempting env reconnect`);
593
+ reconnectEnvironmentWithSession().then((success) => {
594
+ if (success)
595
+ return;
596
+ if (pollController.signal.aborted)
597
+ return;
598
+ logForDebugging("[bridge:repl] reconnectEnvironmentWithSession resolved false \u2014 tearing down");
599
+ logEvent("tengu_bridge_repl_reconnect_failed", {
600
+ close_code: closeCode
601
+ });
602
+ onStateChange?.("failed", "reconnection failed");
603
+ triggerTeardown();
604
+ });
605
+ }
606
+ let sigusr2Handler;
607
+ if (process.env.USER_TYPE === "ant" && process.platform !== "win32") {
608
+ sigusr2Handler = () => {
609
+ logForDebugging("[bridge:repl] SIGUSR2 received \u2014 forcing doReconnect() for testing");
610
+ reconnectEnvironmentWithSession();
611
+ };
612
+ process.on("SIGUSR2", sigusr2Handler);
613
+ }
614
+ let debugFireClose = null;
615
+ if (process.env.USER_TYPE === "ant") {
616
+ registerBridgeDebugHandle({
617
+ fireClose: (code) => {
618
+ if (!debugFireClose) {
619
+ logForDebugging("[bridge:debug] fireClose: no transport wired yet");
620
+ return;
621
+ }
622
+ logForDebugging(`[bridge:debug] fireClose(${code}) \u2014 injecting`);
623
+ debugFireClose(code);
624
+ },
625
+ forceReconnect: () => {
626
+ logForDebugging("[bridge:debug] forceReconnect \u2014 injecting");
627
+ reconnectEnvironmentWithSession();
628
+ },
629
+ injectFault: injectBridgeFault,
630
+ wakePollLoop,
631
+ describe: () => `env=${environmentId} session=${currentSessionId} transport=${transport?.getStateLabel() ?? "null"} workId=${currentWorkId ?? "null"}`
632
+ });
633
+ }
634
+ const pollOpts = {
635
+ api,
636
+ getCredentials: () => ({ environmentId, environmentSecret }),
637
+ signal: pollController.signal,
638
+ getPollIntervalConfig: getPollIntervalConfig2,
639
+ onStateChange,
640
+ getWsState: () => transport?.getStateLabel() ?? "null",
641
+ isAtCapacity: () => transport !== null,
642
+ capacitySignal,
643
+ onFatalError: triggerTeardown,
644
+ getHeartbeatInfo: () => {
645
+ if (!currentWorkId || !currentIngressToken) {
646
+ return null;
647
+ }
648
+ return {
649
+ environmentId,
650
+ workId: currentWorkId,
651
+ sessionToken: currentIngressToken
652
+ };
653
+ },
654
+ onHeartbeatFatal: (err) => {
655
+ logForDebugging(`[bridge:repl] heartbeatWork fatal (status=${err.status}) \u2014 tearing down work item for fast re-dispatch`);
656
+ if (transport) {
657
+ const seq2 = transport.getLastSequenceNum();
658
+ if (seq2 > lastTransportSequenceNum) {
659
+ lastTransportSequenceNum = seq2;
660
+ }
661
+ transport.close();
662
+ transport = null;
663
+ }
664
+ flushGate.drop();
665
+ if (currentWorkId) {
666
+ api.stopWork(environmentId, currentWorkId, false).catch((e) => {
667
+ logForDebugging(`[bridge:repl] stopWork after heartbeat fatal: ${errorMessage(e)}`);
668
+ });
669
+ }
670
+ currentWorkId = null;
671
+ currentIngressToken = null;
672
+ wakePollLoop();
673
+ onStateChange?.("reconnecting", "Work item lease expired, fetching fresh token");
674
+ },
675
+ async onEnvironmentLost() {
676
+ const success = await reconnectEnvironmentWithSession();
677
+ if (!success) {
678
+ return null;
679
+ }
680
+ return { environmentId, environmentSecret };
681
+ },
682
+ onWorkReceived: (workSessionId, ingressToken, workId, serverUseCcrV2) => {
683
+ if (transport?.isConnectedStatus()) {
684
+ logForDebugging(`[bridge:repl] Work received while transport connected, replacing with fresh token (workId=${workId})`);
685
+ }
686
+ logForDebugging(`[bridge:repl] Work received: workId=${workId} workSessionId=${workSessionId} currentSessionId=${currentSessionId} match=${sameSessionId(workSessionId, currentSessionId)}`);
687
+ writeBridgePointer(dir, {
688
+ sessionId: currentSessionId,
689
+ environmentId,
690
+ source: "repl"
691
+ });
692
+ if (!sameSessionId(workSessionId, currentSessionId)) {
693
+ logForDebugging(`[bridge:repl] Rejecting foreign session: expected=${currentSessionId} got=${workSessionId}`);
694
+ return;
695
+ }
696
+ currentWorkId = workId;
697
+ currentIngressToken = ingressToken;
698
+ const useCcrV2 = serverUseCcrV2 || isEnvTruthy(process.env.CLAUDE_BRIDGE_USE_CCR_V2);
699
+ let v1OauthToken;
700
+ if (!useCcrV2) {
701
+ v1OauthToken = getOAuthToken();
702
+ if (!v1OauthToken) {
703
+ logForDebugging("[bridge:repl] No OAuth token available for session ingress, skipping work");
704
+ return;
705
+ }
706
+ updateSessionIngressAuthToken(v1OauthToken);
707
+ }
708
+ logEvent("tengu_bridge_repl_work_received", {});
709
+ if (transport) {
710
+ const oldTransport = transport;
711
+ transport = null;
712
+ const oldSeq = oldTransport.getLastSequenceNum();
713
+ if (oldSeq > lastTransportSequenceNum) {
714
+ lastTransportSequenceNum = oldSeq;
715
+ }
716
+ oldTransport.close();
717
+ }
718
+ flushGate.deactivate();
719
+ const onServerControlRequest = (request) => handleServerControlRequest(request, {
720
+ transport,
721
+ sessionId: currentSessionId,
722
+ onInterrupt,
723
+ onSetModel,
724
+ onSetMaxThinkingTokens,
725
+ onSetPermissionMode
726
+ });
727
+ let initialFlushDone = false;
728
+ const wireTransport = (newTransport) => {
729
+ transport = newTransport;
730
+ newTransport.setOnConnect(() => {
731
+ if (transport !== newTransport)
732
+ return;
733
+ logForDebugging("[bridge:repl] Ingress transport connected");
734
+ logEvent("tengu_bridge_repl_ws_connected", {});
735
+ if (!useCcrV2) {
736
+ const freshToken = getOAuthToken();
737
+ if (freshToken) {
738
+ updateSessionIngressAuthToken(freshToken);
739
+ }
740
+ }
741
+ teardownStarted = false;
742
+ if (!initialFlushDone && initialMessages && initialMessages.length > 0) {
743
+ initialFlushDone = true;
744
+ const historyCap = initialHistoryCap;
745
+ const eligibleMessages = initialMessages.filter((m) => isEligibleBridgeMessage(m) && !previouslyFlushedUUIDs?.has(m.uuid));
746
+ const cappedMessages = historyCap > 0 && eligibleMessages.length > historyCap ? eligibleMessages.slice(-historyCap) : eligibleMessages;
747
+ if (cappedMessages.length < eligibleMessages.length) {
748
+ logForDebugging(`[bridge:repl] Capped initial flush: ${eligibleMessages.length} -> ${cappedMessages.length} (cap=${historyCap})`);
749
+ logEvent("tengu_bridge_repl_history_capped", {
750
+ eligible_count: eligibleMessages.length,
751
+ capped_count: cappedMessages.length
752
+ });
753
+ }
754
+ const sdkMessages = toSDKMessages2(cappedMessages);
755
+ if (sdkMessages.length > 0) {
756
+ logForDebugging(`[bridge:repl] Flushing ${sdkMessages.length} initial message(s) via transport`);
757
+ const events = sdkMessages.map((sdkMsg) => ({
758
+ ...sdkMsg,
759
+ session_id: currentSessionId
760
+ }));
761
+ const dropsBefore = newTransport.droppedBatchCount;
762
+ newTransport.writeBatch(events).then(() => {
763
+ if (newTransport.droppedBatchCount > dropsBefore) {
764
+ logForDebugging(`[bridge:repl] Initial flush dropped ${newTransport.droppedBatchCount - dropsBefore} batch(es) \u2014 not marking ${sdkMessages.length} UUID(s) as flushed`);
765
+ return;
766
+ }
767
+ if (previouslyFlushedUUIDs) {
768
+ for (const sdkMsg of sdkMessages) {
769
+ if (sdkMsg.uuid) {
770
+ previouslyFlushedUUIDs.add(sdkMsg.uuid);
771
+ }
772
+ }
773
+ }
774
+ }).catch((e) => logForDebugging(`[bridge:repl] Initial flush failed: ${e}`)).finally(() => {
775
+ if (transport !== newTransport)
776
+ return;
777
+ drainFlushGate();
778
+ onStateChange?.("connected");
779
+ });
780
+ } else {
781
+ drainFlushGate();
782
+ onStateChange?.("connected");
783
+ }
784
+ } else if (!flushGate.active) {
785
+ onStateChange?.("connected");
786
+ }
787
+ });
788
+ newTransport.setOnData((data) => {
789
+ handleIngressMessage(data, recentPostedUUIDs, recentInboundUUIDs, onInboundMessage, onPermissionResponse, onServerControlRequest);
790
+ });
791
+ debugFireClose = handleTransportPermanentClose;
792
+ newTransport.setOnClose((closeCode) => {
793
+ if (transport !== newTransport)
794
+ return;
795
+ handleTransportPermanentClose(closeCode);
796
+ });
797
+ if (!initialFlushDone && initialMessages && initialMessages.length > 0) {
798
+ flushGate.start();
799
+ }
800
+ newTransport.connect();
801
+ };
802
+ v2Generation++;
803
+ if (useCcrV2) {
804
+ const sessionUrl = buildCCRv2SdkUrl(baseUrl, workSessionId);
805
+ const thisGen = v2Generation;
806
+ logForDebugging(`[bridge:repl] CCR v2: sessionUrl=${sessionUrl} session=${workSessionId} gen=${thisGen}`);
807
+ createV2ReplTransport({
808
+ sessionUrl,
809
+ ingressToken,
810
+ sessionId: workSessionId,
811
+ initialSequenceNum: lastTransportSequenceNum
812
+ }).then((t) => {
813
+ if (pollController.signal.aborted) {
814
+ t.close();
815
+ return;
816
+ }
817
+ if (thisGen !== v2Generation) {
818
+ logForDebugging(`[bridge:repl] CCR v2: discarding stale handshake gen=${thisGen} current=${v2Generation}`);
819
+ t.close();
820
+ return;
821
+ }
822
+ wireTransport(t);
823
+ }, (err) => {
824
+ logForDebugging(`[bridge:repl] CCR v2: createV2ReplTransport failed: ${errorMessage(err)}`, { level: "error" });
825
+ logEvent("tengu_bridge_repl_ccr_v2_init_failed", {});
826
+ if (thisGen !== v2Generation)
827
+ return;
828
+ if (currentWorkId) {
829
+ api.stopWork(environmentId, currentWorkId, false).catch((e) => {
830
+ logForDebugging(`[bridge:repl] stopWork after v2 init failure: ${errorMessage(e)}`);
831
+ });
832
+ currentWorkId = null;
833
+ currentIngressToken = null;
834
+ }
835
+ wakePollLoop();
836
+ });
837
+ } else {
838
+ const wsUrl = buildSdkUrl(sessionIngressUrl, workSessionId);
839
+ logForDebugging(`[bridge:repl] Ingress URL: ${wsUrl}`);
840
+ logForDebugging(`[bridge:repl] Creating HybridTransport: session=${workSessionId}`);
841
+ const oauthToken = v1OauthToken ?? "";
842
+ wireTransport(createV1ReplTransport(new HybridTransport(new URL(wsUrl), {
843
+ Authorization: `Bearer ${oauthToken}`,
844
+ "anthropic-version": "2023-06-01"
845
+ }, workSessionId, () => ({
846
+ Authorization: `Bearer ${getOAuthToken() ?? oauthToken}`,
847
+ "anthropic-version": "2023-06-01"
848
+ }), {
849
+ maxConsecutiveFailures: 50,
850
+ isBridge: true,
851
+ onBatchDropped: () => {
852
+ onStateChange?.("reconnecting", "Lost sync with Remote Control \u2014 events could not be delivered");
853
+ wakePollLoop();
854
+ }
855
+ })));
856
+ }
857
+ }
858
+ };
859
+ startWorkPollLoop(pollOpts);
860
+ const pointerRefreshTimer = perpetual ? setInterval(() => {
861
+ if (reconnectPromise)
862
+ return;
863
+ writeBridgePointer(dir, {
864
+ sessionId: currentSessionId,
865
+ environmentId,
866
+ source: "repl"
867
+ });
868
+ }, 3600000) : null;
869
+ pointerRefreshTimer?.unref?.();
870
+ const keepAliveIntervalMs = getPollIntervalConfig2().session_keepalive_interval_v2_ms;
871
+ const keepAliveTimer = keepAliveIntervalMs > 0 ? setInterval(() => {
872
+ if (!transport)
873
+ return;
874
+ logForDebugging("[bridge:repl] keep_alive sent");
875
+ transport.write({ type: "keep_alive" }).catch((err) => {
876
+ logForDebugging(`[bridge:repl] keep_alive write failed: ${errorMessage(err)}`);
877
+ });
878
+ }, keepAliveIntervalMs) : null;
879
+ keepAliveTimer?.unref?.();
880
+ let teardownStarted = false;
881
+ doTeardownImpl = async () => {
882
+ if (teardownStarted) {
883
+ logForDebugging(`[bridge:repl] Teardown already in progress, skipping duplicate call env=${environmentId} session=${currentSessionId}`);
884
+ return;
885
+ }
886
+ teardownStarted = true;
887
+ const teardownStart = Date.now();
888
+ logForDebugging(`[bridge:repl] Teardown starting: env=${environmentId} session=${currentSessionId} workId=${currentWorkId ?? "none"} transportState=${transport?.getStateLabel() ?? "null"}`);
889
+ if (pointerRefreshTimer !== null) {
890
+ clearInterval(pointerRefreshTimer);
891
+ }
892
+ if (keepAliveTimer !== null) {
893
+ clearInterval(keepAliveTimer);
894
+ }
895
+ if (sigusr2Handler) {
896
+ process.off("SIGUSR2", sigusr2Handler);
897
+ }
898
+ if (process.env.USER_TYPE === "ant") {
899
+ clearBridgeDebugHandle();
900
+ debugFireClose = null;
901
+ }
902
+ pollController.abort();
903
+ logForDebugging("[bridge:repl] Teardown: poll loop aborted");
904
+ if (transport) {
905
+ const finalSeq = transport.getLastSequenceNum();
906
+ if (finalSeq > lastTransportSequenceNum) {
907
+ lastTransportSequenceNum = finalSeq;
908
+ }
909
+ }
910
+ if (perpetual) {
911
+ transport = null;
912
+ flushGate.drop();
913
+ await writeBridgePointer(dir, {
914
+ sessionId: currentSessionId,
915
+ environmentId,
916
+ source: "repl"
917
+ });
918
+ logForDebugging(`[bridge:repl] Teardown (perpetual): leaving env=${environmentId} session=${currentSessionId} alive on server, duration=${Date.now() - teardownStart}ms`);
919
+ return;
920
+ }
921
+ const teardownTransport = transport;
922
+ transport = null;
923
+ flushGate.drop();
924
+ if (teardownTransport) {
925
+ teardownTransport.write(makeResultMessage(currentSessionId));
926
+ }
927
+ const stopWorkP = currentWorkId ? api.stopWork(environmentId, currentWorkId, true).then(() => {
928
+ logForDebugging("[bridge:repl] Teardown: stopWork completed");
929
+ }).catch((err) => {
930
+ logForDebugging(`[bridge:repl] Teardown stopWork failed: ${errorMessage(err)}`);
931
+ }) : Promise.resolve();
932
+ await Promise.all([stopWorkP, archiveSession(currentSessionId)]);
933
+ teardownTransport?.close();
934
+ logForDebugging("[bridge:repl] Teardown: transport closed");
935
+ await api.deregisterEnvironment(environmentId).catch((err) => {
936
+ logForDebugging(`[bridge:repl] Teardown deregister failed: ${errorMessage(err)}`);
937
+ });
938
+ await clearBridgePointer(dir);
939
+ logForDebugging(`[bridge:repl] Teardown complete: env=${environmentId} duration=${Date.now() - teardownStart}ms`);
940
+ };
941
+ const unregister = registerCleanup(() => doTeardownImpl?.());
942
+ logForDebugging(`[bridge:repl] Ready: env=${environmentId} session=${currentSessionId}`);
943
+ onStateChange?.("ready");
944
+ return {
945
+ get bridgeSessionId() {
946
+ return currentSessionId;
947
+ },
948
+ get environmentId() {
949
+ return environmentId;
950
+ },
951
+ getSSESequenceNum() {
952
+ const live = transport?.getLastSequenceNum() ?? 0;
953
+ return Math.max(lastTransportSequenceNum, live);
954
+ },
955
+ sessionIngressUrl,
956
+ writeMessages(messages) {
957
+ const filtered = messages.filter((m) => isEligibleBridgeMessage(m) && !initialMessageUUIDs.has(m.uuid) && !recentPostedUUIDs.has(m.uuid));
958
+ if (filtered.length === 0)
959
+ return;
960
+ if (!userMessageCallbackDone) {
961
+ for (const m of filtered) {
962
+ const text = extractTitleText(m);
963
+ if (text !== undefined && onUserMessage?.(text, currentSessionId)) {
964
+ userMessageCallbackDone = true;
965
+ break;
966
+ }
967
+ }
968
+ }
969
+ if (flushGate.enqueue(...filtered)) {
970
+ logForDebugging(`[bridge:repl] Queued ${filtered.length} message(s) during initial flush`);
971
+ return;
972
+ }
973
+ if (!transport) {
974
+ const types = filtered.map((m) => m.type).join(",");
975
+ logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} message(s) [${types}] for session=${currentSessionId}`, { level: "warn" });
976
+ return;
977
+ }
978
+ for (const msg of filtered) {
979
+ recentPostedUUIDs.add(msg.uuid);
980
+ }
981
+ logForDebugging(`[bridge:repl] Sending ${filtered.length} message(s) via transport`);
982
+ const sdkMessages = toSDKMessages2(filtered);
983
+ const events = sdkMessages.map((sdkMsg) => ({
984
+ ...sdkMsg,
985
+ session_id: currentSessionId
986
+ }));
987
+ transport.writeBatch(events);
988
+ },
989
+ writeSdkMessages(messages) {
990
+ const filtered = messages.filter((m) => !m.uuid || !recentPostedUUIDs.has(m.uuid));
991
+ if (filtered.length === 0)
992
+ return;
993
+ if (!transport) {
994
+ logForDebugging(`[bridge:repl] Transport not configured, dropping ${filtered.length} SDK message(s) for session=${currentSessionId}`, { level: "warn" });
995
+ return;
996
+ }
997
+ for (const msg of filtered) {
998
+ if (msg.uuid)
999
+ recentPostedUUIDs.add(msg.uuid);
1000
+ }
1001
+ const events = filtered.map((m) => ({ ...m, session_id: currentSessionId }));
1002
+ transport.writeBatch(events);
1003
+ },
1004
+ sendControlRequest(request) {
1005
+ if (!transport) {
1006
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_request");
1007
+ return;
1008
+ }
1009
+ const event = { ...request, session_id: currentSessionId };
1010
+ transport.write(event);
1011
+ logForDebugging(`[bridge:repl] Sent control_request request_id=${request.request_id}`);
1012
+ },
1013
+ sendControlResponse(response) {
1014
+ if (!transport) {
1015
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_response");
1016
+ return;
1017
+ }
1018
+ const event = { ...response, session_id: currentSessionId };
1019
+ transport.write(event);
1020
+ logForDebugging("[bridge:repl] Sent control_response");
1021
+ },
1022
+ sendControlCancelRequest(requestId) {
1023
+ if (!transport) {
1024
+ logForDebugging("[bridge:repl] Transport not configured, skipping control_cancel_request");
1025
+ return;
1026
+ }
1027
+ const event = {
1028
+ type: "control_cancel_request",
1029
+ request_id: requestId,
1030
+ session_id: currentSessionId
1031
+ };
1032
+ transport.write(event);
1033
+ logForDebugging(`[bridge:repl] Sent control_cancel_request request_id=${requestId}`);
1034
+ },
1035
+ sendResult() {
1036
+ if (!transport) {
1037
+ logForDebugging(`[bridge:repl] sendResult: skipping, transport not configured session=${currentSessionId}`);
1038
+ return;
1039
+ }
1040
+ transport.write(makeResultMessage(currentSessionId));
1041
+ logForDebugging(`[bridge:repl] Sent result for session=${currentSessionId}`);
1042
+ },
1043
+ async teardown() {
1044
+ unregister();
1045
+ await doTeardownImpl?.();
1046
+ logForDebugging("[bridge:repl] Torn down");
1047
+ logEvent("tengu_bridge_repl_teardown", {});
1048
+ }
1049
+ };
1050
+ }
1051
+ async function startWorkPollLoop({
1052
+ api,
1053
+ getCredentials,
1054
+ signal,
1055
+ onStateChange,
1056
+ onWorkReceived,
1057
+ onEnvironmentLost,
1058
+ getWsState,
1059
+ isAtCapacity,
1060
+ capacitySignal,
1061
+ onFatalError,
1062
+ getPollIntervalConfig: getPollIntervalConfig2 = () => DEFAULT_POLL_CONFIG,
1063
+ getHeartbeatInfo,
1064
+ onHeartbeatFatal
1065
+ }) {
1066
+ const MAX_ENVIRONMENT_RECREATIONS = 3;
1067
+ logForDebugging(`[bridge:repl] Starting work poll loop for env=${getCredentials().environmentId}`);
1068
+ let consecutiveErrors = 0;
1069
+ let firstErrorTime = null;
1070
+ let lastPollErrorTime = null;
1071
+ let environmentRecreations = 0;
1072
+ let suspensionDetected = false;
1073
+ while (!signal.aborted) {
1074
+ const { environmentId: envId, environmentSecret: envSecret } = getCredentials();
1075
+ const pollConfig = getPollIntervalConfig2();
1076
+ try {
1077
+ const work = await api.pollForWork(envId, envSecret, signal, pollConfig.reclaim_older_than_ms);
1078
+ environmentRecreations = 0;
1079
+ if (consecutiveErrors > 0) {
1080
+ logForDebugging(`[bridge:repl] Poll recovered after ${consecutiveErrors} consecutive error(s)`);
1081
+ consecutiveErrors = 0;
1082
+ firstErrorTime = null;
1083
+ lastPollErrorTime = null;
1084
+ onStateChange?.("ready");
1085
+ }
1086
+ if (!work) {
1087
+ const skipAtCapacityOnce = suspensionDetected;
1088
+ suspensionDetected = false;
1089
+ if (isAtCapacity?.() && capacitySignal && !skipAtCapacityOnce) {
1090
+ const atCapMs = pollConfig.poll_interval_ms_at_capacity;
1091
+ if (pollConfig.non_exclusive_heartbeat_interval_ms > 0 && getHeartbeatInfo) {
1092
+ logEvent("tengu_bridge_heartbeat_mode_entered", {
1093
+ heartbeat_interval_ms: pollConfig.non_exclusive_heartbeat_interval_ms
1094
+ });
1095
+ const pollDeadline = atCapMs > 0 ? Date.now() + atCapMs : null;
1096
+ let needsBackoff = false;
1097
+ let hbCycles = 0;
1098
+ while (!signal.aborted && isAtCapacity() && (pollDeadline === null || Date.now() < pollDeadline)) {
1099
+ const hbConfig = getPollIntervalConfig2();
1100
+ if (hbConfig.non_exclusive_heartbeat_interval_ms <= 0)
1101
+ break;
1102
+ const info = getHeartbeatInfo();
1103
+ if (!info)
1104
+ break;
1105
+ const cap = capacitySignal();
1106
+ try {
1107
+ await api.heartbeatWork(info.environmentId, info.workId, info.sessionToken);
1108
+ } catch (err) {
1109
+ logForDebugging(`[bridge:repl:heartbeat] Failed: ${errorMessage(err)}`);
1110
+ if (err instanceof BridgeFatalError) {
1111
+ cap.cleanup();
1112
+ logEvent("tengu_bridge_heartbeat_error", {
1113
+ status: err.status,
1114
+ error_type: err.status === 401 || err.status === 403 ? "auth_failed" : "fatal"
1115
+ });
1116
+ if (onHeartbeatFatal) {
1117
+ onHeartbeatFatal(err);
1118
+ logForDebugging(`[bridge:repl:heartbeat] Fatal (status=${err.status}), work state cleared \u2014 fast-polling for re-dispatch`);
1119
+ } else {
1120
+ needsBackoff = true;
1121
+ }
1122
+ break;
1123
+ }
1124
+ }
1125
+ hbCycles++;
1126
+ await sleep(hbConfig.non_exclusive_heartbeat_interval_ms, cap.signal);
1127
+ cap.cleanup();
1128
+ }
1129
+ const exitReason = needsBackoff ? "error" : signal.aborted ? "shutdown" : !isAtCapacity() ? "capacity_changed" : pollDeadline !== null && Date.now() >= pollDeadline ? "poll_due" : "config_disabled";
1130
+ logEvent("tengu_bridge_heartbeat_mode_exited", {
1131
+ reason: exitReason,
1132
+ heartbeat_cycles: hbCycles
1133
+ });
1134
+ if (!needsBackoff) {
1135
+ if (exitReason === "poll_due") {
1136
+ logForDebugging(`[bridge:repl] Heartbeat poll_due after ${hbCycles} cycles \u2014 falling through to pollForWork`);
1137
+ }
1138
+ continue;
1139
+ }
1140
+ }
1141
+ const sleepMs = atCapMs > 0 ? atCapMs : pollConfig.non_exclusive_heartbeat_interval_ms;
1142
+ if (sleepMs > 0) {
1143
+ const cap = capacitySignal();
1144
+ const sleepStart = Date.now();
1145
+ await sleep(sleepMs, cap.signal);
1146
+ cap.cleanup();
1147
+ const overrun = Date.now() - sleepStart - sleepMs;
1148
+ if (overrun > 60000) {
1149
+ logForDebugging(`[bridge:repl] At-capacity sleep overran by ${Math.round(overrun / 1000)}s \u2014 process suspension detected, forcing one fast-poll cycle`);
1150
+ logEvent("tengu_bridge_repl_suspension_detected", {
1151
+ overrun_ms: overrun
1152
+ });
1153
+ suspensionDetected = true;
1154
+ }
1155
+ }
1156
+ } else {
1157
+ await sleep(pollConfig.poll_interval_ms_not_at_capacity, signal);
1158
+ }
1159
+ continue;
1160
+ }
1161
+ let secret;
1162
+ try {
1163
+ secret = decodeWorkSecret(work.secret);
1164
+ } catch (err) {
1165
+ logForDebugging(`[bridge:repl] Failed to decode work secret: ${errorMessage(err)}`);
1166
+ logEvent("tengu_bridge_repl_work_secret_failed", {});
1167
+ await api.stopWork(envId, work.id, false).catch(() => {});
1168
+ continue;
1169
+ }
1170
+ logForDebugging(`[bridge:repl] Acknowledging workId=${work.id}`);
1171
+ try {
1172
+ await api.acknowledgeWork(envId, work.id, secret.session_ingress_token);
1173
+ } catch (err) {
1174
+ logForDebugging(`[bridge:repl] Acknowledge failed workId=${work.id}: ${errorMessage(err)}`);
1175
+ }
1176
+ if (work.data.type === "healthcheck") {
1177
+ logForDebugging("[bridge:repl] Healthcheck received");
1178
+ continue;
1179
+ }
1180
+ if (work.data.type === "session") {
1181
+ const workSessionId = work.data.id;
1182
+ try {
1183
+ validateBridgeId(workSessionId, "session_id");
1184
+ } catch {
1185
+ logForDebugging(`[bridge:repl] Invalid session_id in work: ${workSessionId}`);
1186
+ continue;
1187
+ }
1188
+ onWorkReceived(workSessionId, secret.session_ingress_token, work.id, secret.use_code_sessions === true);
1189
+ logForDebugging("[bridge:repl] Work accepted, continuing poll loop");
1190
+ }
1191
+ } catch (err) {
1192
+ if (signal.aborted)
1193
+ break;
1194
+ if (err instanceof BridgeFatalError && err.status === 404 && onEnvironmentLost) {
1195
+ const currentEnvId = getCredentials().environmentId;
1196
+ if (envId !== currentEnvId) {
1197
+ logForDebugging(`[bridge:repl] Stale poll error for old env=${envId}, current env=${currentEnvId} \u2014 skipping onEnvironmentLost`);
1198
+ consecutiveErrors = 0;
1199
+ firstErrorTime = null;
1200
+ continue;
1201
+ }
1202
+ environmentRecreations++;
1203
+ logForDebugging(`[bridge:repl] Environment deleted, attempting re-registration (attempt ${environmentRecreations}/${MAX_ENVIRONMENT_RECREATIONS})`);
1204
+ logEvent("tengu_bridge_repl_env_lost", {
1205
+ attempt: environmentRecreations
1206
+ });
1207
+ if (environmentRecreations > MAX_ENVIRONMENT_RECREATIONS) {
1208
+ logForDebugging(`[bridge:repl] Environment re-registration limit reached (${MAX_ENVIRONMENT_RECREATIONS}), giving up`);
1209
+ onStateChange?.("failed", "Environment deleted and re-registration limit reached");
1210
+ onFatalError?.();
1211
+ break;
1212
+ }
1213
+ onStateChange?.("reconnecting", "environment lost, recreating session");
1214
+ const newCreds = await onEnvironmentLost();
1215
+ if (signal.aborted)
1216
+ break;
1217
+ if (newCreds) {
1218
+ consecutiveErrors = 0;
1219
+ firstErrorTime = null;
1220
+ onStateChange?.("ready");
1221
+ logForDebugging(`[bridge:repl] Re-registered environment: ${newCreds.environmentId}`);
1222
+ continue;
1223
+ }
1224
+ onStateChange?.("failed", "Environment deleted and re-registration failed");
1225
+ onFatalError?.();
1226
+ break;
1227
+ }
1228
+ if (err instanceof BridgeFatalError) {
1229
+ const isExpiry = isExpiredErrorType(err.errorType);
1230
+ const isSuppressible = isSuppressible403(err);
1231
+ logForDebugging(`[bridge:repl] Fatal poll error: ${err.message} (status=${err.status}, type=${err.errorType ?? "unknown"})${isSuppressible ? " (suppressed)" : ""}`);
1232
+ logEvent("tengu_bridge_repl_fatal_error", {
1233
+ status: err.status,
1234
+ error_type: err.errorType
1235
+ });
1236
+ logForDiagnosticsNoPII(isExpiry ? "info" : "error", "bridge_repl_fatal_error", { status: err.status, error_type: err.errorType });
1237
+ if (!isSuppressible) {
1238
+ onStateChange?.("failed", isExpiry ? "session expired \xB7 /remote-control to reconnect" : err.message);
1239
+ }
1240
+ onFatalError?.();
1241
+ break;
1242
+ }
1243
+ const now = Date.now();
1244
+ if (lastPollErrorTime !== null && now - lastPollErrorTime > POLL_ERROR_MAX_DELAY_MS * 2) {
1245
+ logForDebugging(`[bridge:repl] Detected system sleep (${Math.round((now - lastPollErrorTime) / 1000)}s gap), resetting poll error budget`);
1246
+ logForDiagnosticsNoPII("info", "bridge_repl_poll_sleep_detected", {
1247
+ gapMs: now - lastPollErrorTime
1248
+ });
1249
+ consecutiveErrors = 0;
1250
+ firstErrorTime = null;
1251
+ }
1252
+ lastPollErrorTime = now;
1253
+ consecutiveErrors++;
1254
+ if (firstErrorTime === null) {
1255
+ firstErrorTime = now;
1256
+ }
1257
+ const elapsed = now - firstErrorTime;
1258
+ const httpStatus = extractHttpStatus(err);
1259
+ const errMsg = describeAxiosError(err);
1260
+ const wsLabel = getWsState?.() ?? "unknown";
1261
+ logForDebugging(`[bridge:repl] Poll error (attempt ${consecutiveErrors}, elapsed ${Math.round(elapsed / 1000)}s, ws=${wsLabel}): ${errMsg}`);
1262
+ logEvent("tengu_bridge_repl_poll_error", {
1263
+ status: httpStatus,
1264
+ consecutiveErrors,
1265
+ elapsedMs: elapsed
1266
+ });
1267
+ if (consecutiveErrors === 1) {
1268
+ onStateChange?.("reconnecting", errMsg);
1269
+ }
1270
+ if (elapsed >= POLL_ERROR_GIVE_UP_MS) {
1271
+ logForDebugging(`[bridge:repl] Poll failures exceeded ${POLL_ERROR_GIVE_UP_MS / 1000}s (${consecutiveErrors} errors), giving up`);
1272
+ logForDiagnosticsNoPII("info", "bridge_repl_poll_give_up");
1273
+ logEvent("tengu_bridge_repl_poll_give_up", {
1274
+ consecutiveErrors,
1275
+ elapsedMs: elapsed,
1276
+ lastStatus: httpStatus
1277
+ });
1278
+ onStateChange?.("failed", "connection to server lost");
1279
+ break;
1280
+ }
1281
+ const backoff = Math.min(POLL_ERROR_INITIAL_DELAY_MS * 2 ** (consecutiveErrors - 1), POLL_ERROR_MAX_DELAY_MS);
1282
+ if (getPollIntervalConfig2().non_exclusive_heartbeat_interval_ms > 0) {
1283
+ const info = getHeartbeatInfo?.();
1284
+ if (info) {
1285
+ try {
1286
+ await api.heartbeatWork(info.environmentId, info.workId, info.sessionToken);
1287
+ } catch {}
1288
+ }
1289
+ }
1290
+ await sleep(backoff, signal);
1291
+ }
1292
+ }
1293
+ logForDebugging(`[bridge:repl] Work poll loop ended (aborted=${signal.aborted}) env=${getCredentials().environmentId}`);
1294
+ }
1295
+
1296
+ // src/bridge/initReplBridge.ts
1297
+ async function initReplBridge(options) {
1298
+ const {
1299
+ onInboundMessage,
1300
+ onPermissionResponse,
1301
+ onInterrupt,
1302
+ onSetModel,
1303
+ onSetMaxThinkingTokens,
1304
+ onSetPermissionMode,
1305
+ onStateChange,
1306
+ initialMessages,
1307
+ getMessages,
1308
+ previouslyFlushedUUIDs,
1309
+ initialName,
1310
+ perpetual,
1311
+ outboundOnly,
1312
+ tags
1313
+ } = options ?? {};
1314
+ setCseShimGate(isCseShimEnabled);
1315
+ if (!await isBridgeEnabledBlocking()) {
1316
+ logBridgeSkip("not_enabled", "[bridge:repl] Skipping: bridge not enabled");
1317
+ return null;
1318
+ }
1319
+ if (!getBridgeAccessToken()) {
1320
+ logBridgeSkip("no_oauth", "[bridge:repl] Skipping: no OAuth tokens");
1321
+ onStateChange?.("failed", "/login");
1322
+ return null;
1323
+ }
1324
+ await waitForPolicyLimitsToLoad();
1325
+ if (!isPolicyAllowed("allow_remote_control")) {
1326
+ logBridgeSkip("policy_denied", "[bridge:repl] Skipping: allow_remote_control policy not allowed");
1327
+ onStateChange?.("failed", "disabled by your organization's policy");
1328
+ return null;
1329
+ }
1330
+ if (!getBridgeTokenOverride()) {
1331
+ const cfg = getGlobalConfig();
1332
+ if (cfg.bridgeOauthDeadExpiresAt != null && (cfg.bridgeOauthDeadFailCount ?? 0) >= 3 && getClaudeAIOAuthTokens()?.expiresAt === cfg.bridgeOauthDeadExpiresAt) {
1333
+ logForDebugging(`[bridge:repl] Skipping: cross-process backoff (dead token seen ${cfg.bridgeOauthDeadFailCount} times)`);
1334
+ return null;
1335
+ }
1336
+ await checkAndRefreshOAuthTokenIfNeeded();
1337
+ const tokens = getClaudeAIOAuthTokens();
1338
+ if (tokens && tokens.expiresAt !== null && tokens.expiresAt <= Date.now()) {
1339
+ logBridgeSkip("oauth_expired_unrefreshable", "[bridge:repl] Skipping: OAuth token expired and refresh failed (re-login required)");
1340
+ onStateChange?.("failed", "/login");
1341
+ const deadExpiresAt = tokens.expiresAt;
1342
+ saveGlobalConfig((c) => ({
1343
+ ...c,
1344
+ bridgeOauthDeadExpiresAt: deadExpiresAt,
1345
+ bridgeOauthDeadFailCount: c.bridgeOauthDeadExpiresAt === deadExpiresAt ? (c.bridgeOauthDeadFailCount ?? 0) + 1 : 1
1346
+ }));
1347
+ return null;
1348
+ }
1349
+ }
1350
+ const baseUrl = getBridgeBaseUrl();
1351
+ let title = `remote-control-${generateShortWordSlug()}`;
1352
+ let hasTitle = false;
1353
+ let hasExplicitTitle = false;
1354
+ if (initialName) {
1355
+ title = initialName;
1356
+ hasTitle = true;
1357
+ hasExplicitTitle = true;
1358
+ } else {
1359
+ const sessionId = getSessionId();
1360
+ const customTitle = sessionId ? getCurrentSessionTitle(sessionId) : undefined;
1361
+ if (customTitle) {
1362
+ title = customTitle;
1363
+ hasTitle = true;
1364
+ hasExplicitTitle = true;
1365
+ } else if (initialMessages && initialMessages.length > 0) {
1366
+ for (let i = initialMessages.length - 1;i >= 0; i--) {
1367
+ const msg = initialMessages[i];
1368
+ if (msg.type !== "user" || msg.isMeta || msg.toolUseResult || msg.isCompactSummary || msg.origin && msg.origin.kind !== "human" || isSyntheticMessage(msg))
1369
+ continue;
1370
+ const rawContent = getContentText(msg.message.content);
1371
+ if (!rawContent)
1372
+ continue;
1373
+ const derived = deriveTitle(rawContent);
1374
+ if (!derived)
1375
+ continue;
1376
+ title = derived;
1377
+ hasTitle = true;
1378
+ break;
1379
+ }
1380
+ }
1381
+ }
1382
+ let userMessageCount = 0;
1383
+ let lastBridgeSessionId;
1384
+ let genSeq = 0;
1385
+ const patch = (derived, bridgeSessionId, atCount) => {
1386
+ hasTitle = true;
1387
+ title = derived;
1388
+ logForDebugging(`[bridge:repl] derived title from message ${atCount}: ${derived}`);
1389
+ updateBridgeSessionTitle(bridgeSessionId, derived, {
1390
+ baseUrl,
1391
+ getAccessToken: getBridgeAccessToken
1392
+ }).catch(() => {});
1393
+ };
1394
+ const generateAndPatch = (input, bridgeSessionId) => {
1395
+ const gen = ++genSeq;
1396
+ const atCount = userMessageCount;
1397
+ generateSessionTitle(input, AbortSignal.timeout(15000)).then((generated) => {
1398
+ if (generated && gen === genSeq && lastBridgeSessionId === bridgeSessionId && !getCurrentSessionTitle(getSessionId())) {
1399
+ patch(generated, bridgeSessionId, atCount);
1400
+ }
1401
+ });
1402
+ };
1403
+ const onUserMessage = (text, bridgeSessionId) => {
1404
+ if (hasExplicitTitle || getCurrentSessionTitle(getSessionId())) {
1405
+ return true;
1406
+ }
1407
+ if (lastBridgeSessionId !== undefined && lastBridgeSessionId !== bridgeSessionId) {
1408
+ userMessageCount = 0;
1409
+ }
1410
+ lastBridgeSessionId = bridgeSessionId;
1411
+ userMessageCount++;
1412
+ if (userMessageCount === 1 && !hasTitle) {
1413
+ const placeholder = deriveTitle(text);
1414
+ if (placeholder)
1415
+ patch(placeholder, bridgeSessionId, userMessageCount);
1416
+ generateAndPatch(text, bridgeSessionId);
1417
+ } else if (userMessageCount === 3) {
1418
+ const msgs = getMessages?.();
1419
+ const input = msgs ? extractConversationText(getMessagesAfterCompactBoundary(msgs)) : text;
1420
+ generateAndPatch(input, bridgeSessionId);
1421
+ }
1422
+ return userMessageCount >= 3;
1423
+ };
1424
+ const initialHistoryCap = getFeatureValue_CACHED_WITH_REFRESH("tengu_bridge_initial_history_cap", 200, 5 * 60 * 1000);
1425
+ const orgUUID = await getOrganizationUUID();
1426
+ if (!orgUUID) {
1427
+ logBridgeSkip("no_org_uuid", "[bridge:repl] Skipping: no org UUID");
1428
+ onStateChange?.("failed", "/login");
1429
+ return null;
1430
+ }
1431
+ if (isEnvLessBridgeEnabled() && !perpetual) {
1432
+ const versionError2 = await checkEnvLessBridgeMinVersion();
1433
+ if (versionError2) {
1434
+ logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError2}`, true);
1435
+ onStateChange?.("failed", "run `claude update` to upgrade");
1436
+ return null;
1437
+ }
1438
+ logForDebugging("[bridge:repl] Using env-less bridge path (tengu_bridge_repl_v2)");
1439
+ const { initEnvLessBridgeCore } = await import("./chunk-94dm5rrm.js");
1440
+ return initEnvLessBridgeCore({
1441
+ baseUrl,
1442
+ orgUUID,
1443
+ title,
1444
+ getAccessToken: getBridgeAccessToken,
1445
+ onAuth401: handleOAuth401Error,
1446
+ toSDKMessages,
1447
+ initialHistoryCap,
1448
+ initialMessages,
1449
+ onInboundMessage,
1450
+ onUserMessage,
1451
+ onPermissionResponse,
1452
+ onInterrupt,
1453
+ onSetModel,
1454
+ onSetMaxThinkingTokens,
1455
+ onSetPermissionMode,
1456
+ onStateChange,
1457
+ outboundOnly,
1458
+ tags
1459
+ });
1460
+ }
1461
+ const versionError = checkBridgeMinVersion();
1462
+ if (versionError) {
1463
+ logBridgeSkip("version_too_old", `[bridge:repl] Skipping: ${versionError}`);
1464
+ onStateChange?.("failed", "run `claude update` to upgrade");
1465
+ return null;
1466
+ }
1467
+ const branch = await getBranch();
1468
+ const gitRepoUrl = await getRemoteUrl();
1469
+ const sessionIngressUrl = process.env.USER_TYPE === "ant" && process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL ? process.env.CLAUDE_BRIDGE_SESSION_INGRESS_URL : baseUrl;
1470
+ let workerType = "claude_code";
1471
+ if (false) {}
1472
+ return initBridgeCore({
1473
+ dir: getOriginalCwd(),
1474
+ machineName: hostname(),
1475
+ branch,
1476
+ gitRepoUrl,
1477
+ title,
1478
+ baseUrl,
1479
+ sessionIngressUrl,
1480
+ workerType,
1481
+ getAccessToken: getBridgeAccessToken,
1482
+ createSession: (opts) => createBridgeSession({
1483
+ ...opts,
1484
+ events: [],
1485
+ baseUrl,
1486
+ getAccessToken: getBridgeAccessToken
1487
+ }),
1488
+ archiveSession: (sessionId) => archiveBridgeSession(sessionId, {
1489
+ baseUrl,
1490
+ getAccessToken: getBridgeAccessToken,
1491
+ timeoutMs: 1500
1492
+ }).catch((err) => {
1493
+ logForDebugging(`[bridge:repl] archiveBridgeSession threw: ${errorMessage(err)}`, { level: "error" });
1494
+ }),
1495
+ getCurrentTitle: () => getCurrentSessionTitle(getSessionId()) ?? title,
1496
+ onUserMessage,
1497
+ toSDKMessages,
1498
+ onAuth401: handleOAuth401Error,
1499
+ getPollIntervalConfig,
1500
+ initialHistoryCap,
1501
+ initialMessages,
1502
+ previouslyFlushedUUIDs,
1503
+ onInboundMessage,
1504
+ onPermissionResponse,
1505
+ onInterrupt,
1506
+ onSetModel,
1507
+ onSetMaxThinkingTokens,
1508
+ onSetPermissionMode,
1509
+ onStateChange,
1510
+ perpetual
1511
+ });
1512
+ }
1513
+ var TITLE_MAX_LEN = 50;
1514
+ function deriveTitle(raw) {
1515
+ const clean = stripDisplayTagsAllowEmpty(raw);
1516
+ const firstSentence = /^(.*?[.!?])\s/.exec(clean)?.[1] ?? clean;
1517
+ const flat = firstSentence.replace(/\s+/g, " ").trim();
1518
+ if (!flat)
1519
+ return;
1520
+ return flat.length > TITLE_MAX_LEN ? flat.slice(0, TITLE_MAX_LEN - 1) + "\u2026" : flat;
1521
+ }
1522
+ export {
1523
+ initReplBridge
1524
+ };