@intent-hq/web 2.390.0 → 2.391.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 (325) hide show
  1. package/package.json +1 -1
  2. package/web/app/immutable/chunks/{caKZ9Z4U.js → -CpNnXIW.js} +1 -1
  3. package/web/app/immutable/chunks/{CyzdJWF0.js → 0WykzpsL.js} +1 -1
  4. package/web/app/immutable/chunks/{Cp5royN1.js → 1-MeqddK.js} +1 -1
  5. package/web/app/immutable/chunks/{DpkDQyZQ.js → 3bAApxgI.js} +1 -1
  6. package/web/app/immutable/chunks/{DR942Ajh.js → 3hx_Pv3I.js} +1 -1
  7. package/web/app/immutable/chunks/{DFOcWzwz.js → 3zZ5VtMA.js} +1 -1
  8. package/web/app/immutable/chunks/{BR96U9Wd.js → 5JwmgTp3.js} +1 -1
  9. package/web/app/immutable/chunks/{DCLLUF6K.js → 6JlgfFWd.js} +1 -1
  10. package/web/app/immutable/chunks/{vCzBOtB7.js → 6zjpUzOd.js} +1 -1
  11. package/web/app/immutable/chunks/{DxyD9o0t.js → 9eqoPT_C.js} +1 -1
  12. package/web/app/immutable/chunks/{D672CX3Y.js → Ao0jjYj2.js} +1 -1
  13. package/web/app/immutable/chunks/{BEhUDDmK.js → B0qyjQ39.js} +1 -1
  14. package/web/app/immutable/chunks/{CmfAV5b9.js → B1U2wa0T.js} +1 -1
  15. package/web/app/immutable/chunks/{D5Jqamkx.js → B1ZnKKBC.js} +1 -1
  16. package/web/app/immutable/chunks/{_UjuBCOJ.js → B1lpukIv.js} +1 -1
  17. package/web/app/immutable/chunks/{CcJmuwXr.js → B26ZHg3s.js} +1 -1
  18. package/web/app/immutable/chunks/{C4u2zmyj.js → B28GhEWZ.js} +1 -1
  19. package/web/app/immutable/chunks/{CrpG0ldr.js → B28HQLvX.js} +1 -1
  20. package/web/app/immutable/chunks/{BIFBPuAO.js → B2Ny2uiy.js} +1 -1
  21. package/web/app/immutable/chunks/{DfheqyY9.js → B2awO10u.js} +1 -1
  22. package/web/app/immutable/chunks/{C4jSaPCg.js → B3T1oiJl.js} +1 -1
  23. package/web/app/immutable/chunks/{BtmHyUSg.js → B4Yz29Q3.js} +1 -1
  24. package/web/app/immutable/chunks/{Klbdavqn.js → B4kHSLJr.js} +1 -1
  25. package/web/app/immutable/chunks/{DWP4pi_Q.js → B55WAZno.js} +1 -1
  26. package/web/app/immutable/chunks/{DZ6KouyB.js → B5TWkOLI.js} +1 -1
  27. package/web/app/immutable/chunks/{DJwakuJL.js → B60nx31p.js} +1 -1
  28. package/web/app/immutable/chunks/{D9ejVVI8.js → B6mEh1Cs.js} +1 -1
  29. package/web/app/immutable/chunks/{9YT9B_ti.js → B7pblHOt.js} +1 -1
  30. package/web/app/immutable/chunks/{CkmDctRH.js → BCLYeYwk.js} +1 -1
  31. package/web/app/immutable/chunks/{BbYWP3Ow.js → BFfRQORP.js} +1 -1
  32. package/web/app/immutable/chunks/{BrMDTgLg.js → BGeImWEk.js} +1 -1
  33. package/web/app/immutable/chunks/{BksTLNI4.js → BHgSQJqT.js} +1 -1
  34. package/web/app/immutable/chunks/{BJEoqPJ5.js → BJCm9MUD.js} +1 -1
  35. package/web/app/immutable/chunks/{958SNXkw.js → BM2ubpAw.js} +1 -1
  36. package/web/app/immutable/chunks/{D36C5UHH.js → BM39k1x6.js} +1 -1
  37. package/web/app/immutable/chunks/{CjPEI4fg.js → BMTanQ2Z.js} +1 -1
  38. package/web/app/immutable/chunks/{BtNlG0Qg.js → BNYZa6GV.js} +1 -1
  39. package/web/app/immutable/chunks/{Cn4A9AjR.js → BOPrepKH.js} +1 -1
  40. package/web/app/immutable/chunks/{BAwfT99s.js → BP9YAxnw.js} +1 -1
  41. package/web/app/immutable/chunks/{Bc1BuSIT.js → BPS-xChS.js} +1 -1
  42. package/web/app/immutable/chunks/{Bq4K4JBr.js → BRSPDdkI.js} +1 -1
  43. package/web/app/immutable/chunks/{CgrVbtN0.js → BS9WBIBb.js} +1 -1
  44. package/web/app/immutable/chunks/{DuaPhBil.js → BSKVcPN7.js} +1 -1
  45. package/web/app/immutable/chunks/{D7b2VLAz.js → BT5iyspK.js} +1 -1
  46. package/web/app/immutable/chunks/{CJsEZbta.js → BT8mEFV6.js} +1 -1
  47. package/web/app/immutable/chunks/{DZzwt3PA.js → BTvJ4T_4.js} +1 -1
  48. package/web/app/immutable/chunks/{aZdb_rCN.js → BU3y3Xes.js} +1 -1
  49. package/web/app/immutable/chunks/{DCs992HX.js → BUSErGiB.js} +1 -1
  50. package/web/app/immutable/chunks/{p1zR6qAw.js → BWQPB65O.js} +1 -1
  51. package/web/app/immutable/chunks/{BwH4Bvte.js → BZ27qIg1.js} +1 -1
  52. package/web/app/immutable/chunks/{BLg51chm.js → BZ2BunMM.js} +3 -3
  53. package/web/app/immutable/chunks/{D-9KNtuV.js → B_FwdBlO.js} +1 -1
  54. package/web/app/immutable/chunks/{CDwhmkPo.js → B_JGVEqN.js} +1 -1
  55. package/web/app/immutable/chunks/{BNCKMxAC.js → Bb-kpHQF.js} +1 -1
  56. package/web/app/immutable/chunks/{BABPbAn1.js → BbXTs-zc.js} +1 -1
  57. package/web/app/immutable/chunks/{k55njABd.js → BczcQRsN.js} +1 -1
  58. package/web/app/immutable/chunks/{Ve-0_aGT.js → BdCPH0Ry.js} +3 -3
  59. package/web/app/immutable/chunks/{B5N8LmEF.js → BdhKX9ZN.js} +1 -1
  60. package/web/app/immutable/chunks/{WbzVOnzB.js → Bdz7xLoU.js} +2 -2
  61. package/web/app/immutable/chunks/{YmRtKLCw.js → Bf739dtf.js} +1 -1
  62. package/web/app/immutable/chunks/{uvhZkGDU.js → Bhq56Jsu.js} +1 -1
  63. package/web/app/immutable/chunks/{Bviyt-Xy.js → Bhyo7hBL.js} +1 -1
  64. package/web/app/immutable/chunks/{DOy5PC7K.js → Bi8v8T9s.js} +1 -1
  65. package/web/app/immutable/chunks/{HlKQh-jr.js → BijokBFk.js} +1 -1
  66. package/web/app/immutable/chunks/{DdNhEgdc.js → BjGqF2I6.js} +1 -1
  67. package/web/app/immutable/chunks/{BYxTMRdy.js → Bk1TahM2.js} +1 -1
  68. package/web/app/immutable/chunks/{BPQFiQQc.js → BkcCJyDK.js} +1 -1
  69. package/web/app/immutable/chunks/{C8ukaQ4v.js → BkoVJN8J.js} +1 -1
  70. package/web/app/immutable/chunks/{DQTlXZTK.js → BlIQH-6S.js} +1 -1
  71. package/web/app/immutable/chunks/{Bq2Q6gce.js → BlzuDW6O.js} +1 -1
  72. package/web/app/immutable/chunks/{5Rw929MQ.js → BmlW0rtZ.js} +1 -1
  73. package/web/app/immutable/chunks/{C8rJ090F.js → Bmr0NXg9.js} +1 -1
  74. package/web/app/immutable/chunks/{C97rJdwd.js → Bn3gcMEi.js} +2 -2
  75. package/web/app/immutable/chunks/{BIkp_Hmt.js → BnLeDIe_.js} +1 -1
  76. package/web/app/immutable/chunks/{RhUR09AA.js → Bnz_gGcf.js} +1 -1
  77. package/web/app/immutable/chunks/{UTM5G-w-.js → BpezAJRw.js} +1 -1
  78. package/web/app/immutable/chunks/BrS-M4QZ.js +411 -0
  79. package/web/app/immutable/chunks/{DhZ3_JXX.js → Bt4BDbd9.js} +1 -1
  80. package/web/app/immutable/chunks/{CnpTi_2q.js → BudXN7v1.js} +2 -2
  81. package/web/app/immutable/chunks/{Bwe7RKw-.js → Bv7vQoAK.js} +1 -1
  82. package/web/app/immutable/chunks/{D09F61W3.js → BvKMYZXt.js} +1 -1
  83. package/web/app/immutable/chunks/{B1cYD5sf.js → Bvnhw_a1.js} +1 -1
  84. package/web/app/immutable/chunks/{CfNIzRu8.js → Bx1P9uW7.js} +1 -1
  85. package/web/app/immutable/chunks/{BhCMc9G0.js → By2YlE-l.js} +1 -1
  86. package/web/app/immutable/chunks/{CSjV3uYy.js → Byobtdo1.js} +1 -1
  87. package/web/app/immutable/chunks/{CEE0831H.js → Bz80vYvX.js} +1 -1
  88. package/web/app/immutable/chunks/{BnknS-C6.js → BzX67fGt.js} +1 -1
  89. package/web/app/immutable/chunks/{pfX_M-aK.js → C-nTKxY9.js} +1 -1
  90. package/web/app/immutable/chunks/{sLmWN1ks.js → C0wQm_cl.js} +1 -1
  91. package/web/app/immutable/chunks/{CVWwz1Ss.js → C22cBcHz.js} +1 -1
  92. package/web/app/immutable/chunks/{D9CNxngf.js → C3JJkOFb.js} +1 -1
  93. package/web/app/immutable/chunks/{96V4v2iI.js → C3jMXj_V.js} +1 -1
  94. package/web/app/immutable/chunks/{BTEHnOFb.js → C4BZMChh.js} +1 -1
  95. package/web/app/immutable/chunks/{DRND1Lha.js → C4l6men1.js} +1 -1
  96. package/web/app/immutable/chunks/{B75YmuDW.js → C6xamGmH.js} +3 -3
  97. package/web/app/immutable/chunks/C8E14ldW.js +1 -0
  98. package/web/app/immutable/chunks/{mfOfLDEg.js → C9N7yhqm.js} +1 -1
  99. package/web/app/immutable/chunks/{BId1zNus.js → CAGrRNbp.js} +1 -1
  100. package/web/app/immutable/chunks/{BOVEEbKv.js → CAUJiTuz.js} +1 -1
  101. package/web/app/immutable/chunks/{CgrukgLv.js → CA_E2EO_.js} +1 -1
  102. package/web/app/immutable/chunks/{BPXITtd5.js → CBZWgc2D.js} +1 -1
  103. package/web/app/immutable/chunks/{BR1TNOav.js → CDUYzZ2W.js} +1 -1
  104. package/web/app/immutable/chunks/CDVPwJHE.js +1 -0
  105. package/web/app/immutable/chunks/{CiRuCsUo.js → CDh2mZdS.js} +1 -1
  106. package/web/app/immutable/chunks/{BBRFTdr4.js → CDqF0p7U.js} +1 -1
  107. package/web/app/immutable/chunks/{DpCic98X.js → CEA7jD1C.js} +1 -1
  108. package/web/app/immutable/chunks/{Dp7Hm0g0.js → CEyWnfg4.js} +1 -1
  109. package/web/app/immutable/chunks/{BcEFHs1M.js → CGBripl0.js} +1 -1
  110. package/web/app/immutable/chunks/{BwNrQXlF.js → CGmYraIa.js} +1 -1
  111. package/web/app/immutable/chunks/{yofTuS8P.js → CH6Im5iM.js} +1 -1
  112. package/web/app/immutable/chunks/{BBFoj-dS.js → CHIxjTWu.js} +1 -1
  113. package/web/app/immutable/chunks/{Gz_O-dMq.js → CKBFGMc-.js} +3 -3
  114. package/web/app/immutable/chunks/{TyAuxp07.js → CLvqghA8.js} +1 -1
  115. package/web/app/immutable/chunks/{D9vbo-CC.js → CM8uib8e.js} +3 -3
  116. package/web/app/immutable/chunks/{Bm6N2soI.js → COJ7FcW0.js} +4 -4
  117. package/web/app/immutable/chunks/{DPttSllj.js → COofQgO0.js} +1 -1
  118. package/web/app/immutable/chunks/{BrtJC6OX.js → COpm3Tww.js} +4 -4
  119. package/web/app/immutable/chunks/{DZaRsTHz.js → CPjnlep8.js} +1 -1
  120. package/web/app/immutable/chunks/{Cjn3mkT-.js → CR1CxoNP.js} +1 -1
  121. package/web/app/immutable/chunks/{Lai6pqjy.js → CREbzS7Z.js} +1 -1
  122. package/web/app/immutable/chunks/{DtXgUHCj.js → CRXlvdEs.js} +1 -1
  123. package/web/app/immutable/chunks/{C3s2I-px.js → CRwY2AeH.js} +1 -1
  124. package/web/app/immutable/chunks/{DPqjG1Qz.js → CT1weljk.js} +1 -1
  125. package/web/app/immutable/chunks/{TB9r2XJy.js → CT8vPg_p.js} +2 -2
  126. package/web/app/immutable/chunks/{hkJYqn41.js → CTgYTdXw.js} +1 -1
  127. package/web/app/immutable/chunks/{o0-ObNWE.js → CU15H7o_.js} +1 -1
  128. package/web/app/immutable/chunks/{Y3Xkuhtt.js → CUWwQrpD.js} +1 -1
  129. package/web/app/immutable/chunks/{C3dytrTL.js → CUZpLDKB.js} +1 -1
  130. package/web/app/immutable/chunks/{DMrzeQEi.js → CV17KbhT.js} +1 -1
  131. package/web/app/immutable/chunks/{BbhtQrkZ.js → CVtLV3_x.js} +1 -1
  132. package/web/app/immutable/chunks/{etz9IKpr.js → CWXVdpgZ.js} +1 -1
  133. package/web/app/immutable/chunks/{J2joGn0l.js → CWm_v4XX.js} +1 -1
  134. package/web/app/immutable/chunks/{DVx4z2O_.js → CXlmxn9D.js} +1 -1
  135. package/web/app/immutable/chunks/{8NmvrAbf.js → CY5E-txU.js} +1 -1
  136. package/web/app/immutable/chunks/{ggXs_b9y.js → C_8_aEto.js} +1 -1
  137. package/web/app/immutable/chunks/{BNJ3edFz.js → CbB6SI0i.js} +1 -1
  138. package/web/app/immutable/chunks/{DGdVv1yv.js → Cc9GRpTQ.js} +1 -1
  139. package/web/app/immutable/chunks/{zGyI6qOq.js → CdTSfppl.js} +1 -1
  140. package/web/app/immutable/chunks/{BxQzAB5H.js → CdVvsm2p.js} +1 -1
  141. package/web/app/immutable/chunks/{B6U9KgKY.js → CedswVQA.js} +1 -1
  142. package/web/app/immutable/chunks/{B6dUCFoz.js → CeoBhFo7.js} +1 -1
  143. package/web/app/immutable/chunks/{CwEjDuJ3.js → Cgz4dZpP.js} +1 -1
  144. package/web/app/immutable/chunks/{7MNwLg3l.js → ChLkDI4a.js} +1 -1
  145. package/web/app/immutable/chunks/{CovKrpBE.js → ChSyGlG9.js} +1 -1
  146. package/web/app/immutable/chunks/{BGniv2IE.js → ChYLETZB.js} +1 -1
  147. package/web/app/immutable/chunks/{vj8NdGWd.js → Chbrtg19.js} +1 -1
  148. package/web/app/immutable/chunks/{D54MIPdF.js → Ci6PI5sn.js} +1 -1
  149. package/web/app/immutable/chunks/{TBtn8giw.js → CiHhUIjb.js} +1 -1
  150. package/web/app/immutable/chunks/{B9vHutcJ.js → CiKoEJ2m.js} +1 -1
  151. package/web/app/immutable/chunks/{D4ytz2EC.js → CjpWOZGa.js} +1 -1
  152. package/web/app/immutable/chunks/{B6c2kL4w.js → CkoYXKFa.js} +2 -2
  153. package/web/app/immutable/chunks/{CfQcMKZg.js → CktgkomQ.js} +1 -1
  154. package/web/app/immutable/chunks/{D99jSct3.js → ClaP_sir.js} +1 -1
  155. package/web/app/immutable/chunks/{DZ-x-eWR.js → CmvX1OIv.js} +1 -1
  156. package/web/app/immutable/chunks/{KZwZoyIt.js → Cn-Afla1.js} +1 -1
  157. package/web/app/immutable/chunks/{z3SZgGAK.js → CnDgS0vt.js} +1 -1
  158. package/web/app/immutable/chunks/{B1CKzIA2.js → CnFZbWXv.js} +1 -1
  159. package/web/app/immutable/chunks/{j1QbeoGS.js → CpmTFmUr.js} +1 -1
  160. package/web/app/immutable/chunks/{2kr9sl0a.js → CqVzh7wS.js} +1 -1
  161. package/web/app/immutable/chunks/{E1ou7S5Q.js → CrbOuYLj.js} +2 -2
  162. package/web/app/immutable/chunks/{D7QZQ0zf.js → Crey45Oa.js} +1 -1
  163. package/web/app/immutable/chunks/{Cqrn6Iuw.js → Cs94v59b.js} +1 -1
  164. package/web/app/immutable/chunks/{DJ9ILql1.js → Csqi0oV3.js} +1 -1
  165. package/web/app/immutable/chunks/{6zHrL7ht.js → Ct3K7T3j.js} +1 -1
  166. package/web/app/immutable/chunks/CtfEuoOH.js +1 -0
  167. package/web/app/immutable/chunks/{-Zg6rfog.js → Cv_bDXRO.js} +1 -1
  168. package/web/app/immutable/chunks/{ClxyT-Se.js → CwCvyVGi.js} +1 -1
  169. package/web/app/immutable/chunks/{Ctp-YfoS.js → CwqyVbqi.js} +3 -3
  170. package/web/app/immutable/chunks/{DXLbZrSI.js → CxKuw3AV.js} +1 -1
  171. package/web/app/immutable/chunks/{CSEXx_lD.js → CxXCJ2kp.js} +1 -1
  172. package/web/app/immutable/chunks/{B_vpadVO.js → Cxc8q3rR.js} +1 -1
  173. package/web/app/immutable/chunks/{vpQRVk8F.js → Cxmepjfl.js} +1 -1
  174. package/web/app/immutable/chunks/{D06KyCnD.js → CyJX_0ZH.js} +1 -1
  175. package/web/app/immutable/chunks/{CzJm3Kxa.js → CyinuwPx.js} +1 -1
  176. package/web/app/immutable/chunks/{C4fj9uDh.js → CyvzL5p8.js} +3 -3
  177. package/web/app/immutable/chunks/{X0RLj3lE.js → CzxEKNiF.js} +1 -1
  178. package/web/app/immutable/chunks/{Dnkb7G58.js → D-wrxbVY.js} +1 -1
  179. package/web/app/immutable/chunks/{XwUFesej.js → D0Z4j4KD.js} +1 -1
  180. package/web/app/immutable/chunks/{BgnV10Sc.js → D1FTpY7r.js} +2 -2
  181. package/web/app/immutable/chunks/{CZtfaUbt.js → D1tq2CRk.js} +1 -1
  182. package/web/app/immutable/chunks/{GnUYJfg_.js → D3JNbQ4D.js} +1 -1
  183. package/web/app/immutable/chunks/{Dfp6ssYD.js → D3tqOSzT.js} +1 -1
  184. package/web/app/immutable/chunks/{Ch_2itxw.js → D49mWFig.js} +1 -1
  185. package/web/app/immutable/chunks/{BzWT_wQw.js → D5tDAzIo.js} +1 -1
  186. package/web/app/immutable/chunks/{BotNUGl4.js → D6q64aEo.js} +3 -3
  187. package/web/app/immutable/chunks/{Jg5r77fy.js → D7QFmXLb.js} +1 -1
  188. package/web/app/immutable/chunks/{Bttnblj5.js → D970Mqsu.js} +1 -1
  189. package/web/app/immutable/chunks/{nxtepGjE.js → D9R5fzn8.js} +1 -1
  190. package/web/app/immutable/chunks/{CAUT4r9n.js → DCLeEFTU.js} +1 -1
  191. package/web/app/immutable/chunks/{Dzy45J4U.js → DCoRWScq.js} +1 -1
  192. package/web/app/immutable/chunks/{CIbfGsF-.js → DFKhOU69.js} +1 -1
  193. package/web/app/immutable/chunks/{CCdFHP5T.js → DFlZYhla.js} +1 -1
  194. package/web/app/immutable/chunks/{BpMXdC4H.js → DG3-me8H.js} +1 -1
  195. package/web/app/immutable/chunks/{nIshZjK_.js → DGU9U1O6.js} +1 -1
  196. package/web/app/immutable/chunks/{D69-2bhh.js → DGwxrltY.js} +1 -1
  197. package/web/app/immutable/chunks/{C3WhRTo5.js → DHQU4kkd.js} +1 -1
  198. package/web/app/immutable/chunks/{Ll0WtNFW.js → DHkcvVzr.js} +1 -1
  199. package/web/app/immutable/chunks/{tCg_s90g.js → DIIj7EWA.js} +1 -1
  200. package/web/app/immutable/chunks/{DZOkhMcO.js → DJSvqrCI.js} +1 -1
  201. package/web/app/immutable/chunks/{BYHw69-J.js → DJqiMUht.js} +1 -1
  202. package/web/app/immutable/chunks/{i5FUlYpy.js → DLqZuVvj.js} +1 -1
  203. package/web/app/immutable/chunks/{Cu5e4npY.js → DMEIbJII.js} +1 -1
  204. package/web/app/immutable/chunks/{D1BvOU2l.js → DOhHP999.js} +1 -1
  205. package/web/app/immutable/chunks/{CqCb3N-V.js → DPZ2um_T.js} +4 -4
  206. package/web/app/immutable/chunks/{BniyCzQ9.js → DPk2fLxi.js} +1 -1
  207. package/web/app/immutable/chunks/{Dn2kTCYW.js → DPmtJhEg.js} +1 -1
  208. package/web/app/immutable/chunks/{Bizymm2G.js → DQMrEH0w.js} +2 -2
  209. package/web/app/immutable/chunks/{C8LWodzW.js → DQbu7pou.js} +2 -2
  210. package/web/app/immutable/chunks/DQkOZWKk.js +1 -0
  211. package/web/app/immutable/chunks/{BnV9CBUH.js → DQpGArF7.js} +1 -1
  212. package/web/app/immutable/chunks/{R-UFG3MB.js → DRuLniWc.js} +1 -1
  213. package/web/app/immutable/chunks/{z5FcOXD5.js → DSZbBNDD.js} +1 -1
  214. package/web/app/immutable/chunks/{DtzJzV-4.js → DUTvR2si.js} +1 -1
  215. package/web/app/immutable/chunks/{C6dmVB1C.js → DUkc2huG.js} +4 -4
  216. package/web/app/immutable/chunks/{D2YDfFKv.js → DW8fwVBf.js} +1 -1
  217. package/web/app/immutable/chunks/{Bs_2q1R8.js → DWZL93Dc.js} +1 -1
  218. package/web/app/immutable/chunks/{u4iPyMwH.js → DXCHCOFX.js} +1 -1
  219. package/web/app/immutable/chunks/{BD_S4uTD.js → DaWbxwE_.js} +1 -1
  220. package/web/app/immutable/chunks/{Bi8MRKMx.js → DalTYFZn.js} +1 -1
  221. package/web/app/immutable/chunks/{C7KJ2WWY.js → DcNjiASe.js} +2 -2
  222. package/web/app/immutable/chunks/{CvLVVi8w.js → DcPZfWKB.js} +1 -1
  223. package/web/app/immutable/chunks/{DaWmj23r.js → DcraaizU.js} +1 -1
  224. package/web/app/immutable/chunks/{C6RhewOE.js → Dd_KPYBw.js} +1 -1
  225. package/web/app/immutable/chunks/{CsJwP4fg.js → DeKlxkvP.js} +1 -1
  226. package/web/app/immutable/chunks/{Cb0GBy9I.js → DedU58Eo.js} +2 -2
  227. package/web/app/immutable/chunks/{BjuRA2LN.js → Df09ThmJ.js} +1 -1
  228. package/web/app/immutable/chunks/{CWsj4Hb7.js → Dgo57zmq.js} +1 -1
  229. package/web/app/immutable/chunks/{C8tk9ZQ3.js → Dh-DCh2Y.js} +1 -1
  230. package/web/app/immutable/chunks/{29xygHrF.js → DhTLwmro.js} +1 -1
  231. package/web/app/immutable/chunks/{DvhzK-4t.js → Dhh3ve0v.js} +1 -1
  232. package/web/app/immutable/chunks/{BsouhNTN.js → Di-MwTUE.js} +1 -1
  233. package/web/app/immutable/chunks/{CZr8f1ch.js → DlljGo_I.js} +1 -1
  234. package/web/app/immutable/chunks/{BOwgyiCF.js → DmQ5G_6J.js} +1 -1
  235. package/web/app/immutable/chunks/{ByyFoG6W.js → DoB-G8kB.js} +1 -1
  236. package/web/app/immutable/chunks/{Dqi2LMpO.js → DoJ49Zrl.js} +1 -1
  237. package/web/app/immutable/chunks/{CFs3R4lt.js → DqtLBCnq.js} +1 -1
  238. package/web/app/immutable/chunks/{Crz8kvLc.js → Drn9m8Tp.js} +1 -1
  239. package/web/app/immutable/chunks/{Dv1h77Vp.js → DvpTRyHt.js} +1 -1
  240. package/web/app/immutable/chunks/DwJc_V5I.js +3 -0
  241. package/web/app/immutable/chunks/{Cp0zjovM.js → Dxe27_xZ.js} +1 -1
  242. package/web/app/immutable/chunks/{BFgvMDua.js → DynUeYUu.js} +1 -1
  243. package/web/app/immutable/chunks/{BjE6fvlI.js → DyreqWqr.js} +1 -1
  244. package/web/app/immutable/chunks/{PslMlnNq.js → Dzp668Nh.js} +1 -1
  245. package/web/app/immutable/chunks/{DQ75EkSY.js → FM3MDwzB.js} +1 -1
  246. package/web/app/immutable/chunks/{DWH71rGR.js → HiIoMspb.js} +1 -1
  247. package/web/app/immutable/chunks/{nBmxMCff.js → HyJzJ05j.js} +1 -1
  248. package/web/app/immutable/chunks/{Drl447ub.js → IxxdIKNN.js} +1 -1
  249. package/web/app/immutable/chunks/{BI8cL-JN.js → JpEb3pk8.js} +1 -1
  250. package/web/app/immutable/chunks/{DQw0Iiac.js → JvFe2B29.js} +1 -1
  251. package/web/app/immutable/chunks/{C3EKiijc.js → KWtYfwVq.js} +1 -1
  252. package/web/app/immutable/chunks/{CYxt6gzD.js → KaOLys0u.js} +1 -1
  253. package/web/app/immutable/chunks/{BpQNd38A.js → OloUMTJw.js} +1 -1
  254. package/web/app/immutable/chunks/{1rpeT4f8.js → OsJD3pkm.js} +1 -1
  255. package/web/app/immutable/chunks/{CfYmMj5F.js → P7zPRuFC.js} +1 -1
  256. package/web/app/immutable/chunks/{BGrimfDs.js → QzxpbvSo.js} +1 -1
  257. package/web/app/immutable/chunks/{Qe8C2Z8H.js → RFYaUG5G.js} +1 -1
  258. package/web/app/immutable/chunks/{qhd9g-fv.js → RV6uszBL.js} +1 -1
  259. package/web/app/immutable/chunks/{Bs_TRDLE.js → Rsl51Ay4.js} +1 -1
  260. package/web/app/immutable/chunks/{D4d1iyeR.js → TPru2I57.js} +1 -1
  261. package/web/app/immutable/chunks/{BKKERvpk.js → TU7ngkX4.js} +1 -1
  262. package/web/app/immutable/chunks/{C_O50F5M.js → VdQBQKAO.js} +1 -1
  263. package/web/app/immutable/chunks/{Rzyk45bZ.js → WYNXUtt9.js} +1 -1
  264. package/web/app/immutable/chunks/{DAHeBTvv.js → XaYlDebr.js} +1 -1
  265. package/web/app/immutable/chunks/{Chj-azz7.js → Xgzr3BTD.js} +1 -1
  266. package/web/app/immutable/chunks/{Cm0Qloca.js → ZX798KkU.js} +1 -1
  267. package/web/app/immutable/chunks/{CfXgD_Pw.js → Zm39im0I.js} +1 -1
  268. package/web/app/immutable/chunks/{CebXSmXo.js → _U0OqOFt.js} +1 -1
  269. package/web/app/immutable/chunks/{Dd-LQrG1.js → aWBSU8IQ.js} +1 -1
  270. package/web/app/immutable/chunks/{CjGXnvXd.js → avlg638g.js} +6 -6
  271. package/web/app/immutable/chunks/{CgGsxeG7.js → axwUS21u.js} +1 -1
  272. package/web/app/immutable/chunks/{BgL-Z3DM.js → b776P7Kr.js} +1 -1
  273. package/web/app/immutable/chunks/{CzEoKeV2.js → f0YGFw5j.js} +3 -3
  274. package/web/app/immutable/chunks/{DyLaiVzG.js → fImwePKC.js} +1 -1
  275. package/web/app/immutable/chunks/{C-llZXnj.js → fKRR6mVT.js} +1 -1
  276. package/web/app/immutable/chunks/{C-HR_nje.js → g5QqP-QE.js} +1 -1
  277. package/web/app/immutable/chunks/{D4xriAny.js → h_d2oU3d.js} +1 -1
  278. package/web/app/immutable/chunks/{C2UL5Ler.js → iQDlfKDR.js} +1 -1
  279. package/web/app/immutable/chunks/jlu1ZSD8.js +1 -0
  280. package/web/app/immutable/chunks/{CnN8HXjd.js → jyQWudgn.js} +1 -1
  281. package/web/app/immutable/chunks/{BWfc0sSK.js → k48f0Jn8.js} +1 -1
  282. package/web/app/immutable/chunks/{BX0V9vST.js → kNaK7_sp.js} +2 -2
  283. package/web/app/immutable/chunks/{CRPm4Pj6.js → kRR2H6lu.js} +1 -1
  284. package/web/app/immutable/chunks/{BiYZcl7D.js → kkKMJ9w9.js} +1 -1
  285. package/web/app/immutable/chunks/{BHy9cRzo.js → l7sDKa65.js} +1 -1
  286. package/web/app/immutable/chunks/{D7AN7xLp.js → mFWmuyR-.js} +1 -1
  287. package/web/app/immutable/chunks/{BIjxJZ5i.js → qhttc0fS.js} +2 -2
  288. package/web/app/immutable/chunks/{BsY6roFy.js → rwibDzZr.js} +1 -1
  289. package/web/app/immutable/chunks/{Br0totzy.js → tNEZffSS.js} +1 -1
  290. package/web/app/immutable/chunks/{CaTfcRGE.js → uWX23oC4.js} +2 -2
  291. package/web/app/immutable/chunks/{D-osFWh4.js → zBrnybDu.js} +1 -1
  292. package/web/app/immutable/entry/{app.Ck7KNM4b.js → app.DHDoU_7H.js} +3 -3
  293. package/web/app/immutable/entry/start.nfTNgo5B.js +1 -0
  294. package/web/app/immutable/nodes/{0.BL1rQnVQ.js → 0.Cu9LrIhB.js} +1 -1
  295. package/web/app/immutable/nodes/{1.BLzCq48F.js → 1.D2vLkPwg.js} +1 -1
  296. package/web/app/immutable/nodes/{10.CQRco_pp.js → 10.CsTau1tB.js} +6 -6
  297. package/web/app/immutable/nodes/{11.CqlkrbW8.js → 11.BJH0IaNU.js} +1 -1
  298. package/web/app/immutable/nodes/{12.Dwdqbt9T.js → 12.DUMat2GN.js} +1 -1
  299. package/web/app/immutable/nodes/{13.jK1i4wo4.js → 13.BEiznOPk.js} +1 -1
  300. package/web/app/immutable/nodes/{14.DdHtnE9x.js → 14.DFolVj6c.js} +3 -3
  301. package/web/app/immutable/nodes/{15.Bl9Ro66C.js → 15.CODir9mj.js} +1 -1
  302. package/web/app/immutable/nodes/{16.DFPLVaTv.js → 16.cptOJ-f9.js} +1 -1
  303. package/web/app/immutable/nodes/{17.Dylz7DBe.js → 17.BVn1LtfR.js} +1 -1
  304. package/web/app/immutable/nodes/{18.CxblUMg0.js → 18.BLC8YWHJ.js} +1 -1
  305. package/web/app/immutable/nodes/{19.CeE6vjuX.js → 19.D4bkkQ_T.js} +2 -2
  306. package/web/app/immutable/nodes/{2.DjFjqnV0.js → 2.Dyr3gNeq.js} +4 -4
  307. package/web/app/immutable/nodes/{20.CXw8Twm7.js → 20.g9As4rvG.js} +1 -1
  308. package/web/app/immutable/nodes/{3.BCbxJGeq.js → 3.NGM8GOql.js} +1 -1
  309. package/web/app/immutable/nodes/{4.CL0JqE8n.js → 4.yPviv-Bq.js} +1 -1
  310. package/web/app/immutable/nodes/{5.hD1YagZR.js → 5.W4sBVxOK.js} +1 -1
  311. package/web/app/immutable/nodes/{6.776DAlfQ.js → 6.C_4emjsH.js} +1 -1
  312. package/web/app/immutable/nodes/{7.5BWaKbyF.js → 7.yUloHxmW.js} +1 -1
  313. package/web/app/immutable/nodes/{8.C_V2pSbF.js → 8.BT8o95-5.js} +1 -1
  314. package/web/app/immutable/nodes/{9.CBuIBgSj.js → 9.Izg3VgEv.js} +5 -5
  315. package/web/app/version.json +1 -1
  316. package/web/generated/paraglide.js +45 -45
  317. package/web/index.html +18 -18
  318. package/web/app/immutable/chunks/ByGh65n0.js +0 -411
  319. package/web/app/immutable/chunks/CLAmm_T1.js +0 -1
  320. package/web/app/immutable/chunks/CRSiOiSR.js +0 -1
  321. package/web/app/immutable/chunks/D7TF3ktW.js +0 -1
  322. package/web/app/immutable/chunks/DFh0CfhB.js +0 -1
  323. package/web/app/immutable/chunks/KnkAG0HD.js +0 -1
  324. package/web/app/immutable/chunks/prVatUwz.js +0 -3
  325. package/web/app/immutable/entry/start.DjIjqTgP.js +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["/app/immutable/chunks/uvhZkGDU.js","/app/immutable/chunks/B9vHutcJ.js","/app/immutable/chunks/Dms_DO28.js","/app/immutable/chunks/3SdAC2_C.js","/app/immutable/chunks/ChTqQfQN.js","/app/immutable/chunks/BBFoj-dS.js","/app/immutable/chunks/CIyUrgF0.js","/app/immutable/chunks/BwNrQXlF.js","/app/immutable/chunks/CLAmm_T1.js","/app/immutable/chunks/DxwfiAWm.js","/app/immutable/chunks/uXuxG9cN.js","/app/immutable/chunks/Bqd7fdCF.js","/app/immutable/chunks/C2UL5Ler.js","/app/immutable/chunks/_UjuBCOJ.js","/app/immutable/chunks/DPttSllj.js","/app/immutable/chunks/BwH4Bvte.js","/app/immutable/chunks/BFgvMDua.js","/app/immutable/chunks/CcJmuwXr.js","/app/immutable/assets/spinner.D_TRo5Hy.css","/app/immutable/chunks/B1CKzIA2.js","/app/immutable/chunks/TB9r2XJy.js","/app/immutable/chunks/UTM5G-w-.js","/app/immutable/assets/button.-yaUNjRS.css","/app/immutable/chunks/BGrimfDs.js","/app/immutable/chunks/Cu5e4npY.js","/app/immutable/chunks/aZdb_rCN.js","/app/immutable/chunks/BPQFiQQc.js","/app/immutable/chunks/96V4v2iI.js","/app/immutable/chunks/nxtepGjE.js","/app/immutable/chunks/Dn334wJv.js","/app/immutable/chunks/CIbfGsF-.js","/app/immutable/chunks/BbYWP3Ow.js","/app/immutable/chunks/D9tVylVS.js","/app/immutable/chunks/CfNIzRu8.js","/app/immutable/chunks/DU3vNstz.js","/app/immutable/chunks/XJv96NUg.js","/app/immutable/assets/notify.DylRFR3N.css","/app/immutable/chunks/D4ytz2EC.js","/app/immutable/chunks/CMiilI_P.js","/app/immutable/chunks/B_QPRXJ5.js","/app/immutable/chunks/BbhtQrkZ.js","/app/immutable/chunks/B5aYN90J.js","/app/immutable/chunks/BdWqymET.js","/app/immutable/chunks/BBWuirRW.js","/app/immutable/chunks/DONrLvvt.js"])))=>i.map(i=>d[i]);
2
- var Rt=Object.defineProperty;var xt=(e,t,n)=>t in e?Rt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>xt(e,typeof t!="symbol"?t+"":t,n);import{JH as A,m as be,nZ as R,wu as Pt,CB as Ge,ww as Bt,DP as Ye,cK as Ot,cL as Lt,n_ as Je,nM as Ut,i as ke,fV as $t,ma as Nt,cS as Ht}from"./B9vHutcJ.js";import{J as Ft,Z as Kt,dX as Be,cU as pe,dI as Wt,ax as qt,be as Xe,I as jt,e9 as Vt}from"./C2UL5Ler.js";import{e as zt,b as ae,F as Gt,y as re,_ as _e,G as Yt,C as Jt,W as Qe,v as Xt,u as Qt,M as Zt}from"./BBFoj-dS.js";import{D as Oe,a as en,d as tn}from"./CQcEqK4G.js";import{m as nn,g as Ze,r as an,k as rn,D as sn}from"./CZr8f1ch.js";import{e as on}from"./CL3a4Hm1.js";import{z as et,O as cn,R as ln}from"./Bqd7fdCF.js";import{a as dn}from"./ClxyT-Se.js";import{f as un}from"./B_vpadVO.js";import{bm as h,_ as fe}from"./CLAmm_T1.js";import{a8 as tt,aA as se,I as he,a as nt,n as at,cT as rt,e as st,aI as ot,M as mn,aa as pn,aV as Le,d as le,C as fn,cU as hn,U as gn,a4 as yn,aJ as wn,b_ as bn}from"./Klbdavqn.js";import{W as kn,L as _n,w as vn,R as Sn,h as it,M as Mn}from"./TB9r2XJy.js";import{l as H,i as An,n as In}from"./Cu5e4npY.js";import{b as Tn}from"./BbhtQrkZ.js";import{K as Cn,P as En,as as Dn,aC as Rn}from"./Bm6N2soI.js";import{b as Ue,c as xn,a as Pn}from"./_UjuBCOJ.js";import{m as Bn}from"./DQw0Iiac.js";import{m as On}from"./96V4v2iI.js";import"./3SdAC2_C.js";import"./CcJmuwXr.js";import"./BwNrQXlF.js";import"./ChTqQfQN.js";import"./BbYWP3Ow.js";import{i as ct}from"./Dms_DO28.js";import{C as Ln}from"./B5aYN90J.js";import{i as Un}from"./Dqi2LMpO.js";import{o as L,e as $n,l as z,s as C,n as ce,b as Nn,d as Hn,c as Fn}from"./CIyUrgF0.js";const Vr=A.createSelector((e,t)=>e.unreadTracking.dividerSessionByAgentId[t]??null),zr=A.createSelector(e=>e.unreadTracking.currentlyViewedAgentId),Gr=A.createSelector(e=>{const t=[];for(const s of Object.values(e.panelLayout.byWorkspaceId))for(const o of Object.values(s.panels))for(const i of o.tabs)i.type==="agent"&&i.agentId&&t.push(i.agentId);const n=Object.keys(e.unreadTracking.dividerSessionByAgentId),a=new Set(e.agentSessions.agentIdsByWorkspace[be]??[]);return{chiefCardVisible:e.sidebarNav.panelItem==="chief",chiefSessionAgentIds:n.filter(s=>a.has(s)),dividerSessionAgentIds:n,openAgentTabIds:t}});function Yr(e,t){if(e)return e.model}function Kn({messages:e,pendingInitialPrompt:t,pendingContextReferenceCount:n=0}){return e.length>0||!!t||n>0}function Jr({session:e,messages:t,pendingInitialPrompt:n,pendingContextReferenceCount:a=0}){return!(e?Ft(e):!1)&&!Kn({messages:t,pendingInitialPrompt:n,pendingContextReferenceCount:a})}function Xr(e){return Kt(e.messageMetadata)}function Wn(e){return{id:e.id,appMessageId:e.appMessageId,role:"user",timestamp:new Date(e.createdAt??0).toISOString(),contentBlocks:[...e.content?[{type:"text",text:e.content}]:[],...e.imageBlocks??[],...e.fileBlocks??[]],metadata:e.messageMetadata,...e.author!==void 0?{author:e.author}:{}}}function Qr(e){return Wn({...e,createdAt:Date.parse(e.queuedAt)})}const qn=8*1024*1024,jn=3*1024*1024;function Vn(e){return Math.ceil(Math.max(0,e)/3)*4}function zn(e){const t=e.promptBase64Bytes;return e.mimeType==="image/jpeg"&&Number.isSafeInteger(e.size)&&e.size>0&&e.size<=jn&&typeof t=="number"&&t===Vn(e.size)?t:null}async function lt(e,t,n,a,r=()=>{}){const s=()=>{if(!a())throw new Error("media-send-retired")};if(s(),r("overlay-render"),!n.exportMedia)throw new Error("media-export-unavailable");const o=dn(e.source,e.saved);if(o.length>1e4)throw new Error("media-animation-layer-limit");const i=[];for(const c of o)s(),i.push({...c,png:await nn(e.source,e.saved,c.atMs)});s(),r("export");const l=await n.exportMedia({outputVersion:zt,jobId:t,media:e,layers:i});if(s(),!l.ok)throw new Error(["media-export-failed",l.error].filter(Boolean).join(":"));return{jobId:t,value:l.value}}const ve={CLIPBOARD_WRITE:"dock-media:clipboard-write",CLIPBOARD_READ:"dock-media:clipboard-read",MENU:"dock-media:menu"};function $e(e,t){return Math.max(0,(e.pausedAt??t)-e.startedAt-(e.pausedMs??0))}function ge(e,t){if(!t?.startsWith(".intent/attachments/"))return;const n=t.split("/").map(encodeURIComponent).join("/"),a=tt(`intent://local/file/${n}`,e);return a?.kind==="video"?a.url:void 0}function Gn(e){const t=e.video==="full"?h.dock_captureEditor_videoFull_label():h.dock_captureEditor_videoHighlights_label(),n=e.voice==="audio"?h.dock_captureEditor_voiceAudio_label():e.voice==="transcript"?h.dock_captureEditor_voiceTranscript_label():h.dock_captureEditor_voiceOff_summary();return`${t} · ${n}`}function Yn(e,t,n,a){if(a?.error==="permission")return a.kind==="pick"?"accessibility":"screen";if(e==="permission"||t==="permission")return"screen";if(n?.startsWith("microphone-permission"))return"microphone";if(n?.startsWith("speech-permission"))return"speech"}const V=un;function Zr(e){const{view:t,items:n,local:a,labels:r,copy:s}=e,o=t.speech.error??t.speech.capability?.reason??null,i=Yn(t.captureError,t.clips.find(y=>y.status==="failed"&&y.error==="permission")?.error??null,o,t.annotationIssue),l=t.annotationIssue?.error==="unavailable"?s?.annotationUnavailable:void 0,c=t.annotationIssue,d=t.captureError==="permission",u=c?.error==="permission"&&c.kind!=="pick",g=c?.error==="permission"&&c.kind==="pick",p=o?.startsWith("speech-permission")?"speech":o?.startsWith("microphone-permission")||o==="permission"?"microphone":void 0,m={},w={},f=(y,D,$)=>{m[y]=D,$&&(w[y]=$)};s&&(d&&(f("capture",s.permission,"screen"),t.recording||f("record",s.permission,"screen")),u&&!t.annotating&&f("annotate",s.permission,"screen"),g&&(f("pick",s.accessibilityPermission,"accessibility"),t.tool==="pick"&&!t.annotating&&f("annotate",s.accessibilityPermission,"accessibility")),p&&!t.dictation&&f("mic",(o&&r.speechError?.(o))??s.speechPermission,p));const k=y=>{const D=w[y];D&&e.actions.onOpenSettings(D)},_=new Set(t.evidenceOwnedItemIds),I=t.clips.find(y=>y.status==="recording"),S=t.clips.length>=ae.clips,v=t.capabilities,B=t.speech.available,E=new Set(t.clips.filter(y=>y.status==="recording"||y.status==="placing"||!!y.media).flatMap(y=>y.captureHistory?.map(D=>D.image.id)??[])),P=[...t.tiles.filter(({image:y,marks:D})=>!!y.media||y.source!=="annotate"||!E.has(y.id)||D.some(({mark:$})=>!$.clipId)).map(({image:y,marks:D})=>({kind:"image",id:y.contextItemId,url:a.previews[y.id]??"",markCount:D.length,owner:"evidence",...a.previews[y.id]?{}:{status:"placing"}})),...t.clips.filter(y=>!y.discarding).map(y=>({kind:"clip",id:y.contextItemId??y.id,duration:V(y.status==="recording"?$e(y,a.now):y.durationMs),recording:y.status==="recording",...y.media?.saved?{summary:Gn(y.media.saved)}:{},...y.status==="ready"&&ge(e.workspaceId,y.path)?{url:ge(e.workspaceId,y.path)}:{},owner:"evidence",...y.status==="placing"?{status:"placing"}:{},...y.status==="failed"?{status:"failed",...y.error==="limit"?{error:h.dock_composer_clipTooLarge_error()}:{}}:{}})),...n.filter(y=>!_.has(y.id)).map(y=>({...y.imageData&&y.imageMimeType?{kind:"image",id:y.id,url:`data:${y.imageMimeType};base64,${y.imageData}`,markCount:0,file:{name:y.label,imageData:y.imageData,imageMimeType:y.imageMimeType}}:{kind:"file",id:y.id,name:y.label},owner:"attachment",...y.placementStatus==="placing"?{status:"placing"}:{},...y.placementStatus==="failed"?{status:"failed",error:y.placementError}:{}}))];return{mediaStatus:t.recording?{kind:"recording",label:r.recording}:t.annotating?{kind:"annotating",label:r.annotating}:void 0,...i?{settingsPane:i}:{},...l?{annotationNotice:l}:{},labels:r,attachments:P,...s?{placeholder:t.dictation?"":s.idle}:{},state:{captureRevision:t.captureAccepted,capturePending:t.capturePending,captureDisabled:!v.capture||t.captureDisabled,...t.captureDisabled?{captureTooltip:r.captureLimit}:{},captureMode:t.evidence?.annotation?"fullscreen":t.captureMode,captureModesAvailable:!!v.captureModes&&!t.evidence?.annotation,annotationActive:t.annotating,tool:t.tool,toolUsed:t.toolUsed,annotationDisabled:!v.annotate,recording:t.recording&&!I?.discarding,recordingDisabled:!!I?.discarding||!t.recording&&(!v.record||S),...S&&!t.recording?{recordingTooltip:r.clipLimit}:{},recordingTime:V(I?$e(I,a.now):0),dictating:!!t.dictation,dictationPending:t.speech.pending||t.dictation?.status==="transcribing",dictationDisabled:!B&&!t.dictation&&!m.mic,...t.speech.error&&r.speechError?{dictationTooltip:r.speechError(t.speech.error)}:{},dictationTime:t.dictation?V(a.now-t.dictation.startedAt):V(0),inputLevels:t.speech.levels,...Object.keys(m).length?{alerts:m}:{}},...e.actions,...t.fileAttachmentsEnabled===!1?{onEdit:void 0}:{},onAlert:k,beforeSubmit:e.beforeSubmit}}const Se=()=>globalThis.electronAPI,Jn=["image/png","image/jpeg","image/webp"],Ne=e=>Jn.includes(e??"")?e:null;function He(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return n}async function es(e,t){const{view:n,items:a,previews:r}=t,s=n.tiles.find(({image:c})=>c.id===e||c.contextItemId===e);if(s){const c=a.find(p=>p.id===s.image.contextItemId),d=s.image.media;if(s.image.mediaError)return null;if(d?.saved){if(!t.createSavedPreviewUrl||!t.revokeUrl)return null;const p={...d,saved:d.saved},m=await t.createSavedPreviewUrl(t.workspaceId,p);try{const w=await t.fetchBytes(m),f=p.saved.crop;return{kind:"image",name:c?.label||"screenshot.png",mimeType:"image/png",bytes:w,intent:{pixels:{mimeType:"image/png",width:Math.max(1,Math.round(f?.w??p.source.width)),height:Math.max(1,Math.round(f?.h??p.source.height)),displayScale:s.image.displayScale,capturedAt:s.image.capturedAt},raw:w,marks:[]}}}finally{t.revokeUrl(m)}}const u=Ne(c?.imageMimeType),g=r[s.image.id];return!c?.imageData||!u||!g?null:{kind:"image",name:c.label||"screenshot.png",mimeType:"image/png",bytes:await t.fetchBytes(g),intent:{pixels:{mimeType:u,width:s.image.width,height:s.image.height,displayScale:s.image.displayScale,capturedAt:s.image.capturedAt,...s.image.hash?{hash:s.image.hash}:{}},raw:He(c.imageData),marks:s.marks.map(({mark:p})=>({tool:p.tool,geometry:p.geometry,bounds:p.bounds,element:p.element}))}}}const o=n.clips.find(c=>c.id===e||c.contextItemId===e);if(o){const c=o.status==="ready"?ge(t.workspaceId,o.path):null;if(!c)return null;const d=a.find(g=>g.id===o.contextItemId),u=await t.fetchBytes(c);if(!Qn(u))throw new Error("Not a recording file");return{kind:"clip",name:d?.label||`recording-${o.id.slice(0,8)}.mp4`,mimeType:d?.attachmentMimeType||"video/mp4",bytes:u,durationMs:o.durationMs,hasMicAudio:o.hasMicAudio}}const i=a.find(c=>c.id===e),l=Ne(i?.imageMimeType);return i?.imageData&&l?{kind:"image",name:i.label||"image",mimeType:l,bytes:He(i.imageData)}:null}async function Xn(e){const t=await fetch(e);if(!t.ok)throw new Error(`Media request failed (${t.status})`);const n=new Uint8Array(await t.arrayBuffer()),a=Number(t.headers.get("content-length")??Number.NaN);if(n.byteLength===0||Number.isFinite(a)&&a!==n.byteLength)throw new Error("Media response was incomplete");return n}function Qn(e){return e.byteLength>8&&String.fromCharCode(...e.subarray(4,8))==="ftyp"}async function ts(e){try{return(await Se()?.invoke(ve.CLIPBOARD_WRITE,e))?.ok===!0}catch{return!1}}async function Zn(){try{return await Se()?.invoke(ve.CLIPBOARD_READ,{})??null}catch{return null}}async function ns(e){try{const t=await Se()?.invoke(ve.MENU,{canCut:e});return t?.action==="copy"||t?.action==="cut"?t.action:null}catch{return null}}const Fe=new WeakSet;async function ea(e,t){const[n]=e;if(e.length!==1||!n||n.size!==t.size)return!1;try{const a=await crypto.subtle.digest("SHA-256",await n.arrayBuffer());return Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")===t.sha256}catch{return!1}}function as(e,{onIntentMedia:t,isCurrent:n,read:a=Zn}){const r=e.clipboardData;if(Fe.has(e)||!r||r.files.length===0)return!1;const s=e.target,o=Array.from(r.files),i=r.types.filter(l=>l!=="Files").map(l=>[l,r.getData(l)]);return e.preventDefault(),e.stopImmediatePropagation(),a().catch(()=>null).then(async l=>{if(!n())return;if(l&&await ea(o,l)){n()&&t(l);return}if(!n()||!(s instanceof Node)||!s.isConnected)return;const c=new DataTransfer;for(const u of o)c.items.add(u);for(const[u,g]of i)c.setData(u,g);const d=new ClipboardEvent("paste",{clipboardData:c,bubbles:!0,cancelable:!0});Fe.add(d),s.dispatchEvent(d)}),!0}function ta(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function na(e){let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)}function dt(e){let t=0;return e.endsWith("==")?t=2:e.endsWith("=")&&(t=1),Math.floor(e.length*3/4)-t}async function aa(e){const t=await crypto.subtle.digest("SHA-256",e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}const ut={placeAttachment:ot,beginAttachmentUpload:st,sendAttachmentUploadChunk:rt,commitAttachmentUpload:at,abortAttachmentUpload:nt,getAttachmentInfo:he,mintIdempotencyKey:se};async function Me(e,t,n,a=ut){const{idempotencyKey:r}=n,s={...r!==void 0?{idempotencyKey:r}:{},...n.rawScreenshot!==void 0?{rawScreenshot:n.rawScreenshot}:{}},o=async m=>hn(m,r)?Le(e,r,a.getAttachmentInfo):void 0;if(dt(n.data)<=mn)try{return await a.placeAttachment(e,t,{data:n.data,mimeType:n.mimeType,...s})}catch(m){const w=await o(m);if(w)return w;throw m}const i=ta(n.data),l=await aa(i);let c,d;try{({uploadId:c,maxChunkBytes:d}=await a.beginAttachmentUpload(e,t,i.byteLength,l,{mimeType:n.mimeType,...s}))}catch(m){if(r!==void 0&&pn(m)){const w=await Le(e,r,a.getAttachmentInfo);if(w)return w}throw m}const u=Math.min(gn,d),g=Math.ceil(i.byteLength/u);let p=!1;try{for(let m=0;m<g;m++){const w=i.subarray(m*u,(m+1)*u);await a.sendAttachmentUploadChunk(c,m,na(w),e)}return p=!0,await a.commitAttachmentUpload(c,e)}catch(m){const w=p?await o(m):void 0;if(w)return w;throw await a.abortAttachmentUpload(c,e).catch(()=>{}),m}}function ra(e,t){return yn(e,`image-${Date.now()}-${t+1}`)}class Ae extends Error{constructor(n,a){super(n);Pe(this,"retryBlocks");this.name="ImagePlacementError",this.retryBlocks=a}}function sa(e,t){return e instanceof Ae?e.retryBlocks:t}async function oa(e,t,n=ut,a=()=>!0){const r=l=>(...c)=>(le(a),l(...c));n={placeAttachment:r(n.placeAttachment),beginAttachmentUpload:r(n.beginAttachmentUpload),sendAttachmentUploadChunk:r(n.sendAttachmentUploadChunk),commitAttachmentUpload:r(n.commitAttachmentUpload),abortAttachmentUpload:r(n.abortAttachmentUpload),getAttachmentInfo:r(n.getAttachmentInfo),mintIdempotencyKey:r(n.mintIdempotencyKey)};const s=[],o=[],i=[];for(let l=0;l<t.length;l++){le(a);const c=t[l];if("attachmentId"in c&&c.attachmentId){const p={type:"image",attachmentId:c.attachmentId,...c.mimeType?{mimeType:c.mimeType}:{}};s.push(p),o.push(p);continue}const d=c,u=d.placementFileName??ra(d.mimeType,l),g=n.mintIdempotencyKey(d.placementIdempotencyKey);try{const p=await Me(e,u,{data:d.data,mimeType:d.mimeType,...g!==void 0?{idempotencyKey:g}:{}},n),m={type:"image",attachmentId:p.attachmentId,...p.mimeType??d.mimeType?{mimeType:p.mimeType??d.mimeType}:{}};s.push(m),o.push(m)}catch(p){const m=fn(p);i.push(m?`${u} (${m})`:u),o.push(g!==void 0?{...d,placementIdempotencyKey:g,placementFileName:u}:d)}}if(i.length>0)throw new Ae(h.chat_imagePlacement_failed_error({names:i.join(", ")}),o);return le(a),s}const rs=Object.freeze(Object.defineProperty({__proto__:null,ImagePlacementError:Ae,base64DecodedBytes:dt,imageRetryBlocks:sa,placeImageAttachment:Me,toImageReferenceBlocks:oa},Symbol.toStringTag,{value:"Module"}));function mt(){try{return kn()}catch{return null}}function ia(){return{backendId:A.state.connections.windowBackendId??null,generation:A.state.daemonHealth.connectionGeneration,transport:mt()}}class Ie extends Error{constructor(){super("dock-evidence-backend-changed")}}function N(e,t){return async(...n)=>{e();const a=await t(...n);return e(),a}}const K={current:e=>mt()===e.transport&&A.state.daemonHealth.connectionGeneration===e.generation&&(A.state.connections.windowBackendId??null)===e.backendId,capabilities:()=>_n(),placeImage:(e,t,n,a)=>Me(e,t,n,{placeAttachment:N(a,ot),beginAttachmentUpload:N(a,st),sendAttachmentUploadChunk:N(a,rt),commitAttachmentUpload:N(a,at),abortAttachmentUpload:N(a,nt),getAttachmentInfo:N(a,he),mintIdempotencyKey:se}),lookup:(e,t)=>he({workspaceId:e,idempotencyKey:t}),mintKey:se};function Y(e){return K.current(e)}function ca(e,t){const n=A.state.dockConversation;return{generation:n.generation,authority:n.authority,clearRevision:R(n.drafts,Gt(e,t))?.clearRevision??0,binding:ia()}}function ss(e,t,n){const a=ca(e,t);return a.generation===n.generation&&a.authority===n.authority&&a.clearRevision===n.clearRevision&&Y(n.binding)}function pt(e,t){return()=>{if(!e.current(t))throw new Ie}}const ft=Object.freeze({rawRetention:!1,chiefAttachments:!1});function os(e){return e!==ft}const de=new Map;function ht(e,t=K){const n=`${e.backendId}:${e.generation}`;let a=de.get(n);if(!a){const r=pt(t,e);a=(async()=>{r();const o=await t.capabilities();r();const i=o?.server?.capabilities;if(!i||typeof i!="object")throw new Error("unobserved");return{rawRetention:i.rawScreenshotRetention===1,chiefAttachments:i.chiefAttachments===1}})().catch(()=>(de.delete(n),ft)),de.set(n,a)}return a}class ee extends Error{constructor(t){super(`dock-raw-retention-contract:${t}`),this.reason=t}}function gt(e){const{rpcCode:t,code:n}=e??{};return t===-32602||n==="INVALID_PARAMS"}function la(e){const t=String(e?.message??"");return gt(e)&&(t.includes("rawScreenshotExpired:")||/expired at .*not renewable/i.test(t))}function da(e,t,n){const a=e.rawScreenshot;if(!a||a.compositeAttachmentId!==t)return null;const r=Date.parse(a.expiresAt);return Number.isFinite(r)?a.expired||r<=n?"expired":{attachmentId:e.attachmentId,expiresAt:a.expiresAt}:null}function Ke(e){return{ok:!0,path:e.path,fileName:e.fileName,size:e.size,attachmentId:e.attachmentId,...e.mimeType?{mimeType:e.mimeType}:{},uploadedAt:e.uploadedAt,replayed:!0,...e.rawScreenshot?{rawScreenshot:e.rawScreenshot}:{}}}class ua extends Error{constructor(t,n){super("dock-evidence-placement-failed"),this.imageId=t,this.failure=n}}const We=e=>e.split("/")[1]?.replace("jpeg","jpg")||"png";async function ma(e){const t=e.api??K,n=e.now??Date.now,a=pt(t,e.binding);a();const r=await ht(e.binding,t);a();const s=r.rawRetention&&(e.workspaceId!==be||r.chiefAttachments),o=[];for(const i of e.images){const l=e.records[i.image.id];let c=l&&l.signature===i.signature&&l.workspaceId===e.workspaceId&&l.backendId===e.binding.backendId?l:{imageId:i.image.id,signature:i.signature,workspaceId:e.workspaceId,backendId:e.binding.backendId,compositeKey:null,rawKey:null,composite:null,raw:null,rawSettled:!1};const d=u=>{c=u,e.onRecord(u)};try{if(!c.composite){const g=c.compositeKey,p=t.mintKey(g??void 0)??null;p!==c.compositeKey&&d({...c,compositeKey:p});let m;g&&p===g&&(a(),m=await t.lookup(e.workspaceId,p).then(Ke).catch(()=>{}),a()),m||(a(),m=await t.placeImage(e.workspaceId,`screenshot-${i.image.id.slice(0,8)}.${We(i.composite.mimeType)}`,{data:i.composite.base64,mimeType:i.composite.mimeType,...p?{idempotencyKey:p}:{}},a),a()),d({...c,composite:{attachmentId:m.attachmentId,mimeType:m.mimeType??i.composite.mimeType}})}const u=c.composite.attachmentId;if(s&&i.raw&&!c.raw&&!c.rawSettled){const g=c.rawKey,p=t.mintKey(g??void 0);if(p){p!==c.rawKey&&d({...c,rawKey:p});let m;g&&p===g&&(a(),m=await t.lookup(e.workspaceId,p).then(Ke).catch(()=>{}),a());try{m||(a(),m=await t.placeImage(e.workspaceId,`screenshot-${i.image.id.slice(0,8)}-original.${We(i.raw.mimeType)}`,{data:i.raw.base64,mimeType:i.raw.mimeType,idempotencyKey:p,rawScreenshot:{compositeAttachmentId:u}},a),a());const w=da(m,u,n());if(w==="expired")d({...c,rawSettled:!0});else if(w)d({...c,raw:w});else throw new ee("echo")}catch(w){if(la(w))d({...c,rawSettled:!0});else throw w instanceof ee?w:gt(w)?new ee("refused"):w}}else throw new ee("unkeyed")}}catch(u){throw u instanceof Ie?u:new ua(i.image.id,u)}o.push(c)}return o}async function is(e,t,n,a){const r=()=>{if(!K.current(a))throw new Ie};r();const s=await K.placeImage(e,t,{...n,idempotencyKey:K.mintKey()},r);return r(),s}const pa=new Set(["invalid-saved-edit","media-send-retired","transcript-unavailable","transcript-pending","invalid-edit","stale-source","legacy-baked-marks","timing-unavailable","audio-unavailable","media-source-unavailable","media-export-unavailable","media-animation-layer-limit","media-export-failed","legacy-original-unavailable","capture-render-unavailable","capture-blur-unavailable","stale-source-pixels","not-a-screenshot","not-admitted","unavailable","dock-evidence-missing-pixels","draft-restore-failed","image-budget-exceeded"]),fa=new Set(["unavailable","permission","failed","busy","cancelled","limit"]);class O extends Error{constructor(t,n){super(n),this.stage=t,this.code=n,this.name="DockSendError"}}function oe(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";if(t.length>64)return"unclassified";const[n,...a]=t.split(":");return!pa.has(n)||a.length>2?"unclassified":n!=="media-export-failed"?a.length?"unclassified":n:[n,...a.map(r=>fa.has(r)?r:"other")].join(":")}function cs(e,t){return e instanceof O?{stage:e.stage,code:oe(e.code)}:{stage:t,code:oe(e)}}function W(e){if(!e||e.source.kind!=="recording")return!1;const t=e.source,n=e.saved??re(t,t.capturedMarks??[],e.transcript);if(n.video!=="full"||n.voice!=="audio"||n.crop||n.blurRegions.length||n.blurStrokes?.length)return!1;const a=_e(n,t,e.transcript);return t.visuals==="clean"?!a.errors.length&&!a.muted&&n.cuts.length===0&&!n.marks.some(r=>r.included)&&a.marks.length===0&&a.transcript===null&&a.kept.length===1&&a.kept[0].startMs===0&&a.kept[0].endMs===t.durationMs&&a.clips.length===1&&a.clips[0].startMs===0&&a.clips[0].endMs===t.durationMs:!a.errors.length&&!a.muted&&a.clips.length===1&&a.clips[0].startMs===0&&a.clips[0].endMs>=t.durationMs}async function ha(e,t,n,a,r,s){const o={images:{},files:[],frames:[],framePromptBytes:[],metadata:[]};let i="validate";try{const l=()=>{if(!r()||!Y(n))throw new Error("media-send-retired")};for(const c of[...t.images,...t.clips]){if(i="validate",s?.stage(i),c.mediaError)throw new Error("invalid-saved-edit");if(!c.media||W(c.media))continue;l();const d=structuredClone(c.media),u=d.source;let g=d.saved??re(u,u.capturedMarks??[],d.transcript),p=crypto.randomUUID();try{if(u.kind==="recording"&&g.voice==="transcript"&&d.transcript?.status!=="ready"){if(i="transcribe",s?.stage(i),!a?.transcribeMedia)throw new Error("transcript-unavailable");const f=await a.transcribeMedia({jobId:p,media:d});if(l(),!f.ok)throw new Error("transcript-unavailable");d.transcript=f.value,d.saved||(g=re(u,u.capturedMarks??[],d.transcript))}i="plan",s?.stage(i);const m=_e(g,u,d.transcript);if(m.errors.length)throw new Error(m.errors[0]);const w={id:c.id,kind:u.kind,video:g.video,voice:g.voice,transcript:m.transcript,batches:u.batches,marks:m.marks.map(({n:f,mark:k,frameAtMs:_})=>({n:f,id:k.id,at_ms:_,kind:k.kind,label:k.label,note:k.note,context:k.context,geometry:k.geometry}))};if(u.kind==="screenshot"){i="screenshot-source",s?.stage(i);const f=u.path.split("/").map(encodeURIComponent).join("/"),k=tt(`intent://local/file/${f}`,e);if(!k||k.kind!=="image")throw new Error("media-source-unavailable");const _=await Xn(k.url);l();const I={base64:Ze(_.buffer.slice(_.byteOffset,_.byteOffset+_.byteLength)),mimeType:/\.jpe?g$/i.test(u.path)?"image/jpeg":/\.webp$/i.test(u.path)?"image/webp":"image/png"};i="screenshot-render",s?.stage(i),o.images[c.id]=await an(u,g,I),l()}else{if(!m.clips.length){w.video_attachment_id=null,w.frames=[],w.kept_ms=[],o.metadata.push(w);continue}const f={...d,saved:g};let k=await a?.takePreparedRecording?.(f);if(k&&(p=k.jobId),l(),!k){if(!a)throw new Error("media-export-unavailable");k=await lt(f,p,a,()=>r()&&Y(n),S=>{i=S,s?.stage(S),S==="export"&&s?.exportAttempt(p)})}p=k.jobId,i="placement",s?.stage(i);const _=[k.value.video,...k.value.frames],I=[];for(let S=0;S<_.length;S++){l();const v=_[S],B=`capture-${c.id.slice(0,12)}-${S}.${S===0?"mp4":v.mimeType==="image/jpeg"?"jpg":"png"}`,E=await wn(e,B,{sourcePath:v.sourcePath,mimeType:v.mimeType,idempotencyKey:se()},void 0,void 0,()=>r()&&Y(n));l(),S===0?o.files.push({type:"file",attachmentId:E.attachmentId,fileName:B,mimeType:E.mimeType??v.mimeType,size:E.size}):(o.frames.push({type:"image",attachmentId:E.attachmentId,mimeType:v.mimeType==="image/jpeg"?"image/jpeg":"image/png"}),o.framePromptBytes.push(zn(v))),I.push(E.attachmentId)}w.video_attachment_id=I[0],w.frames=k.value.frames.map((S,v)=>({mark_id:S.markId,attachment_id:I[v+1]})),w.kept_ms=m.clips}o.metadata.push(w)}finally{s?.stage("release"),await a?.releaseMediaJob?.(p).catch(()=>{})}}return o}catch(l){throw l instanceof O?l:new O(i,oe(l))}}const ue=1568,ga=.85;async function ya(e,t){const n=Math.round(e.length*3/4/1024),a=await wa(e,t),{width:r,height:s}=a,o=r>ue||s>ue;let i=r,l=s;if(o){const f=ue/Math.max(r,s);i=Math.round(r*f),l=Math.round(s*f)}const c=new OffscreenCanvas(i,l),d=c.getContext("2d");if(!d)throw new Error("Failed to get 2D canvas context for image resize");d.drawImage(a,0,0,i,l);let u=t;ba(d,i,l)||(u="image/jpeg");const g=await c.convertToBlob({type:u,quality:u==="image/jpeg"?ga:void 0}),p=g.type||u,m=await ka(g),w=Math.round(m.length*3/4/1024);return console.debug(`[image-resize] ${r}×${s} → ${i}×${l} | ${t} → ${p} | ${n} KB → ${w} KB`),{base64:m,mimeType:p}}async function wa(e,t){const n=atob(e),a=new Uint8Array(n.length);for(let s=0;s<n.length;s++)a[s]=n.charCodeAt(s);const r=new Blob([a],{type:t});return createImageBitmap(r)}function ba(e,t,n){const r=e.getImageData(0,0,t,n).data;for(let s=3;s<r.length;s+=4)if(r[s]<255)return!0;return!1}async function ka(e){const t=await e.arrayBuffer(),n=new Uint8Array(t);let a="";for(let r=0;r<n.length;r++)a+=String.fromCharCode(n[r]);return btoa(a)}const T={...Oe,badge:Oe.badgeRadius*2};function _a(e,t,n=1,a=0){const r=Math.max(1,e.displayScale)*n,s=[],o=i=>i*n;for(const{n:i,mark:l}of t){const c=l.geometry;if(c.kind==="rect")s.push({kind:"rect",x:o(c.x),y:o(c.y),w:o(c.w),h:o(c.h),width:T.stroke*r});else if(c.kind==="path")s.push({kind:"path",points:c.points.map(m=>({x:o(m.x),y:o(m.y)})),width:T.pen*r});else{const m={x:o(c.from.x),y:o(c.from.y)},w={x:o(c.to.x),y:o(c.to.y)};s.push({kind:"arrow",from:m,to:w,head:Ia(m,w,T.arrowHead*r),width:T.stroke*r})}if(!T.showNumbers)continue;const d=Math.max(a,T.badge/2*r),u=o(l.bounds.x+l.bounds.w),g=o(l.bounds.y),p=tn({x:o(l.bounds.x),y:g,w:u-o(l.bounds.x),h:o(l.bounds.h)},{x:0,y:0,w:o(e.width),h:o(e.height)},r,d);s.push({kind:"badge",...p,radius:d,label:String(i),font:d*T.badgeTextScale})}return s}function va(e,t){"letterSpacing"in e&&(e.letterSpacing="0px"),"wordSpacing"in e&&(e.wordSpacing="0px");const n=(a,r,s)=>{e.strokeStyle=T.halo,e.lineWidth=a+T.haloWidth*r,s(),e.strokeStyle=T.accent,e.lineWidth=a,s()};e.strokeStyle=T.accent,e.lineCap="round",e.lineJoin="round";for(const a of t)if(a.kind==="rect")n(a.width,a.width/T.stroke,()=>e.strokeRect(a.x,a.y,a.w,a.h));else if(a.kind==="path"||a.kind==="arrow"){e.lineWidth=a.width,e.beginPath();const r=a.kind==="path"?a.points:[a.from,a.to];a.kind==="arrow"&&r.forEach((o,i)=>i?e.lineTo(o.x,o.y):e.moveTo(o.x,o.y)),a.kind==="arrow"&&(e.moveTo(a.head.left.x,a.head.left.y),e.lineTo(a.to.x,a.to.y),e.lineTo(a.head.right.x,a.head.right.y));const s=a.kind==="path"?new Path2D(en(a.points)):null;n(a.width,a.width/(a.kind==="path"?T.pen:T.stroke),()=>s?e.stroke(s):e.stroke())}else e.fillStyle=T.paper,e.beginPath(),e.arc(a.x,a.y,a.radius,0,Math.PI*2),e.closePath(),e.fill(),e.strokeStyle=T.accent,e.lineWidth=T.badgeOutline*a.radius/T.badgeRadius,e.stroke(),e.fillStyle=T.ink,e.font=`600 ${a.font}px ${T.badgeFontFamily}`,e.textAlign="center",e.textBaseline="middle",e.fillText(a.label,a.x,a.y)}async function Sa(e,t){const n=Uint8Array.from(atob(e),a=>a.charCodeAt(0));return createImageBitmap(new Blob([n],{type:t}))}async function Ma(e){const t=await e.convertToBlob({type:"image/png"});return Ze(await t.arrayBuffer())}async function yt(e,t,n,a,r=0){await rn();const s=await Sa(e.base64,e.mimeType);try{const o=Math.min(1,a/Math.max(t.width,t.height)),i=new OffscreenCanvas(Math.max(1,Math.round(t.width*o)),Math.max(1,Math.round(t.height*o))),l=i.getContext("2d");if(!l)throw new Error("dock-evidence-canvas-unavailable");return l.drawImage(s,0,0,i.width,i.height),va(l,_a(t,n,o,r)),i}finally{s.close()}}async function Aa(e,t,n){const a=await yt(e,t,n,Math.max(t.width,t.height));return ya(await Ma(a),"image/png")}async function ls(e,t,n,a=384){const r=await yt(e,t,n,a,a/32);return URL.createObjectURL(await r.convertToBlob({type:"image/png"}))}function Ia(e,t,n=T.arrowHead){const a=Math.atan2(t.y-e.y,t.x-e.x),r=T.arrowSpread;return{left:{x:t.x-n*Math.cos(a-r),y:t.y-n*Math.sin(a-r)},right:{x:t.x-n*Math.cos(a+r),y:t.y-n*Math.sin(a+r)}}}function ds(e,t){const n=Yt(t??void 0),a=new Set(t?.clips.filter(r=>!!r.media&&!W(r.media)).map(r=>r.contextItemId));return e.filter(r=>!n.has(r.id)&&!a.has(r.id))}async function us({workspaceId:e,agentId:t,evidence:n,clickedItems:a,sendItems:r,clickedPayload:s,binding:o,service:i,current:l,onRecord:c,timing:d}){const u=()=>{if(!l()||!Y(o))throw new O("validate","media-send-retired")};if(u(),n?.images.some(b=>b.mediaError)||n?.clips.some(b=>b.mediaError))throw new O("validate","invalid-saved-edit");const g=b=>!!b.media&&!W(b.media),p=n?{workspaceId:e,agentId:t,appUrl:`intent://local/workspace/${encodeURIComponent(e)}`,clipAttachmentIds:Object.fromEntries(n.clips.map(b=>[b.id,a.find(M=>M.id===b.contextItemId)?.attachmentId??null]))}:null;for(const b of n?.clips??[]){if(!b.media||!W(b.media))continue;const M=a.find(Q=>Q.id===b.contextItemId);if(!M||M.attachmentId!==b.media.source.attachmentId||M.path!==b.media.source.path||M.placementStatus!==void 0&&M.placementStatus!=="placed")throw new O("validate","legacy-original-unavailable")}const m=n?await ha(e,n,o,i,l,d):{images:{},files:[],frames:[],framePromptBytes:[],metadata:[]},w=new Set(n?.clips.filter(b=>g(b)||!!b.media&&W(b.media)).map(b=>b.id)),f=new Set(n?.clips.filter(b=>w.has(b.id)).flatMap(b=>(b.captureHistory??[]).map(M=>M.image.id))),k=(n?.images??[]).filter(b=>b.source!=="annotate"||!!b.media||!f.has(b.id)||n.marks.some(M=>M.imageId===b.id&&!(M.clipId&&w.has(M.clipId))));d?.stage("burn");let _=[];try{_=n?await Ta({...n,images:k},a,m.images):[]}catch(b){throw new O("burn",oe(b))}if(m.framePromptBytes.reduce((b,M)=>b+(M??0),0)>qn)throw new O("validate","image-budget-exceeded");const S=new Set(n?.images.filter(b=>b.media).map(b=>b.id)),v=n?{...n,images:k.map(b=>m.images[b.id]?{...b,width:m.images[b.id].width,height:m.images[b.id].height}:b),clips:n.clips.filter(b=>!g(b)),marks:n.marks.filter(b=>!S.has(b.imageId)&&!n.clips.some(M=>g(M)&&M.id===b.clipId))}:null;u();const B=m.metadata.some(b=>typeof b.transcript=="string"&&b.transcript.trim());if(!s.text.trim()&&!r.length&&!s.workspaceContextStr?.trim()&&!_.length&&!m.files.length&&!m.frames.length&&!s.imageBlocks?.length&&!s.fileBlocks?.length&&!B)return null;let E=_,P=null;d?.stage("placement");const xe=n?await ht(o):null;if(u(),n&&(e!==be||xe?.chiefAttachments)){const b=await ma({workspaceId:e,binding:o,images:k.map((M,Q)=>{const Z=a.find(Dt=>Dt.id===M.contextItemId);return{image:M,signature:Jt(n,M.id),composite:{base64:_[Q].data,mimeType:_[Q].mimeType},raw:!M.media&&Z?.imageData&&Z.imageMimeType?{base64:Z.imageData,mimeType:Z.imageMimeType}:null}}),records:n?.placements??{},onRecord:c});u(),E=b.map(M=>({type:"image",attachmentId:M.composite.attachmentId,mimeType:M.composite.mimeType})),P=Object.fromEntries(b.map(M=>[M.imageId,{attachmentId:M.composite.attachmentId,raw:M.raw}]))}const y=new Map(n?Qe(n).map(({n:b,mark:M})=>[M.id,b]):[]),D=p&&P?{...p,imageAttachments:P,markNumbers:y}:p&&{...p,markNumbers:y},$=n&&D?{...s,imageBlocks:[...E,...m.frames,...s.imageBlocks??[]],fileBlocks:[...s.fileBlocks??[],...m.files],workspaceContextStr:[Qt(v,D),m.metadata.length?`[Edited capture outputs]
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["/app/immutable/chunks/Bhq56Jsu.js","/app/immutable/chunks/CiKoEJ2m.js","/app/immutable/chunks/Dms_DO28.js","/app/immutable/chunks/3SdAC2_C.js","/app/immutable/chunks/ChTqQfQN.js","/app/immutable/chunks/CHIxjTWu.js","/app/immutable/chunks/CIyUrgF0.js","/app/immutable/chunks/CGmYraIa.js","/app/immutable/chunks/CtfEuoOH.js","/app/immutable/chunks/DxwfiAWm.js","/app/immutable/chunks/uXuxG9cN.js","/app/immutable/chunks/Bqd7fdCF.js","/app/immutable/chunks/iQDlfKDR.js","/app/immutable/chunks/B1lpukIv.js","/app/immutable/chunks/COofQgO0.js","/app/immutable/chunks/BZ27qIg1.js","/app/immutable/chunks/DynUeYUu.js","/app/immutable/chunks/B26ZHg3s.js","/app/immutable/assets/spinner.D_TRo5Hy.css","/app/immutable/chunks/CnFZbWXv.js","/app/immutable/chunks/CT8vPg_p.js","/app/immutable/chunks/BpezAJRw.js","/app/immutable/assets/button.-yaUNjRS.css","/app/immutable/chunks/QzxpbvSo.js","/app/immutable/chunks/DMEIbJII.js","/app/immutable/chunks/BU3y3Xes.js","/app/immutable/chunks/BkcCJyDK.js","/app/immutable/chunks/C3jMXj_V.js","/app/immutable/chunks/D9R5fzn8.js","/app/immutable/chunks/Dn334wJv.js","/app/immutable/chunks/DFKhOU69.js","/app/immutable/chunks/BFfRQORP.js","/app/immutable/chunks/D9tVylVS.js","/app/immutable/chunks/Bx1P9uW7.js","/app/immutable/chunks/DU3vNstz.js","/app/immutable/chunks/XJv96NUg.js","/app/immutable/assets/notify.DylRFR3N.css","/app/immutable/chunks/CjpWOZGa.js","/app/immutable/chunks/CMiilI_P.js","/app/immutable/chunks/B_QPRXJ5.js","/app/immutable/chunks/CVtLV3_x.js","/app/immutable/chunks/B5aYN90J.js","/app/immutable/chunks/BdWqymET.js","/app/immutable/chunks/BBWuirRW.js","/app/immutable/chunks/DONrLvvt.js"])))=>i.map(i=>d[i]);
2
+ var Rt=Object.defineProperty;var xt=(e,t,n)=>t in e?Rt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>xt(e,typeof t!="symbol"?t+"":t,n);import{JH as A,m as be,nZ as R,wu as Pt,CB as Ge,ww as Bt,DP as Ye,cK as Ot,cL as Lt,n_ as Je,nM as Ut,i as ke,fV as $t,ma as Nt,cS as Ht}from"./CiKoEJ2m.js";import{J as Ft,Z as Kt,dX as Be,cU as pe,dI as Wt,ax as qt,be as Xe,I as jt,e9 as Vt}from"./iQDlfKDR.js";import{e as zt,b as ae,F as Gt,y as re,_ as _e,G as Yt,C as Jt,W as Qe,v as Xt,u as Qt,M as Zt}from"./CHIxjTWu.js";import{D as Oe,a as en,d as tn}from"./CQcEqK4G.js";import{m as nn,g as Ze,r as an,k as rn,D as sn}from"./DlljGo_I.js";import{e as on}from"./CL3a4Hm1.js";import{z as et,O as cn,R as ln}from"./Bqd7fdCF.js";import{a as dn}from"./CwCvyVGi.js";import{f as un}from"./Cxc8q3rR.js";import{bm as h,_ as fe}from"./CtfEuoOH.js";import{a8 as tt,aA as se,I as he,a as nt,n as at,cT as rt,e as st,aI as ot,M as mn,aa as pn,aV as Le,d as le,C as fn,cU as hn,U as gn,a4 as yn,aJ as wn,b_ as bn}from"./B4kHSLJr.js";import{W as kn,L as _n,w as vn,R as Sn,h as it,M as Mn}from"./CT8vPg_p.js";import{l as H,i as An,n as In}from"./DMEIbJII.js";import{b as Tn}from"./CVtLV3_x.js";import{K as Cn,P as En,as as Dn,aC as Rn}from"./COJ7FcW0.js";import{b as Ue,c as xn,a as Pn}from"./B1lpukIv.js";import{m as Bn}from"./JvFe2B29.js";import{m as On}from"./C3jMXj_V.js";import"./3SdAC2_C.js";import"./B26ZHg3s.js";import"./CGmYraIa.js";import"./ChTqQfQN.js";import"./BFfRQORP.js";import{i as ct}from"./Dms_DO28.js";import{C as Ln}from"./B5aYN90J.js";import{i as Un}from"./DoJ49Zrl.js";import{o as L,e as $n,l as z,s as C,n as ce,b as Nn,d as Hn,c as Fn}from"./CIyUrgF0.js";const Vr=A.createSelector((e,t)=>e.unreadTracking.dividerSessionByAgentId[t]??null),zr=A.createSelector(e=>e.unreadTracking.currentlyViewedAgentId),Gr=A.createSelector(e=>{const t=[];for(const s of Object.values(e.panelLayout.byWorkspaceId))for(const o of Object.values(s.panels))for(const i of o.tabs)i.type==="agent"&&i.agentId&&t.push(i.agentId);const n=Object.keys(e.unreadTracking.dividerSessionByAgentId),a=new Set(e.agentSessions.agentIdsByWorkspace[be]??[]);return{chiefCardVisible:e.sidebarNav.panelItem==="chief",chiefSessionAgentIds:n.filter(s=>a.has(s)),dividerSessionAgentIds:n,openAgentTabIds:t}});function Yr(e,t){if(e)return e.model}function Kn({messages:e,pendingInitialPrompt:t,pendingContextReferenceCount:n=0}){return e.length>0||!!t||n>0}function Jr({session:e,messages:t,pendingInitialPrompt:n,pendingContextReferenceCount:a=0}){return!(e?Ft(e):!1)&&!Kn({messages:t,pendingInitialPrompt:n,pendingContextReferenceCount:a})}function Xr(e){return Kt(e.messageMetadata)}function Wn(e){return{id:e.id,appMessageId:e.appMessageId,role:"user",timestamp:new Date(e.createdAt??0).toISOString(),contentBlocks:[...e.content?[{type:"text",text:e.content}]:[],...e.imageBlocks??[],...e.fileBlocks??[]],metadata:e.messageMetadata,...e.author!==void 0?{author:e.author}:{}}}function Qr(e){return Wn({...e,createdAt:Date.parse(e.queuedAt)})}const qn=8*1024*1024,jn=3*1024*1024;function Vn(e){return Math.ceil(Math.max(0,e)/3)*4}function zn(e){const t=e.promptBase64Bytes;return e.mimeType==="image/jpeg"&&Number.isSafeInteger(e.size)&&e.size>0&&e.size<=jn&&typeof t=="number"&&t===Vn(e.size)?t:null}async function lt(e,t,n,a,r=()=>{}){const s=()=>{if(!a())throw new Error("media-send-retired")};if(s(),r("overlay-render"),!n.exportMedia)throw new Error("media-export-unavailable");const o=dn(e.source,e.saved);if(o.length>1e4)throw new Error("media-animation-layer-limit");const i=[];for(const c of o)s(),i.push({...c,png:await nn(e.source,e.saved,c.atMs)});s(),r("export");const l=await n.exportMedia({outputVersion:zt,jobId:t,media:e,layers:i});if(s(),!l.ok)throw new Error(["media-export-failed",l.error].filter(Boolean).join(":"));return{jobId:t,value:l.value}}const ve={CLIPBOARD_WRITE:"dock-media:clipboard-write",CLIPBOARD_READ:"dock-media:clipboard-read",MENU:"dock-media:menu"};function $e(e,t){return Math.max(0,(e.pausedAt??t)-e.startedAt-(e.pausedMs??0))}function ge(e,t){if(!t?.startsWith(".intent/attachments/"))return;const n=t.split("/").map(encodeURIComponent).join("/"),a=tt(`intent://local/file/${n}`,e);return a?.kind==="video"?a.url:void 0}function Gn(e){const t=e.video==="full"?h.dock_captureEditor_videoFull_label():h.dock_captureEditor_videoHighlights_label(),n=e.voice==="audio"?h.dock_captureEditor_voiceAudio_label():e.voice==="transcript"?h.dock_captureEditor_voiceTranscript_label():h.dock_captureEditor_voiceOff_summary();return`${t} · ${n}`}function Yn(e,t,n,a){if(a?.error==="permission")return a.kind==="pick"?"accessibility":"screen";if(e==="permission"||t==="permission")return"screen";if(n?.startsWith("microphone-permission"))return"microphone";if(n?.startsWith("speech-permission"))return"speech"}const V=un;function Zr(e){const{view:t,items:n,local:a,labels:r,copy:s}=e,o=t.speech.error??t.speech.capability?.reason??null,i=Yn(t.captureError,t.clips.find(y=>y.status==="failed"&&y.error==="permission")?.error??null,o,t.annotationIssue),l=t.annotationIssue?.error==="unavailable"?s?.annotationUnavailable:void 0,c=t.annotationIssue,d=t.captureError==="permission",u=c?.error==="permission"&&c.kind!=="pick",g=c?.error==="permission"&&c.kind==="pick",p=o?.startsWith("speech-permission")?"speech":o?.startsWith("microphone-permission")||o==="permission"?"microphone":void 0,m={},w={},f=(y,D,$)=>{m[y]=D,$&&(w[y]=$)};s&&(d&&(f("capture",s.permission,"screen"),t.recording||f("record",s.permission,"screen")),u&&!t.annotating&&f("annotate",s.permission,"screen"),g&&(f("pick",s.accessibilityPermission,"accessibility"),t.tool==="pick"&&!t.annotating&&f("annotate",s.accessibilityPermission,"accessibility")),p&&!t.dictation&&f("mic",(o&&r.speechError?.(o))??s.speechPermission,p));const k=y=>{const D=w[y];D&&e.actions.onOpenSettings(D)},_=new Set(t.evidenceOwnedItemIds),I=t.clips.find(y=>y.status==="recording"),S=t.clips.length>=ae.clips,v=t.capabilities,B=t.speech.available,E=new Set(t.clips.filter(y=>y.status==="recording"||y.status==="placing"||!!y.media).flatMap(y=>y.captureHistory?.map(D=>D.image.id)??[])),P=[...t.tiles.filter(({image:y,marks:D})=>!!y.media||y.source!=="annotate"||!E.has(y.id)||D.some(({mark:$})=>!$.clipId)).map(({image:y,marks:D})=>({kind:"image",id:y.contextItemId,url:a.previews[y.id]??"",markCount:D.length,owner:"evidence",...a.previews[y.id]?{}:{status:"placing"}})),...t.clips.filter(y=>!y.discarding).map(y=>({kind:"clip",id:y.contextItemId??y.id,duration:V(y.status==="recording"?$e(y,a.now):y.durationMs),recording:y.status==="recording",...y.media?.saved?{summary:Gn(y.media.saved)}:{},...y.status==="ready"&&ge(e.workspaceId,y.path)?{url:ge(e.workspaceId,y.path)}:{},owner:"evidence",...y.status==="placing"?{status:"placing"}:{},...y.status==="failed"?{status:"failed",...y.error==="limit"?{error:h.dock_composer_clipTooLarge_error()}:{}}:{}})),...n.filter(y=>!_.has(y.id)).map(y=>({...y.imageData&&y.imageMimeType?{kind:"image",id:y.id,url:`data:${y.imageMimeType};base64,${y.imageData}`,markCount:0,file:{name:y.label,imageData:y.imageData,imageMimeType:y.imageMimeType}}:{kind:"file",id:y.id,name:y.label},owner:"attachment",...y.placementStatus==="placing"?{status:"placing"}:{},...y.placementStatus==="failed"?{status:"failed",error:y.placementError}:{}}))];return{mediaStatus:t.recording?{kind:"recording",label:r.recording}:t.annotating?{kind:"annotating",label:r.annotating}:void 0,...i?{settingsPane:i}:{},...l?{annotationNotice:l}:{},labels:r,attachments:P,...s?{placeholder:t.dictation?"":s.idle}:{},state:{captureRevision:t.captureAccepted,capturePending:t.capturePending,captureDisabled:!v.capture||t.captureDisabled,...t.captureDisabled?{captureTooltip:r.captureLimit}:{},captureMode:t.evidence?.annotation?"fullscreen":t.captureMode,captureModesAvailable:!!v.captureModes&&!t.evidence?.annotation,annotationActive:t.annotating,tool:t.tool,toolUsed:t.toolUsed,annotationDisabled:!v.annotate,recording:t.recording&&!I?.discarding,recordingDisabled:!!I?.discarding||!t.recording&&(!v.record||S),...S&&!t.recording?{recordingTooltip:r.clipLimit}:{},recordingTime:V(I?$e(I,a.now):0),dictating:!!t.dictation,dictationPending:t.speech.pending||t.dictation?.status==="transcribing",dictationDisabled:!B&&!t.dictation&&!m.mic,...t.speech.error&&r.speechError?{dictationTooltip:r.speechError(t.speech.error)}:{},dictationTime:t.dictation?V(a.now-t.dictation.startedAt):V(0),inputLevels:t.speech.levels,...Object.keys(m).length?{alerts:m}:{}},...e.actions,...t.fileAttachmentsEnabled===!1?{onEdit:void 0}:{},onAlert:k,beforeSubmit:e.beforeSubmit}}const Se=()=>globalThis.electronAPI,Jn=["image/png","image/jpeg","image/webp"],Ne=e=>Jn.includes(e??"")?e:null;function He(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a+=1)n[a]=t.charCodeAt(a);return n}async function es(e,t){const{view:n,items:a,previews:r}=t,s=n.tiles.find(({image:c})=>c.id===e||c.contextItemId===e);if(s){const c=a.find(p=>p.id===s.image.contextItemId),d=s.image.media;if(s.image.mediaError)return null;if(d?.saved){if(!t.createSavedPreviewUrl||!t.revokeUrl)return null;const p={...d,saved:d.saved},m=await t.createSavedPreviewUrl(t.workspaceId,p);try{const w=await t.fetchBytes(m),f=p.saved.crop;return{kind:"image",name:c?.label||"screenshot.png",mimeType:"image/png",bytes:w,intent:{pixels:{mimeType:"image/png",width:Math.max(1,Math.round(f?.w??p.source.width)),height:Math.max(1,Math.round(f?.h??p.source.height)),displayScale:s.image.displayScale,capturedAt:s.image.capturedAt},raw:w,marks:[]}}}finally{t.revokeUrl(m)}}const u=Ne(c?.imageMimeType),g=r[s.image.id];return!c?.imageData||!u||!g?null:{kind:"image",name:c.label||"screenshot.png",mimeType:"image/png",bytes:await t.fetchBytes(g),intent:{pixels:{mimeType:u,width:s.image.width,height:s.image.height,displayScale:s.image.displayScale,capturedAt:s.image.capturedAt,...s.image.hash?{hash:s.image.hash}:{}},raw:He(c.imageData),marks:s.marks.map(({mark:p})=>({tool:p.tool,geometry:p.geometry,bounds:p.bounds,element:p.element}))}}}const o=n.clips.find(c=>c.id===e||c.contextItemId===e);if(o){const c=o.status==="ready"?ge(t.workspaceId,o.path):null;if(!c)return null;const d=a.find(g=>g.id===o.contextItemId),u=await t.fetchBytes(c);if(!Qn(u))throw new Error("Not a recording file");return{kind:"clip",name:d?.label||`recording-${o.id.slice(0,8)}.mp4`,mimeType:d?.attachmentMimeType||"video/mp4",bytes:u,durationMs:o.durationMs,hasMicAudio:o.hasMicAudio}}const i=a.find(c=>c.id===e),l=Ne(i?.imageMimeType);return i?.imageData&&l?{kind:"image",name:i.label||"image",mimeType:l,bytes:He(i.imageData)}:null}async function Xn(e){const t=await fetch(e);if(!t.ok)throw new Error(`Media request failed (${t.status})`);const n=new Uint8Array(await t.arrayBuffer()),a=Number(t.headers.get("content-length")??Number.NaN);if(n.byteLength===0||Number.isFinite(a)&&a!==n.byteLength)throw new Error("Media response was incomplete");return n}function Qn(e){return e.byteLength>8&&String.fromCharCode(...e.subarray(4,8))==="ftyp"}async function ts(e){try{return(await Se()?.invoke(ve.CLIPBOARD_WRITE,e))?.ok===!0}catch{return!1}}async function Zn(){try{return await Se()?.invoke(ve.CLIPBOARD_READ,{})??null}catch{return null}}async function ns(e){try{const t=await Se()?.invoke(ve.MENU,{canCut:e});return t?.action==="copy"||t?.action==="cut"?t.action:null}catch{return null}}const Fe=new WeakSet;async function ea(e,t){const[n]=e;if(e.length!==1||!n||n.size!==t.size)return!1;try{const a=await crypto.subtle.digest("SHA-256",await n.arrayBuffer());return Array.from(new Uint8Array(a),s=>s.toString(16).padStart(2,"0")).join("")===t.sha256}catch{return!1}}function as(e,{onIntentMedia:t,isCurrent:n,read:a=Zn}){const r=e.clipboardData;if(Fe.has(e)||!r||r.files.length===0)return!1;const s=e.target,o=Array.from(r.files),i=r.types.filter(l=>l!=="Files").map(l=>[l,r.getData(l)]);return e.preventDefault(),e.stopImmediatePropagation(),a().catch(()=>null).then(async l=>{if(!n())return;if(l&&await ea(o,l)){n()&&t(l);return}if(!n()||!(s instanceof Node)||!s.isConnected)return;const c=new DataTransfer;for(const u of o)c.items.add(u);for(const[u,g]of i)c.setData(u,g);const d=new ClipboardEvent("paste",{clipboardData:c,bubbles:!0,cancelable:!0});Fe.add(d),s.dispatchEvent(d)}),!0}function ta(e){const t=atob(e),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);return n}function na(e){let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)}function dt(e){let t=0;return e.endsWith("==")?t=2:e.endsWith("=")&&(t=1),Math.floor(e.length*3/4)-t}async function aa(e){const t=await crypto.subtle.digest("SHA-256",e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength));return Array.from(new Uint8Array(t)).map(n=>n.toString(16).padStart(2,"0")).join("")}const ut={placeAttachment:ot,beginAttachmentUpload:st,sendAttachmentUploadChunk:rt,commitAttachmentUpload:at,abortAttachmentUpload:nt,getAttachmentInfo:he,mintIdempotencyKey:se};async function Me(e,t,n,a=ut){const{idempotencyKey:r}=n,s={...r!==void 0?{idempotencyKey:r}:{},...n.rawScreenshot!==void 0?{rawScreenshot:n.rawScreenshot}:{}},o=async m=>hn(m,r)?Le(e,r,a.getAttachmentInfo):void 0;if(dt(n.data)<=mn)try{return await a.placeAttachment(e,t,{data:n.data,mimeType:n.mimeType,...s})}catch(m){const w=await o(m);if(w)return w;throw m}const i=ta(n.data),l=await aa(i);let c,d;try{({uploadId:c,maxChunkBytes:d}=await a.beginAttachmentUpload(e,t,i.byteLength,l,{mimeType:n.mimeType,...s}))}catch(m){if(r!==void 0&&pn(m)){const w=await Le(e,r,a.getAttachmentInfo);if(w)return w}throw m}const u=Math.min(gn,d),g=Math.ceil(i.byteLength/u);let p=!1;try{for(let m=0;m<g;m++){const w=i.subarray(m*u,(m+1)*u);await a.sendAttachmentUploadChunk(c,m,na(w),e)}return p=!0,await a.commitAttachmentUpload(c,e)}catch(m){const w=p?await o(m):void 0;if(w)return w;throw await a.abortAttachmentUpload(c,e).catch(()=>{}),m}}function ra(e,t){return yn(e,`image-${Date.now()}-${t+1}`)}class Ae extends Error{constructor(n,a){super(n);Pe(this,"retryBlocks");this.name="ImagePlacementError",this.retryBlocks=a}}function sa(e,t){return e instanceof Ae?e.retryBlocks:t}async function oa(e,t,n=ut,a=()=>!0){const r=l=>(...c)=>(le(a),l(...c));n={placeAttachment:r(n.placeAttachment),beginAttachmentUpload:r(n.beginAttachmentUpload),sendAttachmentUploadChunk:r(n.sendAttachmentUploadChunk),commitAttachmentUpload:r(n.commitAttachmentUpload),abortAttachmentUpload:r(n.abortAttachmentUpload),getAttachmentInfo:r(n.getAttachmentInfo),mintIdempotencyKey:r(n.mintIdempotencyKey)};const s=[],o=[],i=[];for(let l=0;l<t.length;l++){le(a);const c=t[l];if("attachmentId"in c&&c.attachmentId){const p={type:"image",attachmentId:c.attachmentId,...c.mimeType?{mimeType:c.mimeType}:{}};s.push(p),o.push(p);continue}const d=c,u=d.placementFileName??ra(d.mimeType,l),g=n.mintIdempotencyKey(d.placementIdempotencyKey);try{const p=await Me(e,u,{data:d.data,mimeType:d.mimeType,...g!==void 0?{idempotencyKey:g}:{}},n),m={type:"image",attachmentId:p.attachmentId,...p.mimeType??d.mimeType?{mimeType:p.mimeType??d.mimeType}:{}};s.push(m),o.push(m)}catch(p){const m=fn(p);i.push(m?`${u} (${m})`:u),o.push(g!==void 0?{...d,placementIdempotencyKey:g,placementFileName:u}:d)}}if(i.length>0)throw new Ae(h.chat_imagePlacement_failed_error({names:i.join(", ")}),o);return le(a),s}const rs=Object.freeze(Object.defineProperty({__proto__:null,ImagePlacementError:Ae,base64DecodedBytes:dt,imageRetryBlocks:sa,placeImageAttachment:Me,toImageReferenceBlocks:oa},Symbol.toStringTag,{value:"Module"}));function mt(){try{return kn()}catch{return null}}function ia(){return{backendId:A.state.connections.windowBackendId??null,generation:A.state.daemonHealth.connectionGeneration,transport:mt()}}class Ie extends Error{constructor(){super("dock-evidence-backend-changed")}}function N(e,t){return async(...n)=>{e();const a=await t(...n);return e(),a}}const K={current:e=>mt()===e.transport&&A.state.daemonHealth.connectionGeneration===e.generation&&(A.state.connections.windowBackendId??null)===e.backendId,capabilities:()=>_n(),placeImage:(e,t,n,a)=>Me(e,t,n,{placeAttachment:N(a,ot),beginAttachmentUpload:N(a,st),sendAttachmentUploadChunk:N(a,rt),commitAttachmentUpload:N(a,at),abortAttachmentUpload:N(a,nt),getAttachmentInfo:N(a,he),mintIdempotencyKey:se}),lookup:(e,t)=>he({workspaceId:e,idempotencyKey:t}),mintKey:se};function Y(e){return K.current(e)}function ca(e,t){const n=A.state.dockConversation;return{generation:n.generation,authority:n.authority,clearRevision:R(n.drafts,Gt(e,t))?.clearRevision??0,binding:ia()}}function ss(e,t,n){const a=ca(e,t);return a.generation===n.generation&&a.authority===n.authority&&a.clearRevision===n.clearRevision&&Y(n.binding)}function pt(e,t){return()=>{if(!e.current(t))throw new Ie}}const ft=Object.freeze({rawRetention:!1,chiefAttachments:!1});function os(e){return e!==ft}const de=new Map;function ht(e,t=K){const n=`${e.backendId}:${e.generation}`;let a=de.get(n);if(!a){const r=pt(t,e);a=(async()=>{r();const o=await t.capabilities();r();const i=o?.server?.capabilities;if(!i||typeof i!="object")throw new Error("unobserved");return{rawRetention:i.rawScreenshotRetention===1,chiefAttachments:i.chiefAttachments===1}})().catch(()=>(de.delete(n),ft)),de.set(n,a)}return a}class ee extends Error{constructor(t){super(`dock-raw-retention-contract:${t}`),this.reason=t}}function gt(e){const{rpcCode:t,code:n}=e??{};return t===-32602||n==="INVALID_PARAMS"}function la(e){const t=String(e?.message??"");return gt(e)&&(t.includes("rawScreenshotExpired:")||/expired at .*not renewable/i.test(t))}function da(e,t,n){const a=e.rawScreenshot;if(!a||a.compositeAttachmentId!==t)return null;const r=Date.parse(a.expiresAt);return Number.isFinite(r)?a.expired||r<=n?"expired":{attachmentId:e.attachmentId,expiresAt:a.expiresAt}:null}function Ke(e){return{ok:!0,path:e.path,fileName:e.fileName,size:e.size,attachmentId:e.attachmentId,...e.mimeType?{mimeType:e.mimeType}:{},uploadedAt:e.uploadedAt,replayed:!0,...e.rawScreenshot?{rawScreenshot:e.rawScreenshot}:{}}}class ua extends Error{constructor(t,n){super("dock-evidence-placement-failed"),this.imageId=t,this.failure=n}}const We=e=>e.split("/")[1]?.replace("jpeg","jpg")||"png";async function ma(e){const t=e.api??K,n=e.now??Date.now,a=pt(t,e.binding);a();const r=await ht(e.binding,t);a();const s=r.rawRetention&&(e.workspaceId!==be||r.chiefAttachments),o=[];for(const i of e.images){const l=e.records[i.image.id];let c=l&&l.signature===i.signature&&l.workspaceId===e.workspaceId&&l.backendId===e.binding.backendId?l:{imageId:i.image.id,signature:i.signature,workspaceId:e.workspaceId,backendId:e.binding.backendId,compositeKey:null,rawKey:null,composite:null,raw:null,rawSettled:!1};const d=u=>{c=u,e.onRecord(u)};try{if(!c.composite){const g=c.compositeKey,p=t.mintKey(g??void 0)??null;p!==c.compositeKey&&d({...c,compositeKey:p});let m;g&&p===g&&(a(),m=await t.lookup(e.workspaceId,p).then(Ke).catch(()=>{}),a()),m||(a(),m=await t.placeImage(e.workspaceId,`screenshot-${i.image.id.slice(0,8)}.${We(i.composite.mimeType)}`,{data:i.composite.base64,mimeType:i.composite.mimeType,...p?{idempotencyKey:p}:{}},a),a()),d({...c,composite:{attachmentId:m.attachmentId,mimeType:m.mimeType??i.composite.mimeType}})}const u=c.composite.attachmentId;if(s&&i.raw&&!c.raw&&!c.rawSettled){const g=c.rawKey,p=t.mintKey(g??void 0);if(p){p!==c.rawKey&&d({...c,rawKey:p});let m;g&&p===g&&(a(),m=await t.lookup(e.workspaceId,p).then(Ke).catch(()=>{}),a());try{m||(a(),m=await t.placeImage(e.workspaceId,`screenshot-${i.image.id.slice(0,8)}-original.${We(i.raw.mimeType)}`,{data:i.raw.base64,mimeType:i.raw.mimeType,idempotencyKey:p,rawScreenshot:{compositeAttachmentId:u}},a),a());const w=da(m,u,n());if(w==="expired")d({...c,rawSettled:!0});else if(w)d({...c,raw:w});else throw new ee("echo")}catch(w){if(la(w))d({...c,rawSettled:!0});else throw w instanceof ee?w:gt(w)?new ee("refused"):w}}else throw new ee("unkeyed")}}catch(u){throw u instanceof Ie?u:new ua(i.image.id,u)}o.push(c)}return o}async function is(e,t,n,a){const r=()=>{if(!K.current(a))throw new Ie};r();const s=await K.placeImage(e,t,{...n,idempotencyKey:K.mintKey()},r);return r(),s}const pa=new Set(["invalid-saved-edit","media-send-retired","transcript-unavailable","transcript-pending","invalid-edit","stale-source","legacy-baked-marks","timing-unavailable","audio-unavailable","media-source-unavailable","media-export-unavailable","media-animation-layer-limit","media-export-failed","legacy-original-unavailable","capture-render-unavailable","capture-blur-unavailable","stale-source-pixels","not-a-screenshot","not-admitted","unavailable","dock-evidence-missing-pixels","draft-restore-failed","image-budget-exceeded"]),fa=new Set(["unavailable","permission","failed","busy","cancelled","limit"]);class O extends Error{constructor(t,n){super(n),this.stage=t,this.code=n,this.name="DockSendError"}}function oe(e){const t=e instanceof Error?e.message:typeof e=="string"?e:"";if(t.length>64)return"unclassified";const[n,...a]=t.split(":");return!pa.has(n)||a.length>2?"unclassified":n!=="media-export-failed"?a.length?"unclassified":n:[n,...a.map(r=>fa.has(r)?r:"other")].join(":")}function cs(e,t){return e instanceof O?{stage:e.stage,code:oe(e.code)}:{stage:t,code:oe(e)}}function W(e){if(!e||e.source.kind!=="recording")return!1;const t=e.source,n=e.saved??re(t,t.capturedMarks??[],e.transcript);if(n.video!=="full"||n.voice!=="audio"||n.crop||n.blurRegions.length||n.blurStrokes?.length)return!1;const a=_e(n,t,e.transcript);return t.visuals==="clean"?!a.errors.length&&!a.muted&&n.cuts.length===0&&!n.marks.some(r=>r.included)&&a.marks.length===0&&a.transcript===null&&a.kept.length===1&&a.kept[0].startMs===0&&a.kept[0].endMs===t.durationMs&&a.clips.length===1&&a.clips[0].startMs===0&&a.clips[0].endMs===t.durationMs:!a.errors.length&&!a.muted&&a.clips.length===1&&a.clips[0].startMs===0&&a.clips[0].endMs>=t.durationMs}async function ha(e,t,n,a,r,s){const o={images:{},files:[],frames:[],framePromptBytes:[],metadata:[]};let i="validate";try{const l=()=>{if(!r()||!Y(n))throw new Error("media-send-retired")};for(const c of[...t.images,...t.clips]){if(i="validate",s?.stage(i),c.mediaError)throw new Error("invalid-saved-edit");if(!c.media||W(c.media))continue;l();const d=structuredClone(c.media),u=d.source;let g=d.saved??re(u,u.capturedMarks??[],d.transcript),p=crypto.randomUUID();try{if(u.kind==="recording"&&g.voice==="transcript"&&d.transcript?.status!=="ready"){if(i="transcribe",s?.stage(i),!a?.transcribeMedia)throw new Error("transcript-unavailable");const f=await a.transcribeMedia({jobId:p,media:d});if(l(),!f.ok)throw new Error("transcript-unavailable");d.transcript=f.value,d.saved||(g=re(u,u.capturedMarks??[],d.transcript))}i="plan",s?.stage(i);const m=_e(g,u,d.transcript);if(m.errors.length)throw new Error(m.errors[0]);const w={id:c.id,kind:u.kind,video:g.video,voice:g.voice,transcript:m.transcript,batches:u.batches,marks:m.marks.map(({n:f,mark:k,frameAtMs:_})=>({n:f,id:k.id,at_ms:_,kind:k.kind,label:k.label,note:k.note,context:k.context,geometry:k.geometry}))};if(u.kind==="screenshot"){i="screenshot-source",s?.stage(i);const f=u.path.split("/").map(encodeURIComponent).join("/"),k=tt(`intent://local/file/${f}`,e);if(!k||k.kind!=="image")throw new Error("media-source-unavailable");const _=await Xn(k.url);l();const I={base64:Ze(_.buffer.slice(_.byteOffset,_.byteOffset+_.byteLength)),mimeType:/\.jpe?g$/i.test(u.path)?"image/jpeg":/\.webp$/i.test(u.path)?"image/webp":"image/png"};i="screenshot-render",s?.stage(i),o.images[c.id]=await an(u,g,I),l()}else{if(!m.clips.length){w.video_attachment_id=null,w.frames=[],w.kept_ms=[],o.metadata.push(w);continue}const f={...d,saved:g};let k=await a?.takePreparedRecording?.(f);if(k&&(p=k.jobId),l(),!k){if(!a)throw new Error("media-export-unavailable");k=await lt(f,p,a,()=>r()&&Y(n),S=>{i=S,s?.stage(S),S==="export"&&s?.exportAttempt(p)})}p=k.jobId,i="placement",s?.stage(i);const _=[k.value.video,...k.value.frames],I=[];for(let S=0;S<_.length;S++){l();const v=_[S],B=`capture-${c.id.slice(0,12)}-${S}.${S===0?"mp4":v.mimeType==="image/jpeg"?"jpg":"png"}`,E=await wn(e,B,{sourcePath:v.sourcePath,mimeType:v.mimeType,idempotencyKey:se()},void 0,void 0,()=>r()&&Y(n));l(),S===0?o.files.push({type:"file",attachmentId:E.attachmentId,fileName:B,mimeType:E.mimeType??v.mimeType,size:E.size}):(o.frames.push({type:"image",attachmentId:E.attachmentId,mimeType:v.mimeType==="image/jpeg"?"image/jpeg":"image/png"}),o.framePromptBytes.push(zn(v))),I.push(E.attachmentId)}w.video_attachment_id=I[0],w.frames=k.value.frames.map((S,v)=>({mark_id:S.markId,attachment_id:I[v+1]})),w.kept_ms=m.clips}o.metadata.push(w)}finally{s?.stage("release"),await a?.releaseMediaJob?.(p).catch(()=>{})}}return o}catch(l){throw l instanceof O?l:new O(i,oe(l))}}const ue=1568,ga=.85;async function ya(e,t){const n=Math.round(e.length*3/4/1024),a=await wa(e,t),{width:r,height:s}=a,o=r>ue||s>ue;let i=r,l=s;if(o){const f=ue/Math.max(r,s);i=Math.round(r*f),l=Math.round(s*f)}const c=new OffscreenCanvas(i,l),d=c.getContext("2d");if(!d)throw new Error("Failed to get 2D canvas context for image resize");d.drawImage(a,0,0,i,l);let u=t;ba(d,i,l)||(u="image/jpeg");const g=await c.convertToBlob({type:u,quality:u==="image/jpeg"?ga:void 0}),p=g.type||u,m=await ka(g),w=Math.round(m.length*3/4/1024);return console.debug(`[image-resize] ${r}×${s} → ${i}×${l} | ${t} → ${p} | ${n} KB → ${w} KB`),{base64:m,mimeType:p}}async function wa(e,t){const n=atob(e),a=new Uint8Array(n.length);for(let s=0;s<n.length;s++)a[s]=n.charCodeAt(s);const r=new Blob([a],{type:t});return createImageBitmap(r)}function ba(e,t,n){const r=e.getImageData(0,0,t,n).data;for(let s=3;s<r.length;s+=4)if(r[s]<255)return!0;return!1}async function ka(e){const t=await e.arrayBuffer(),n=new Uint8Array(t);let a="";for(let r=0;r<n.length;r++)a+=String.fromCharCode(n[r]);return btoa(a)}const T={...Oe,badge:Oe.badgeRadius*2};function _a(e,t,n=1,a=0){const r=Math.max(1,e.displayScale)*n,s=[],o=i=>i*n;for(const{n:i,mark:l}of t){const c=l.geometry;if(c.kind==="rect")s.push({kind:"rect",x:o(c.x),y:o(c.y),w:o(c.w),h:o(c.h),width:T.stroke*r});else if(c.kind==="path")s.push({kind:"path",points:c.points.map(m=>({x:o(m.x),y:o(m.y)})),width:T.pen*r});else{const m={x:o(c.from.x),y:o(c.from.y)},w={x:o(c.to.x),y:o(c.to.y)};s.push({kind:"arrow",from:m,to:w,head:Ia(m,w,T.arrowHead*r),width:T.stroke*r})}if(!T.showNumbers)continue;const d=Math.max(a,T.badge/2*r),u=o(l.bounds.x+l.bounds.w),g=o(l.bounds.y),p=tn({x:o(l.bounds.x),y:g,w:u-o(l.bounds.x),h:o(l.bounds.h)},{x:0,y:0,w:o(e.width),h:o(e.height)},r,d);s.push({kind:"badge",...p,radius:d,label:String(i),font:d*T.badgeTextScale})}return s}function va(e,t){"letterSpacing"in e&&(e.letterSpacing="0px"),"wordSpacing"in e&&(e.wordSpacing="0px");const n=(a,r,s)=>{e.strokeStyle=T.halo,e.lineWidth=a+T.haloWidth*r,s(),e.strokeStyle=T.accent,e.lineWidth=a,s()};e.strokeStyle=T.accent,e.lineCap="round",e.lineJoin="round";for(const a of t)if(a.kind==="rect")n(a.width,a.width/T.stroke,()=>e.strokeRect(a.x,a.y,a.w,a.h));else if(a.kind==="path"||a.kind==="arrow"){e.lineWidth=a.width,e.beginPath();const r=a.kind==="path"?a.points:[a.from,a.to];a.kind==="arrow"&&r.forEach((o,i)=>i?e.lineTo(o.x,o.y):e.moveTo(o.x,o.y)),a.kind==="arrow"&&(e.moveTo(a.head.left.x,a.head.left.y),e.lineTo(a.to.x,a.to.y),e.lineTo(a.head.right.x,a.head.right.y));const s=a.kind==="path"?new Path2D(en(a.points)):null;n(a.width,a.width/(a.kind==="path"?T.pen:T.stroke),()=>s?e.stroke(s):e.stroke())}else e.fillStyle=T.paper,e.beginPath(),e.arc(a.x,a.y,a.radius,0,Math.PI*2),e.closePath(),e.fill(),e.strokeStyle=T.accent,e.lineWidth=T.badgeOutline*a.radius/T.badgeRadius,e.stroke(),e.fillStyle=T.ink,e.font=`600 ${a.font}px ${T.badgeFontFamily}`,e.textAlign="center",e.textBaseline="middle",e.fillText(a.label,a.x,a.y)}async function Sa(e,t){const n=Uint8Array.from(atob(e),a=>a.charCodeAt(0));return createImageBitmap(new Blob([n],{type:t}))}async function Ma(e){const t=await e.convertToBlob({type:"image/png"});return Ze(await t.arrayBuffer())}async function yt(e,t,n,a,r=0){await rn();const s=await Sa(e.base64,e.mimeType);try{const o=Math.min(1,a/Math.max(t.width,t.height)),i=new OffscreenCanvas(Math.max(1,Math.round(t.width*o)),Math.max(1,Math.round(t.height*o))),l=i.getContext("2d");if(!l)throw new Error("dock-evidence-canvas-unavailable");return l.drawImage(s,0,0,i.width,i.height),va(l,_a(t,n,o,r)),i}finally{s.close()}}async function Aa(e,t,n){const a=await yt(e,t,n,Math.max(t.width,t.height));return ya(await Ma(a),"image/png")}async function ls(e,t,n,a=384){const r=await yt(e,t,n,a,a/32);return URL.createObjectURL(await r.convertToBlob({type:"image/png"}))}function Ia(e,t,n=T.arrowHead){const a=Math.atan2(t.y-e.y,t.x-e.x),r=T.arrowSpread;return{left:{x:t.x-n*Math.cos(a-r),y:t.y-n*Math.sin(a-r)},right:{x:t.x-n*Math.cos(a+r),y:t.y-n*Math.sin(a+r)}}}function ds(e,t){const n=Yt(t??void 0),a=new Set(t?.clips.filter(r=>!!r.media&&!W(r.media)).map(r=>r.contextItemId));return e.filter(r=>!n.has(r.id)&&!a.has(r.id))}async function us({workspaceId:e,agentId:t,evidence:n,clickedItems:a,sendItems:r,clickedPayload:s,binding:o,service:i,current:l,onRecord:c,timing:d}){const u=()=>{if(!l()||!Y(o))throw new O("validate","media-send-retired")};if(u(),n?.images.some(b=>b.mediaError)||n?.clips.some(b=>b.mediaError))throw new O("validate","invalid-saved-edit");const g=b=>!!b.media&&!W(b.media),p=n?{workspaceId:e,agentId:t,appUrl:`intent://local/workspace/${encodeURIComponent(e)}`,clipAttachmentIds:Object.fromEntries(n.clips.map(b=>[b.id,a.find(M=>M.id===b.contextItemId)?.attachmentId??null]))}:null;for(const b of n?.clips??[]){if(!b.media||!W(b.media))continue;const M=a.find(Q=>Q.id===b.contextItemId);if(!M||M.attachmentId!==b.media.source.attachmentId||M.path!==b.media.source.path||M.placementStatus!==void 0&&M.placementStatus!=="placed")throw new O("validate","legacy-original-unavailable")}const m=n?await ha(e,n,o,i,l,d):{images:{},files:[],frames:[],framePromptBytes:[],metadata:[]},w=new Set(n?.clips.filter(b=>g(b)||!!b.media&&W(b.media)).map(b=>b.id)),f=new Set(n?.clips.filter(b=>w.has(b.id)).flatMap(b=>(b.captureHistory??[]).map(M=>M.image.id))),k=(n?.images??[]).filter(b=>b.source!=="annotate"||!!b.media||!f.has(b.id)||n.marks.some(M=>M.imageId===b.id&&!(M.clipId&&w.has(M.clipId))));d?.stage("burn");let _=[];try{_=n?await Ta({...n,images:k},a,m.images):[]}catch(b){throw new O("burn",oe(b))}if(m.framePromptBytes.reduce((b,M)=>b+(M??0),0)>qn)throw new O("validate","image-budget-exceeded");const S=new Set(n?.images.filter(b=>b.media).map(b=>b.id)),v=n?{...n,images:k.map(b=>m.images[b.id]?{...b,width:m.images[b.id].width,height:m.images[b.id].height}:b),clips:n.clips.filter(b=>!g(b)),marks:n.marks.filter(b=>!S.has(b.imageId)&&!n.clips.some(M=>g(M)&&M.id===b.clipId))}:null;u();const B=m.metadata.some(b=>typeof b.transcript=="string"&&b.transcript.trim());if(!s.text.trim()&&!r.length&&!s.workspaceContextStr?.trim()&&!_.length&&!m.files.length&&!m.frames.length&&!s.imageBlocks?.length&&!s.fileBlocks?.length&&!B)return null;let E=_,P=null;d?.stage("placement");const xe=n?await ht(o):null;if(u(),n&&(e!==be||xe?.chiefAttachments)){const b=await ma({workspaceId:e,binding:o,images:k.map((M,Q)=>{const Z=a.find(Dt=>Dt.id===M.contextItemId);return{image:M,signature:Jt(n,M.id),composite:{base64:_[Q].data,mimeType:_[Q].mimeType},raw:!M.media&&Z?.imageData&&Z.imageMimeType?{base64:Z.imageData,mimeType:Z.imageMimeType}:null}}),records:n?.placements??{},onRecord:c});u(),E=b.map(M=>({type:"image",attachmentId:M.composite.attachmentId,mimeType:M.composite.mimeType})),P=Object.fromEntries(b.map(M=>[M.imageId,{attachmentId:M.composite.attachmentId,raw:M.raw}]))}const y=new Map(n?Qe(n).map(({n:b,mark:M})=>[M.id,b]):[]),D=p&&P?{...p,imageAttachments:P,markNumbers:y}:p&&{...p,markNumbers:y},$=n&&D?{...s,imageBlocks:[...E,...m.frames,...s.imageBlocks??[]],fileBlocks:[...s.fileBlocks??[],...m.files],workspaceContextStr:[Qt(v,D),m.metadata.length?`[Edited capture outputs]
3
3
  ${JSON.stringify(m.metadata)}`:"",s.workspaceContextStr].filter(Boolean).join(`
4
4
 
5
5
  `),messageMetadata:{...s.messageMetadata,...Xt(v,D),edited_captures:m.metadata}}:s;return u(),$}async function Ta(e,t,n={}){const a=Qe(e);return Promise.all(e.images.map(async r=>{if(n[r.id])return{type:"image",...n[r.id]};const s=t.find(i=>i.id===r.contextItemId);if(!s?.imageData||!s.imageMimeType)throw new Error("dock-evidence-missing-pixels");const o=await Aa({base64:s.imageData,mimeType:s.imageMimeType},r,a.filter(({mark:i})=>i.imageId===r.id));return{type:"image",data:o.base64,mimeType:o.mimeType}}))}function Ca(){return et()}function ms(e){const{clip:t}=e;if(t.status!=="ready"||!t.path)return null;const n=e.marks.filter(s=>s.clipId===t.id&&typeof s.clipMs=="number").sort((s,o)=>s.clipMs-o.clipMs).map(s=>({id:s.id,tool:s.tool,atMs:s.clipMs,...s.element?.name?{label:s.element.name.slice(0,200)}:{}})),a=Zt(e.evidence??void 0,t.id),r=a?t.media:void 0;return{kind:"recording",workspaceId:e.workspaceId,agentId:e.agentId,attachmentId:a?.attachmentId??t.id,sourceRevision:a?`${a.id}:${a.revision}`:t.path,attachmentPath:t.path,title:"",durationMs:t.durationMs,marks:n,provenance:a?{...a.audio==="unknown"?{}:{hasMicAudio:a.audio==="available"},visuals:a.visuals}:{hasMicAudio:t.hasMicAudio,visuals:n.length>0?"baked-marks":"clean"},...a&&r?{source:a,saved:r.saved??null,transcript:r.transcript??null}:{}}}async function ps(e){if(!Ca())return{ok:!1,error:"unavailable"};try{return await on().invoke(sn.OPEN,e)??{ok:!1,error:"unavailable"}}catch{return{ok:!1,error:"transport"}}}function fs(e){let t=null,n=null;const a=i=>e.releaseMediaJob?.(i).catch(()=>{});function r(){const i=t;t=null,!(!i||i.taken||i.stopped)&&(i.stopped=!0,clearTimeout(i.timer),a(i.id))}function s(i,l,c){if(t?.key===i||n===i||(r(),n=null,!e.adoptMediaJob||!e.exportMedia||!c()||W(l)))return;const d=structuredClone(l),u=d.saved??re(d.source,d.source.capturedMarks??[],d.transcript),g=_e(u,d.source,d.transcript);if(d.source.kind!=="recording"||d.source.visuals!=="clean"||g.errors.length||!g.clips.length||u.voice==="transcript"&&d.transcript?.status!=="ready")return;const p={...d,saved:u},m=crypto.randomUUID(),w={key:i,mediaKey:JSON.stringify(p),id:m,current:c,taken:!1,stopped:!1,settled:!1,failed:!1,timer:setTimeout(()=>{t===w&&(n=i,r())},3e4),result:Promise.resolve({error:new Error("not-started")})};t=w,w.result=lt(p,m,e,()=>!w.stopped&&w.current()).then(async f=>w.stopped||!w.current()?(await a(m),{error:new Error("media-send-retired")}):{value:f},async f=>(w.failed=!0,t===w&&(n=i),await a(m),{error:f})).finally(()=>{w.settled=!0})}async function o(i,l,c){const d=t;if(!d||d.key!==i||d.mediaKey!==JSON.stringify(l)||d.stopped||d.taken||!c())return null;if(d.failed&&d.settled)return r(),null;d.taken=!0,d.current=c,clearTimeout(d.timer),t=null;const u=await d.result;if("error"in u)throw u.error;try{if(!c())throw new Error("media-send-retired");const g=await e.adoptMediaJob?.(d.id);if(!c())throw new Error("media-send-retired");return!g?.ok||!g.value?(await a(d.id),null):u.value}catch(g){throw await a(d.id),g}}return{warm:s,take:o,cancel:r}}function hs(e={}){const t=a=>cn(a,typeof e=="function"?e():e),n=a=>vn(t(a));return{actionHints:{get capture(){return{label:h.dock_composer_screenshotAction_label(),shortcut:t("dock.capture")}},get record(){return{label:h.ui_shortcuts_dockRecord_label(),shortcut:t("dock.record")}},get dictate(){return{label:h.dock_shortcut_dictate_label()}}},get capture(){return h.dock_composer_capture_tooltip({shortcut:n("dock.capture")})},captureMode:{get window(){return h.dock_composer_captureWindow_tooltip({shortcut:n("dock.capture")})},get region(){return h.dock_composer_captureRegion_tooltip({shortcut:n("dock.capture")})}},captureModes:{fullscreen:h.dock_composer_captureFullscreen_label(),window:h.dock_composer_captureWindow_label(),region:h.dock_composer_captureRegion_label()},captureOptions:h.dock_composer_captureModes_ariaLabel(),captureLimit:h.dock_composer_captureLimit_tooltip(),clipLimit:h.dock_composer_clipLimit_tooltip({limit:H(ae.clips)}),get record(){return h.dock_composer_record_tooltip({shortcut:n("dock.record")})},stopRecording:h.dock_composer_stopRecording_tooltip(),annotationTools:h.annotation_toolbar_ariaLabel(),annotateCurrent:a=>h.dock_composer_annotate_ariaLabel({tool:a}),tools:{pick:h.dock_composer_pick_label(),box:h.dock_composer_box_label(),pen:h.dock_composer_pen_label(),arrow:h.annotation_arrow_label()},get dictate(){return h.dock_shortcut_dictate_label()},stopDictating:h.dock_composer_stopDictating_tooltip(),annotating:h.dock_composer_annotating_status(),recording:h.dock_composer_recording_status(),markUp:h.dock_composer_markUp_label(),remove:h.chat_contextChip_remove_label(),play:h.dock_composer_play_label(),edit:h.dock_composer_edit_label(),done:h.dock_composer_done_label(),attachments:h.context_attachments_title_label(),retry:h.chat_shared_retry_label(),attachmentPending:h.dock_composer_attachmentPending_status(),attachmentFailed:h.dock_composer_attachmentFailed_error(),image:a=>h.dock_composer_image_ariaLabel({n:H(a)}),clip:a=>h.dock_composer_clip_ariaLabel({duration:a}),recordingReference:(a,r)=>r?h.dock_composer_recordingEnd_chip({n:H(a)}):h.dock_composer_recordingStart_chip({n:H(a)}),speechError:a=>a.includes("permission")?h.dock_composer_speechPermission_error():["unsupported-platform","helper-missing","recognizer-unavailable","locale-unsupported","assets-unavailable","unavailable"].includes(a)?h.dock_composer_speechUnavailable_error():h.dock_composer_speechFailed_error()}}function gs(e,t){return{enabled:e,limit:ae.files,excludedIds:t,unavailableMessage:h.dock_composer_filesUnavailable_error(),limitMessage:h.dock_composer_fileLimit_error({limit:H(ae.files)})}}function Ea(e){try{return new URL(e.pageUrl).hostname||e.pageUrl}catch{return e.pageUrl}}function ys(e,t){return e.targetAgentId===t}function ws(e){const t=e.element,n=e.viewport,a=Ea(e),r=t?`<${t.tagName.toLowerCase()}> · ${a}`:e.title||a,s=["<browser-element-capture>",`Page URL: ${e.pageUrl}`,`Page title: ${e.title}`,...t?[`DOM path: ${t.domPath}`,`CSS selector: ${t.selector}`,`Text snippet: ${t.textSnippet}`,...t.sourceRef?[`Source ref: ${t.sourceRef}`]:[],...n?[`Viewport: ${n.width}×${n.height}`]:[],`Element bounds: ${t.rect.width}×${t.rect.height} at (${t.rect.x}, ${t.rect.y})`]:[],"</browser-element-capture>"].join(`
@@ -8,5 +8,5 @@ ${JSON.stringify(m.metadata)}`:"",s.workspaceContextStr].filter(Boolean).join(`
8
8
  \`\`\`
9
9
  ${o}
10
10
  \`\`\`]`)}return Da(a.join(`
11
- `),e)}function bs(e,t,n){if(e==="suggested-prompt")return{fields:{},hasAttachments:!1,cleanup:{clearInput:!1,followBottom:!0,historyText:null}};const a=n(),{imageBlocks:r,fileBlocks:s}=Ra(a.contextItems);return{fields:{contextItems:a.contextItems,workspaceContextStr:xa(a.contextItems,a.checkedPanels,a.checkedSelections),noteIds:a.noteIds,...r.length>0?{imageBlocks:r}:{},...s.length>0?{fileBlocks:s}:{},...a.pickedMentions?{messageMetadata:a.pickedMentions}:{}},hasAttachments:r.length>0||s.length>0,cleanup:{clearInput:!0,followBottom:!0,historyText:t}}}function ks(e){switch(e.kind){case"tooLong":return h.chat_goal_tooLong_error({max:H(Tn)});case"attachments":return h.chat_goal_attachments_error();case"retired":return h.chat_goal_retired_error();case"workspaceRetired":return h.chat_goal_workspaceRetired_error();case"invalid":case"failed":return h.chat_goal_failed_error()}}const Pa="chat-read:",q=new Map,ye=new Set;function _s(e,t){let n=q.get(e);n||(n=new Set,q.set(e,n)),n.add(t)}function vs(e,t){const n=q.get(e);if(!(!n||!n.delete(t))&&n.size===0){q.delete(e);for(const a of[...ye])a(e)}}function Ss(e){return ye.add(e),()=>ye.delete(e)}function Ms(e){return q.has(e)}function As(e){const t=q.get(e);if(!t)return!1;for(const n of t)if(!n.startsWith(Pa))return!0;return!1}function Ba(e,t,n){const a=e.state.pendingSubmissions.byAgentId[t.agentId];if(!a||!Ge(a.scope,t))return null;const r={...structuredClone(n),id:crypto.randomUUID(),createdAt:Date.now()};e.dispatch(Bt(t,r));const s=e.state.pendingSubmissions.byAgentId[t.agentId];return s&&R(s.submissions,r.id)?r:null}function Oa(e,t,n,a,r){const s=Be.select(e.state,n),o=pe.select(e.state)?.principal.id,i=Ue(e.state);if(!s||!o||!i)return null;const l=Cn(t,n),c={agentId:t,workspaceId:n,principalId:o,participation:s,authority:i,owner:l.key,lifetime:e.state.pendingSubmissions.byAgentId[t]?.scope.lifetime??crypto.randomUUID()},d=()=>l.isCurrent(e.state.agentSessions?.byAgentId[t]?.workspaceId)&&Be.select(e.state,n)===s&&pe.select(e.state)?.principal.id===o&&Ue(e.state)===i;if(!d())return null;e.dispatch(Pt(c,a,Wt.select(e.state,n)));const u=Ba(e,c,r);return u?{scope:c,submission:u,isCurrent:()=>{const g=e.state.pendingSubmissions.byAgentId[t];return d()&&!!g&&Ge(g.scope,c)&&(!!R(g.operations,u.id)||!!R(g.submissions,u.id))}}:null}function we(e,t,n){if(!n.text.trim()&&!n.imageBlocks?.length&&!n.fileBlocks?.length)return null;const a=n.userAppMessageId??En();return Oa(e,t,n.wsId,pe.select(e.state)?.capabilities.submissionCorrelation,{content:n.text.trim(),appMessageId:a,destination:!n.forceSubmit&&qt.select(e.state,t)?"queue":"conversation",contextItems:n.contextItems,imageBlocks:n.imageBlocks,fileBlocks:n.fileBlocks,messageMetadata:n.messageMetadata})}function La(e,t,n){const a=we(e,t,n);return a?(e.dispatch(Ye(t,{...n,userAppMessageId:a.submission.appMessageId,submission:{scope:a.scope,id:a.submission.id}})),!0):!1}async function Ua(e,t,n,a){const r=n.submission;if(!r)return"legacy";const s=r.reference,o=()=>s.scope.agentId===e&&s.scope.workspaceId===t&&Xe.select(A.state,e)===n?bn.select(A.state,s.scope):void 0,i=o();if(!i)return null;if(!i.supported)return"legacy";const l={wsId:t,text:n.text,imageBlocks:n.options?.imageBlocks,fileBlocks:n.options?.fileBlocks,noteIds:n.options?.noteIds,messageMetadata:n.options?.messageMetadata,model:a??n.options?.model};if(r.outcome==="rejected"){const p=R(i.tombstones,s.id);return R(i.submissions,s.id)||p&&p.reason!=="rejected"?null:we(A,e,l)}if(r.outcome==="accepted")return we(A,e,l);await Promise.all([Dn(e,t).catch(()=>{}),Rn(e,t).catch(()=>{})]);const c=o();if(!c||R(c.submissions,s.id)?.status!=="uncertain")return null;const{notify:d}=await fe(async()=>{const{notify:p}=await import("./uvhZkGDU.js").then(m=>m.i);return{notify:p}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]),import.meta.url);if(o()!==c)return null;let u=!1;const g=()=>{u=!0};return d.warning(h.agent_chatSend_uncertainRetry_description(),{key:`submission-retry:${t}:${e}:${s.id}`,duration:Number.POSITIVE_INFINITY,action:{label:h.agent_chatSend_resend_label(),onClick:()=>{if(u)return;u=!0;const p=o();!p||p.generation!==c.generation||p.submissions!==c.submissions||p.observationVersion!==c.observationVersion||R(p.submissions,s.id)?.status!=="uncertain"||La(A,e,l)}},cancel:{label:h.chat_richInput_cancel_label(),onClick:g},onDismiss:g}),null}async function Is(e,t,n){const a=Xe.select(A.state,e),r=a?.submission?await Ua(e,t,a,n):"legacy";if(r){if(r==="legacy"){await A.dispatch(n===void 0?Ot(e,t):Lt(e,t,n));return}!r.isCurrent()||!a||A.dispatch(Ye(e,{wsId:t,text:a.text,imageBlocks:a.options?.imageBlocks,fileBlocks:a.options?.fileBlocks,noteIds:a.options?.noteIds,messageMetadata:a.options?.messageMetadata,model:n??a.options?.model,userAppMessageId:r.submission.appMessageId,submission:{scope:r.scope,id:r.submission.id}}))}}const Ts=A.createSelector((e,t)=>{const n=R(e.chatDrafts.owners,t);return n?{restore:n.restore,saves:Je(n.saves),shared:n.restore?e.chatDrafts.shared[JSON.stringify([n.restore.workspaceId,n.restore.agentId])]:void 0}:void 0});function $a(e,t){return t.workspaceId===e&&!t.retiredAt&&!t.pendingDeleteAt&&t.status!==ke.Deleted&&!t.notificationsMuted&&$t(t)==="topLevel"}function Na(e){const t=e.metadata?.pendingQuestionsMessageId;return typeof t=="string"&&t.length>0&&!Bn(e.metadata,t)?t:null}function Ha(e){return e.status===ke.Error&&!jt(Vt(e))}function Cs(e,t){return t.filter(n=>$a(e,n)).flatMap(n=>{const a=Ut(n),r=Na(n),s=n.status===ke.Error;if(!a&&!r&&!s)return[];const o=a?.timestamp??(s?n.stopReasonTimestamp:void 0);return[{agentId:n.id,agentName:n.name,kind:a?.kind??(s?"failed":"question"),reason:a?.reason,timestamp:o&&Number.isFinite(Date.parse(o))?o:void 0,questionMessageId:r,canRetry:Ha(n)}]})}function Es(e){return e.displayStatus==="failed"?"failed":e.displayStatus==="blocked"?"blocked":e.attention==="review_required"?"review":e.displayStatus==="needs_attention"?"question":e.activity==="agent_running"||e.displayStatus==="in_progress"?"running":e.scriptsRunning===!0?"scripts_running":e.backgroundTasksRunning===!0?"background_tasks_running":e.displayStatus==="pr_ready"?"pr_ready":e.displayStatus==="pr_merged"?"merged":e.displayStatus==="complete"?"complete":e.attention==="unread"?"unread":e.displayStatus==="pr_open"||e.displayStatus==="pr_queued"?e.displayStatus:"idle"}function Ds(e){const t=e.kind==="prs"?e.organization?.trim().toLowerCase():void 0;return{key:JSON.stringify([e.kind,e.workspaceId,t||null,[...new Set((t?[]:e.repositories).map(n=>JSON.stringify([n.key,n.owner,n.name])))].sort()]),hasGitHubRepositories:!!t||e.repositories.some(n=>!!n.owner),hasLocalRepositories:!t&&e.repositories.some(n=>!n.owner)}}function Te(e){const t=Sn(e);if(t?.kind!=="pr"||!Number.isSafeInteger(t.number)||t.number<=0)return null;const n=t.owner.toLowerCase(),a=t.repo.toLowerCase();return{owner:n,repo:a,number:t.number,id:`${n}/${a}#${t.number}`,url:`https://github.com/${n}/${a}/pull/${t.number}`}}function Rs(e,t,n,a){const r=e.filter(s=>a?a.includes(s.id):n?s.repositoryOwner?.toLowerCase()===n.toLowerCase():t.some(o=>o.owner?.toLowerCase()===s.repositoryOwner?.toLowerCase()&&o.name.toLowerCase()===s.repositoryName?.toLowerCase()));return[...new Map(r.flatMap(s=>[...(s.pullRequests??[]).map(o=>o.url),s.activePullRequest?.url,s.prUrl]).flatMap(s=>{const o=s?Te(s):null;return o?[[o.id,{owner:o.owner,repo:o.repo,number:o.number}]]:[]})).values()].sort((s,o)=>`${s.owner}/${s.repo}#${s.number}`.localeCompare(`${o.owner}/${o.repo}#${o.number}`))}function xs(e,t){const[n]=t;return t.length!==1||e.owner?.toLowerCase()!==n?.owner?.toLowerCase()||e.repo?.toLowerCase()!==n?.name.toLowerCase()}const Ps=A.createSelector(e=>e.homeIntegrations),Bs=A.createSelector(e=>{const t=e.homeIntegrations;return!t.linkedItems||!Object.keys(t.linkedItems).length?t:{...t,items:[...new Map([...Object.values(t.linkedItems),...t.items].map(n=>[n.id,n])).values()].sort((n,a)=>(a.updatedAt??"").localeCompare(n.updatedAt??""))}}),wt=A.createSelector(e=>Je(e.workspace.workspaces).flatMap(t=>[...(t.pullRequests??[]).map(n=>n.url),t.activePullRequest?.url,t.prUrl].filter(n=>!!n).map(n=>({url:Te(n)?.url??n.replace(/\/$/,"").toLowerCase(),workspaceId:t.id,name:t.title||t.id})))),Os=A.createSelector(e=>{const t=e.homeIntegrations.detail?.url,n=t?Te(t)?.url??t.replace(/\/$/,"").toLowerCase():void 0;return wt.select(e).find(a=>a.url===n)??null}),Ls=A.createSelector(e=>wt.select(e).map(t=>t.url)),Fa=["setup-retry-not-remote","setup-retry-not-failed","setup-retry-shared-checkout","setup-retry-no-script","agent-busy","agent-not-running","machine-update-required","machine-unreachable"];function Us(e,t){return e&&t?.state==="failed"}function Ka(e){const t=e??{},n=typeof t.message=="string"?t.message:"";if(t.rpcCode===-32601||t.code==="METHOD_NOT_FOUND")return{ok:!1,code:"unsupported",message:n};const a=typeof t.data?.code=="string"?t.data.code:t.code;return{ok:!1,code:Fa.find(s=>s===a)??"unknown",message:n}}async function $s(e,t=it){try{const n=await t("agent.retrySetup",{workspaceId:e.workspaceId,agentId:e.agentId}),a=ln.safeParse(n?.setup);return{ok:!0,setup:a.success?a.data:null}}catch(n){return Ka(n)}}function Wa(e){return e.code==="unsupported"?h.remoteAgent_setupRetry_unsupported_error():e.message.trim()||h.remoteAgent_setupRetry_generic_error()}function Ns(e,t){On.error(h.remoteAgent_setupRetry_failed_title({machine:e}),{description:Wa(t)})}let te=null;function Hs(e){return te=e,()=>{te===e&&(te=null)}}function Fs(){return te}function Ks(e){return[...e.groups.length>0?e.groups.filter(n=>n.expanded).flatMap(n=>n.items):e.workspaces,...e.asideExpanded?e.aside:[]].map(n=>n.id)}function Ws(e,t,n){if(e.length===0)return null;const a=t===null?-1:e.indexOf(t);return a===-1?e[0]:e[a+(n==="clockwise"?1:-1)]??null}let F=[];function qs(e,t={}){const n={source:e,fallback:t.fallback===!0};return F=[...F,n],()=>{F=F.filter(a=>a!==n)}}function js(){const e=F.findLast(n=>!n.fallback);return e?e.source:F.findLast(n=>n.fallback&&(n.source.available?.()??!0))?.source??null}function Vs(e){if(!e?.isConnected||e.closest("[inert]"))return!1;const t=e.ownerDocument.querySelectorAll('[aria-modal="true"]');return Array.from(t).every(n=>n.contains(e))}const zs=ct("conversationGoal/commandSend","conversationGoal/commandSendRequested"),Gs=ct("conversationGoal/set","conversationGoal/setRequested");function Ys(e){return In(e)}function qa(e){return An(e)}function ja(e,t){return!e||!t?!1:e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function me(e){if(e.length===0)return[];const t=[];let n=null;for(const a of e){const r=a.timestamp?typeof a.timestamp=="string"?new Date(a.timestamp):a.timestamp:new Date;(!n||!ja(n.date,r))&&(n={date:r,label:qa(r),messages:[]},t.push(n)),n.messages.push(a)}return t}function Js(e){const t=new Map;return e.map(({date:n})=>{const a=`${n.getFullYear()}-${n.getMonth()+1}-${n.getDate()}`,r=t.get(a)??0;return t.set(a,r+1),r===0?a:`${a}#${r}`})}function Xs(e,t){const n=new Map;let a=t?null:void 0;for(const r of e.groups)for(const s of r.messages)a!==void 0&&n.set(s.id,a),s.role==="user"&&!Un(s)&&(a=s);return n}function Va(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function qe(e,t){const n=new Map;return e.map(a=>{const r=`${t}-${Va(a.date)}`,s=(n.get(r)??0)+1;return n.set(r,s),{...a,groupKey:s===1?r:`${r}-${s}`}})}function za(e,t){if(e.length===0||t.length===0)return e;const n=new Set(t.map(s=>s.id)),a=new Set(t.map(s=>s.appMessageId).filter(s=>typeof s=="string"&&s.length>0)),r=e.filter(s=>!n.has(s.id)&&!(typeof s.appMessageId=="string"&&s.appMessageId.length>0&&a.has(s.appMessageId)));return r.length===e.length?e:r}function Qs(e,t,n){return e=za(e,t),e.length===0?{groups:me(t),detached:!1,hiddenTail:[]}:n?{groups:qe(me(e),"h"),detached:!0,hiddenTail:t}:{groups:qe(me([...e,...t]),"d"),detached:!1,hiddenTail:[]}}function Zs(e){const{scrollTop:t,threshold:n,fetching:a,exhausted:r,historyCount:s,tailCount:o,tailTruncated:i,totalMessages:l,spacerAbove:c=0}=e;return t>n+c||a||r?!1:s>0||i||l>o+s}const eo=300;function to(e){const{fetching:t,chainEvaluationPending:n,visible:a,hideArmed:r}=e;return t||n?a&&!r?"none":"show":a&&!r?"arm-hide":"none"}const je=24,Ga=320;function Ce(e){return Number.isFinite(e)?Math.min(Ga,Math.max(je,e)):je}const Ya=.2,Ja=.12;function Xa(e,t,n=Ya){const a=Ce(t);return e===null||!Number.isFinite(e)?a:e+n*(a-e)}function no(e,t){const n=Ce(t??Number.NaN);return{above:Math.round(Math.max(0,e.above)*n),below:Math.round(Math.max(0,e.below)*n)}}function ao(e){const{totalMessages:t,residentCount:n,exhausted:a,residentContentHeight:r,currentSpacerHeight:s,viewportHeight:o}=e;let i=e.rowHeightEma;n>0&&r>0&&(i=Xa(i,r/n));const l=e.unloadedRows??t-n,d=a||t<=0||n<=0||l<=0||i===null?0:Math.round(l*i),u=Math.abs(d-s);return u===0?{spacerHeight:s,rowHeightEma:i,applied:!1,scrollTopDelta:0}:d===0||s===0||u>s*Ja||o>0&&u>o?{spacerHeight:d,rowHeightEma:i,applied:!0,scrollTopDelta:d-s}:{spacerHeight:s,rowHeightEma:i,applied:!1,scrollTopDelta:0}}const Qa=Ln,Za=2;function ro(e){const{scrollTop:t,spacerAboveHeight:n,rowHeightEstimate:a,pageSize:r=Qa,nearPages:s=Za}=e;if(n<=0||t>=n)return"serial";const o=Ce(a??Number.NaN);return(n-Math.max(0,t))/o>s*r?"seek":"serial"}const bt=200,er=1;function so(e,t,n=bt){const a=t.timestamp-n;return[...e.filter(r=>r.timestamp>=a),t]}function oo(e){const{samples:t,viewportHeight:n,windowMs:a=bt,viewportFactor:r=er}=e;if(n<=0||t.length<2)return"gentle";const s=t[t.length-1].timestamp-a,o=t.filter(l=>l.timestamp>=s);if(o.length<2)return"gentle";let i=0;for(let l=1;l<o.length;l+=1)i+=Math.abs(o[l].scrollTop-o[l-1].scrollTop);return i>n*r?"rapid":"gentle"}function io(e){const{scrollTop:t,spacerAboveHeight:n,unloadedRowsAbove:a}=e;if(a<=0||n<=0)return 0;const r=Math.min(1,Math.max(0,t/n));return Math.min(a-1,Math.max(0,Math.floor(r*a)))}function co(e){const{totalMessages:t,residentCount:n,exhausted:a,startOrdinalEstimate:r,detachedFromTail:s}=e,o=Math.max(0,t-n);if(!s)return{above:a?0:o,below:0};const i=Math.max(0,e.hiddenTailCount??0);if(a)return{above:0,below:o+i};if(r!==null){const c=Math.min(o,Math.max(0,Math.round(r)));return{above:c,below:o-c+i}}const l=Math.min(o,Math.max(0,Math.round(e.holeRowsEstimate??0)));return{above:o-l,below:l+i}}function lo(e){const{exhausted:t,historyCount:n,tailCount:a,tailTruncated:r,totalMessages:s}=e;return t?!0:n>0?!1:!r&&s<=a}const tr="intent.drafts.sync",nr="intent.drafts.changed",ar=L({id:C(),type:C(),label:C(),description:C().optional(),content:C().optional(),path:C().optional(),imageData:C().optional(),imageMimeType:C().optional(),attachmentId:C().optional(),attachmentMimeType:C().optional(),attachmentSize:ce().optional(),sourcePath:C().optional(),placementStatus:z("failed").optional(),screen:$n().optional()}),kt=L({text:C(),attachments:Nn(ar)}),G={provenance:C().min(1),workspaceId:C().min(1),agentId:C().min(1)},ne={lifetime:C(),revision:ce().int().nonnegative()};Hn("kind",[L({...G,kind:z("read")}),L({...G,...ne,kind:z("edit"),origin:C().min(1),sequence:ce().int().positive(),snapshot:kt}),L({...G,...ne,kind:z("flush")}),L({...G,...ne,kind:z("clear"),origin:C().min(1)})]);const _t=L({...G,...ne,origin:C(),sequence:ce().int().nonnegative(),snapshot:kt}),rr=L({accepted:Fn(),draft:_t});function sr(e,t,n=t){const a=new Map,r=new Set,s=crypto.randomUUID();let o=0,i=!1;const l=()=>{const f=t();if(i||!f)throw new Error("draft-authority-unavailable");return f},c=()=>{const f=n();if(!f||i)throw new Error("draft-authority-unavailable");return()=>{if(i||n()!==f)throw new Error("draft-authority-changed")}},d=(f,k,_)=>{const I=JSON.stringify([f,k,_]);let S=a.get(I);return S||(S={dirty:0},a.set(I,S)),S},u=(f,k)=>{if(i||f.provenance!==t())return;const _=d(f.provenance,f.workspaceId,f.agentId);if(!(_.value?.lifetime===f.lifetime&&_.value.revision>f.revision)&&(_.value=f,k&&_.dirty===0))for(const I of r)I(f)},g=e.subscribe(f=>{const k=_t.safeParse(f);k.success&&u(k.data,!0)}),p=async(f,k)=>{k();const _=rr.parse(await e.request(f));if(k(),f.provenance!==l()||_.draft.provenance!==f.provenance)throw new Error("draft-authority-changed");if(!_.accepted)throw u(_.draft,!1),new Error("draft-changed-in-another-editor");return _.draft},m=async(f,k)=>{const _=l(),I=c(),S=d(_,f,k);S.tail&&await S.tail;const v=await p({kind:"read",provenance:_,workspaceId:f,agentId:k},I);return u(v,!1),v},w=(f,k,_)=>{const I=l(),S=c(),v=d(I,f,k),B=v.tail??(v.value?Promise.resolve(v.value):p({kind:"read",provenance:I,workspaceId:f,agentId:k},S));v.dirty+=1;const E=B.then(P=>p(_(P),S));return v.tail=E,E.then(P=>{v.dirty-=1,v.tail===E&&(v.tail=void 0),u(P,!0)},()=>{v.dirty-=1,v.tail===E&&(v.tail=void 0)}),E};return{authority:()=>i?null:n(),read:m,async edit(f,k,_,I){const S=++o;return w(k,_,v=>({kind:"edit",provenance:v.provenance,workspaceId:k,agentId:_,lifetime:v.lifetime,revision:v.revision,origin:f,sequence:S,snapshot:I}))},async flush(f,k){const _=l(),I=c(),S=d(_,f,k),v=await(S.tail??(S.value?Promise.resolve(S.value):m(f,k)));await p({kind:"flush",provenance:_,workspaceId:f,agentId:k,lifetime:v.lifetime,revision:v.revision},I)},async clear(f,k){await w(f,k,_=>({kind:"clear",provenance:_.provenance,workspaceId:f,agentId:k,lifetime:_.lifetime,revision:_.revision,origin:s}))},subscribe(f){return r.add(f),()=>{r.delete(f)}},dispose(){i=!0,g(),r.clear(),a.clear()}}}let U=null;async function uo(e,t,n,a,r){const s=U;if(!s)throw new Error("draft-shared-transport-unavailable");const o=()=>{if(U!==s||s.authority()!==r)throw new Error("draft-authority-changed")};o(),await s.edit(e,t,n,a),o(),await s.flush(t,n),o()}async function mo(e,t){await Promise.resolve(),U&&await U.flush(e,t)}function po(){if(!et())return null;const e=sr({request:n=>it(tr,n),subscribe:n=>Mn(a=>{a.method===nr&&n(a.params)})},()=>xn(A.state),()=>Pn(A.state));U=e;const t=e.dispose;return e.dispose=()=>{U===e&&(U=null),t()},e}const vt=new Map;function St(e,t){return`${e}\0${t}`}function fo(e,t){return vt.get(St(e,t))}function ho(e,t,n){vt.set(St(e,t),n)}const go=A.createSelector((e,t,n)=>{const a=e.chatPanelUi.byWorkspaceId[t];return a?R(a.userMessageIndexes,n):void 0}),yo=A.createSelector((e,t,n)=>{const a=e.chatPanelUi.byWorkspaceId[t];return a?R(a.retryAgents,n):void 0});function or(e){e=Math.max(0,e);const t=Math.floor(e/1e3);if(t<10){const s=e/1e3,o=s.toFixed(1);return o.endsWith(".0")?`${Math.round(s)}s`:`${o}s`}if(t<60)return`${t}s`;const n=Math.floor(t/3600),a=Math.floor(t%3600/60),r=t%60;return n>0?`${n}h ${a}m ${r}s`:`${a}m ${r}s`}function wo(e){return or(Math.max(1e3,Math.round(e/1e3)*1e3))}const ir=new Set(["launch","init","session-create","session-load","prompt"]),cr=new Set(["tool-call","tool-waiting"]);function lr(e){let t=null;for(const n of e)(!t||n.timestamp>=t.timestamp)&&(t=n);return t}function bo(e){return e&&ir.has(e)?"pulse":e&&cr.has(e)?"twist":"bloom"}const Mt="stalled";function ko(e,t){const n=lr(e);return!n||n.phase!==Mt||typeof t=="number"&&t>n.timestamp?null:n}function _o(e){let t=null;for(const n of e)n.phase!==Mt&&(!t||n.timestamp>=t.timestamp)&&(t=n);return t}const Ve={get title(){return h.chat_streamingStatus_sessionCorrupted_title()},get message(){return h.chat_streamingStatus_sessionCorrupted_message()}},dr=/^session\/[a-z_]+(?: failed)?:\s*/i;function ur(e){const n=(e.split(`
12
- `).map(a=>a.trim()).find(Boolean)??"").replace(dr,"");return n.charAt(0).toUpperCase()+n.slice(1)}function vo(e,t){return e?t===!0?{corrupted:!0,title:Ve.title,message:Ve.message,detail:e}:{corrupted:!1,title:h.chat_streamingStatus_responseFailed_label(),message:ur(e),detail:null}:null}const So=A.createSelector((e,t)=>R(e.questionUi.consumers,t)),mr=3e4,J=new Map;function Mo(e,t){const n=J.get(e);n&&clearTimeout(n.timer);const a=setTimeout(()=>J.delete(e),mr);J.set(e,{value:t,timer:a})}function Ao(e){const t=J.get(e);if(t)return clearTimeout(t.timer),J.delete(e),t.value}const At=A.createSelector((e,t,n)=>e.agentWorkers?.byKey[Ht(t,n)]??Nt),pr=A.createSelector((e,t,n)=>{const a=At.select(e,t,n);return a.status==="unsupported"?[]:(a.snapshot?.workers??[]).filter(r=>r.status==="running"||r.status==="unknown")}),Io=A.createSelector((e,t,n)=>{const a=At.select(e,t,n);return a.status==="failed"?!0:a.status!=="ready"||!a.snapshot?!1:a.snapshot.truncated?!0:a.snapshot.support.status!=="supported"&&pr.select(e,t,n).length>0}),fr=1e3,It={requireViewedAndFocused:!0,requireAssistantTail:!0},X=new Map,x=new Map;let j=null;function Ee(e){(e===void 0||j===e)&&(j=null)}const hr=200;function gr(e,t){if(x.delete(e),x.set(e,t),x.size>hr){const n=x.keys().next().value;n!==void 0&&x.delete(n)}}function Tt(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(!n.isStreaming&&typeof n.id=="string"&&n.id.length>0)return n}return null}function To(e){return Tt(e)?.id??null}function Co(e){De(e,{requireViewedAndFocused:!0})}function Eo(e){De(e,{requireViewedAndFocused:!1})}function Do(e){Ee(),De(e,It)}function Ro(e){j===e&&(X.has(e)||(j=null,Re(e,It)))}function xo(e){for(const t of e)typeof t!="string"||t.length===0||(Ct(t),Ee(t),Re(t,{requireViewedAndFocused:!1}))}function Ct(e){const t=X.get(e);t&&(clearTimeout(t.timer),X.delete(e))}function De(e,t){Ct(e),Ee(e);const n=setTimeout(()=>{X.delete(e),Re(e,t)},fr);X.set(e,{timer:n,gates:t})}let ze=null;function yr(){return ze??=Promise.all([fe(()=>import("./D4ytz2EC.js"),__vite__mapDeps([37,1,2,3,4,5,6,7,8,9,10,11,38,39]),import.meta.url),fe(()=>import("./BbhtQrkZ.js").then(e=>e.s),__vite__mapDeps([40,41,8,3,1,2,4,5,6,7,9,10,11,20,21,17,18,22,42,43,44,13]),import.meta.url)]).then(([e,t])=>({appStore:e.store,appClient:t.appClient})),ze}async function Re(e,t){let n=null;try{const{appStore:a,appClient:r}=await yr(),s=a.state;if(t.requireViewedAndFocused&&(s.unreadTracking?.currentlyViewedAgentId!==e||typeof document<"u"&&!document.hasFocus()))return;const o=s.agentSessions?.byAgentId[e];if(!o)return;const i=typeof o.workspaceId=="string"?o.workspaceId:"";if(i.length===0)return;if(t.requireAssistantTail&&s.chatState?.byAgentId[e]?.initialHistoryPending){j=e;return}const l=Tt(o.messages??[]);if(!l){t.requireAssistantTail&&(j=e);return}if(t.requireAssistantTail&&l.role!=="assistant")return;const c=l.id;if(x.get(e)===c)return;gr(e,c),n=c,!(await r.agents.markSeen({workspaceId:i,agentId:e,messageId:c})).success&&x.get(e)===n&&x.delete(e)}catch{n!==null&&x.get(e)===n&&x.delete(e)}}const ie=new Map;function Et(e,t){return`${e}\0${t}`}function Po(e,t){return ie.get(Et(e,t))}function Bo(e,t,n){ie.set(Et(e,t),n)}function Oo(e){if(e.length===0)return;const t=new Set(e);for(const n of[...ie.keys()]){const a=n.slice(n.indexOf("\0")+1);t.has(a)&&ie.delete(n)}}export{ks as $,Gn as A,es as B,ms as C,O as D,cs as E,za as F,ds as G,Pa as H,Ra as I,Xn as J,mo as K,wo as L,fr as M,Ys as N,eo as O,ko as P,Po as Q,bt as R,fo as S,js as T,Cs as U,je as V,Fs as W,Es as X,_o as Y,bo as Z,zs as _,_s as a,Mo as a$,Gs as a0,Ms as a1,As as a2,Ks as a3,rs as a4,sa as a5,Xs as a6,as as a7,lo as a8,Y as a9,vs as aA,Ee as aB,Is as aC,Yr as aD,no as aE,$s as aF,pr as aG,At as aH,Io as aI,Ts as aJ,zr as aK,Gr as aL,Vr as aM,Ps as aN,Os as aO,Bs as aP,Ls as aQ,wt as aR,So as aS,yo as aT,go as aU,Bo as aV,ho as aW,Zs as aX,ns as aY,xs as aZ,co as a_,os as aa,ss as ab,Vs as ac,Xr as ad,io as ae,xo as af,Ro as ag,Co as ah,Eo as ai,Do as aj,To as ak,Ns as al,to as am,Ss as an,ps as ao,Wn as ap,uo as aq,is as ar,bs as as,us as at,Ua as au,ht as av,Qr as aw,qs as ax,ao as ay,Hs as az,we as b,Ws as b0,La as b1,Ao as b2,oa as b3,ts as b4,so as c,ys as d,ws as e,Js as f,Zr as g,xa as h,Jr as i,Us as j,ca as k,ia as l,oo as m,ro as n,Oo as o,Rs as p,Qs as q,gs as r,hs as s,ls as t,po as u,fs as v,vo as w,Ds as x,Ca as y,ge as z};
11
+ `),e)}function bs(e,t,n){if(e==="suggested-prompt")return{fields:{},hasAttachments:!1,cleanup:{clearInput:!1,followBottom:!0,historyText:null}};const a=n(),{imageBlocks:r,fileBlocks:s}=Ra(a.contextItems);return{fields:{contextItems:a.contextItems,workspaceContextStr:xa(a.contextItems,a.checkedPanels,a.checkedSelections),noteIds:a.noteIds,...r.length>0?{imageBlocks:r}:{},...s.length>0?{fileBlocks:s}:{},...a.pickedMentions?{messageMetadata:a.pickedMentions}:{}},hasAttachments:r.length>0||s.length>0,cleanup:{clearInput:!0,followBottom:!0,historyText:t}}}function ks(e){switch(e.kind){case"tooLong":return h.chat_goal_tooLong_error({max:H(Tn)});case"attachments":return h.chat_goal_attachments_error();case"retired":return h.chat_goal_retired_error();case"workspaceRetired":return h.chat_goal_workspaceRetired_error();case"invalid":case"failed":return h.chat_goal_failed_error()}}const Pa="chat-read:",q=new Map,ye=new Set;function _s(e,t){let n=q.get(e);n||(n=new Set,q.set(e,n)),n.add(t)}function vs(e,t){const n=q.get(e);if(!(!n||!n.delete(t))&&n.size===0){q.delete(e);for(const a of[...ye])a(e)}}function Ss(e){return ye.add(e),()=>ye.delete(e)}function Ms(e){return q.has(e)}function As(e){const t=q.get(e);if(!t)return!1;for(const n of t)if(!n.startsWith(Pa))return!0;return!1}function Ba(e,t,n){const a=e.state.pendingSubmissions.byAgentId[t.agentId];if(!a||!Ge(a.scope,t))return null;const r={...structuredClone(n),id:crypto.randomUUID(),createdAt:Date.now()};e.dispatch(Bt(t,r));const s=e.state.pendingSubmissions.byAgentId[t.agentId];return s&&R(s.submissions,r.id)?r:null}function Oa(e,t,n,a,r){const s=Be.select(e.state,n),o=pe.select(e.state)?.principal.id,i=Ue(e.state);if(!s||!o||!i)return null;const l=Cn(t,n),c={agentId:t,workspaceId:n,principalId:o,participation:s,authority:i,owner:l.key,lifetime:e.state.pendingSubmissions.byAgentId[t]?.scope.lifetime??crypto.randomUUID()},d=()=>l.isCurrent(e.state.agentSessions?.byAgentId[t]?.workspaceId)&&Be.select(e.state,n)===s&&pe.select(e.state)?.principal.id===o&&Ue(e.state)===i;if(!d())return null;e.dispatch(Pt(c,a,Wt.select(e.state,n)));const u=Ba(e,c,r);return u?{scope:c,submission:u,isCurrent:()=>{const g=e.state.pendingSubmissions.byAgentId[t];return d()&&!!g&&Ge(g.scope,c)&&(!!R(g.operations,u.id)||!!R(g.submissions,u.id))}}:null}function we(e,t,n){if(!n.text.trim()&&!n.imageBlocks?.length&&!n.fileBlocks?.length)return null;const a=n.userAppMessageId??En();return Oa(e,t,n.wsId,pe.select(e.state)?.capabilities.submissionCorrelation,{content:n.text.trim(),appMessageId:a,destination:!n.forceSubmit&&qt.select(e.state,t)?"queue":"conversation",contextItems:n.contextItems,imageBlocks:n.imageBlocks,fileBlocks:n.fileBlocks,messageMetadata:n.messageMetadata})}function La(e,t,n){const a=we(e,t,n);return a?(e.dispatch(Ye(t,{...n,userAppMessageId:a.submission.appMessageId,submission:{scope:a.scope,id:a.submission.id}})),!0):!1}async function Ua(e,t,n,a){const r=n.submission;if(!r)return"legacy";const s=r.reference,o=()=>s.scope.agentId===e&&s.scope.workspaceId===t&&Xe.select(A.state,e)===n?bn.select(A.state,s.scope):void 0,i=o();if(!i)return null;if(!i.supported)return"legacy";const l={wsId:t,text:n.text,imageBlocks:n.options?.imageBlocks,fileBlocks:n.options?.fileBlocks,noteIds:n.options?.noteIds,messageMetadata:n.options?.messageMetadata,model:a??n.options?.model};if(r.outcome==="rejected"){const p=R(i.tombstones,s.id);return R(i.submissions,s.id)||p&&p.reason!=="rejected"?null:we(A,e,l)}if(r.outcome==="accepted")return we(A,e,l);await Promise.all([Dn(e,t).catch(()=>{}),Rn(e,t).catch(()=>{})]);const c=o();if(!c||R(c.submissions,s.id)?.status!=="uncertain")return null;const{notify:d}=await fe(async()=>{const{notify:p}=await import("./Bhq56Jsu.js").then(m=>m.i);return{notify:p}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]),import.meta.url);if(o()!==c)return null;let u=!1;const g=()=>{u=!0};return d.warning(h.agent_chatSend_uncertainRetry_description(),{key:`submission-retry:${t}:${e}:${s.id}`,duration:Number.POSITIVE_INFINITY,action:{label:h.agent_chatSend_resend_label(),onClick:()=>{if(u)return;u=!0;const p=o();!p||p.generation!==c.generation||p.submissions!==c.submissions||p.observationVersion!==c.observationVersion||R(p.submissions,s.id)?.status!=="uncertain"||La(A,e,l)}},cancel:{label:h.chat_richInput_cancel_label(),onClick:g},onDismiss:g}),null}async function Is(e,t,n){const a=Xe.select(A.state,e),r=a?.submission?await Ua(e,t,a,n):"legacy";if(r){if(r==="legacy"){await A.dispatch(n===void 0?Ot(e,t):Lt(e,t,n));return}!r.isCurrent()||!a||A.dispatch(Ye(e,{wsId:t,text:a.text,imageBlocks:a.options?.imageBlocks,fileBlocks:a.options?.fileBlocks,noteIds:a.options?.noteIds,messageMetadata:a.options?.messageMetadata,model:n??a.options?.model,userAppMessageId:r.submission.appMessageId,submission:{scope:r.scope,id:r.submission.id}}))}}const Ts=A.createSelector((e,t)=>{const n=R(e.chatDrafts.owners,t);return n?{restore:n.restore,saves:Je(n.saves),shared:n.restore?e.chatDrafts.shared[JSON.stringify([n.restore.workspaceId,n.restore.agentId])]:void 0}:void 0});function $a(e,t){return t.workspaceId===e&&!t.retiredAt&&!t.pendingDeleteAt&&t.status!==ke.Deleted&&!t.notificationsMuted&&$t(t)==="topLevel"}function Na(e){const t=e.metadata?.pendingQuestionsMessageId;return typeof t=="string"&&t.length>0&&!Bn(e.metadata,t)?t:null}function Ha(e){return e.status===ke.Error&&!jt(Vt(e))}function Cs(e,t){return t.filter(n=>$a(e,n)).flatMap(n=>{const a=Ut(n),r=Na(n),s=n.status===ke.Error;if(!a&&!r&&!s)return[];const o=a?.timestamp??(s?n.stopReasonTimestamp:void 0);return[{agentId:n.id,agentName:n.name,kind:a?.kind??(s?"failed":"question"),reason:a?.reason,timestamp:o&&Number.isFinite(Date.parse(o))?o:void 0,questionMessageId:r,canRetry:Ha(n)}]})}function Es(e){return e.displayStatus==="failed"?"failed":e.displayStatus==="blocked"?"blocked":e.attention==="review_required"?"review":e.displayStatus==="needs_attention"?"question":e.activity==="agent_running"||e.displayStatus==="in_progress"?"running":e.scriptsRunning===!0?"scripts_running":e.backgroundTasksRunning===!0?"background_tasks_running":e.displayStatus==="pr_ready"?"pr_ready":e.displayStatus==="pr_merged"?"merged":e.displayStatus==="complete"?"complete":e.attention==="unread"?"unread":e.displayStatus==="pr_open"||e.displayStatus==="pr_queued"?e.displayStatus:"idle"}function Ds(e){const t=e.kind==="prs"?e.organization?.trim().toLowerCase():void 0;return{key:JSON.stringify([e.kind,e.workspaceId,t||null,[...new Set((t?[]:e.repositories).map(n=>JSON.stringify([n.key,n.owner,n.name])))].sort()]),hasGitHubRepositories:!!t||e.repositories.some(n=>!!n.owner),hasLocalRepositories:!t&&e.repositories.some(n=>!n.owner)}}function Te(e){const t=Sn(e);if(t?.kind!=="pr"||!Number.isSafeInteger(t.number)||t.number<=0)return null;const n=t.owner.toLowerCase(),a=t.repo.toLowerCase();return{owner:n,repo:a,number:t.number,id:`${n}/${a}#${t.number}`,url:`https://github.com/${n}/${a}/pull/${t.number}`}}function Rs(e,t,n,a){const r=e.filter(s=>a?a.includes(s.id):n?s.repositoryOwner?.toLowerCase()===n.toLowerCase():t.some(o=>o.owner?.toLowerCase()===s.repositoryOwner?.toLowerCase()&&o.name.toLowerCase()===s.repositoryName?.toLowerCase()));return[...new Map(r.flatMap(s=>[...(s.pullRequests??[]).map(o=>o.url),s.activePullRequest?.url,s.prUrl]).flatMap(s=>{const o=s?Te(s):null;return o?[[o.id,{owner:o.owner,repo:o.repo,number:o.number}]]:[]})).values()].sort((s,o)=>`${s.owner}/${s.repo}#${s.number}`.localeCompare(`${o.owner}/${o.repo}#${o.number}`))}function xs(e,t){const[n]=t;return t.length!==1||e.owner?.toLowerCase()!==n?.owner?.toLowerCase()||e.repo?.toLowerCase()!==n?.name.toLowerCase()}const Ps=A.createSelector(e=>e.homeIntegrations),Bs=A.createSelector(e=>{const t=e.homeIntegrations;return!t.linkedItems||!Object.keys(t.linkedItems).length?t:{...t,items:[...new Map([...Object.values(t.linkedItems),...t.items].map(n=>[n.id,n])).values()].sort((n,a)=>(a.updatedAt??"").localeCompare(n.updatedAt??""))}}),wt=A.createSelector(e=>Je(e.workspace.workspaces).flatMap(t=>[...(t.pullRequests??[]).map(n=>n.url),t.activePullRequest?.url,t.prUrl].filter(n=>!!n).map(n=>({url:Te(n)?.url??n.replace(/\/$/,"").toLowerCase(),workspaceId:t.id,name:t.title||t.id})))),Os=A.createSelector(e=>{const t=e.homeIntegrations.detail?.url,n=t?Te(t)?.url??t.replace(/\/$/,"").toLowerCase():void 0;return wt.select(e).find(a=>a.url===n)??null}),Ls=A.createSelector(e=>wt.select(e).map(t=>t.url)),Fa=["setup-retry-not-remote","setup-retry-not-failed","setup-retry-shared-checkout","setup-retry-no-script","agent-busy","agent-not-running","machine-update-required","machine-unreachable"];function Us(e,t){return e&&t?.state==="failed"}function Ka(e){const t=e??{},n=typeof t.message=="string"?t.message:"";if(t.rpcCode===-32601||t.code==="METHOD_NOT_FOUND")return{ok:!1,code:"unsupported",message:n};const a=typeof t.data?.code=="string"?t.data.code:t.code;return{ok:!1,code:Fa.find(s=>s===a)??"unknown",message:n}}async function $s(e,t=it){try{const n=await t("agent.retrySetup",{workspaceId:e.workspaceId,agentId:e.agentId}),a=ln.safeParse(n?.setup);return{ok:!0,setup:a.success?a.data:null}}catch(n){return Ka(n)}}function Wa(e){return e.code==="unsupported"?h.remoteAgent_setupRetry_unsupported_error():e.message.trim()||h.remoteAgent_setupRetry_generic_error()}function Ns(e,t){On.error(h.remoteAgent_setupRetry_failed_title({machine:e}),{description:Wa(t)})}let te=null;function Hs(e){return te=e,()=>{te===e&&(te=null)}}function Fs(){return te}function Ks(e){return[...e.groups.length>0?e.groups.filter(n=>n.expanded).flatMap(n=>n.items):e.workspaces,...e.asideExpanded?e.aside:[]].map(n=>n.id)}function Ws(e,t,n){if(e.length===0)return null;const a=t===null?-1:e.indexOf(t);return a===-1?e[0]:e[a+(n==="clockwise"?1:-1)]??null}let F=[];function qs(e,t={}){const n={source:e,fallback:t.fallback===!0};return F=[...F,n],()=>{F=F.filter(a=>a!==n)}}function js(){const e=F.findLast(n=>!n.fallback);return e?e.source:F.findLast(n=>n.fallback&&(n.source.available?.()??!0))?.source??null}function Vs(e){if(!e?.isConnected||e.closest("[inert]"))return!1;const t=e.ownerDocument.querySelectorAll('[aria-modal="true"]');return Array.from(t).every(n=>n.contains(e))}const zs=ct("conversationGoal/commandSend","conversationGoal/commandSendRequested"),Gs=ct("conversationGoal/set","conversationGoal/setRequested");function Ys(e){return In(e)}function qa(e){return An(e)}function ja(e,t){return!e||!t?!1:e.getFullYear()===t.getFullYear()&&e.getMonth()===t.getMonth()&&e.getDate()===t.getDate()}function me(e){if(e.length===0)return[];const t=[];let n=null;for(const a of e){const r=a.timestamp?typeof a.timestamp=="string"?new Date(a.timestamp):a.timestamp:new Date;(!n||!ja(n.date,r))&&(n={date:r,label:qa(r),messages:[]},t.push(n)),n.messages.push(a)}return t}function Js(e){const t=new Map;return e.map(({date:n})=>{const a=`${n.getFullYear()}-${n.getMonth()+1}-${n.getDate()}`,r=t.get(a)??0;return t.set(a,r+1),r===0?a:`${a}#${r}`})}function Xs(e,t){const n=new Map;let a=t?null:void 0;for(const r of e.groups)for(const s of r.messages)a!==void 0&&n.set(s.id,a),s.role==="user"&&!Un(s)&&(a=s);return n}function Va(e){return`${e.getFullYear()}-${e.getMonth()+1}-${e.getDate()}`}function qe(e,t){const n=new Map;return e.map(a=>{const r=`${t}-${Va(a.date)}`,s=(n.get(r)??0)+1;return n.set(r,s),{...a,groupKey:s===1?r:`${r}-${s}`}})}function za(e,t){if(e.length===0||t.length===0)return e;const n=new Set(t.map(s=>s.id)),a=new Set(t.map(s=>s.appMessageId).filter(s=>typeof s=="string"&&s.length>0)),r=e.filter(s=>!n.has(s.id)&&!(typeof s.appMessageId=="string"&&s.appMessageId.length>0&&a.has(s.appMessageId)));return r.length===e.length?e:r}function Qs(e,t,n){return e=za(e,t),e.length===0?{groups:me(t),detached:!1,hiddenTail:[]}:n?{groups:qe(me(e),"h"),detached:!0,hiddenTail:t}:{groups:qe(me([...e,...t]),"d"),detached:!1,hiddenTail:[]}}function Zs(e){const{scrollTop:t,threshold:n,fetching:a,exhausted:r,historyCount:s,tailCount:o,tailTruncated:i,totalMessages:l,spacerAbove:c=0}=e;return t>n+c||a||r?!1:s>0||i||l>o+s}const eo=300;function to(e){const{fetching:t,chainEvaluationPending:n,visible:a,hideArmed:r}=e;return t||n?a&&!r?"none":"show":a&&!r?"arm-hide":"none"}const je=24,Ga=320;function Ce(e){return Number.isFinite(e)?Math.min(Ga,Math.max(je,e)):je}const Ya=.2,Ja=.12;function Xa(e,t,n=Ya){const a=Ce(t);return e===null||!Number.isFinite(e)?a:e+n*(a-e)}function no(e,t){const n=Ce(t??Number.NaN);return{above:Math.round(Math.max(0,e.above)*n),below:Math.round(Math.max(0,e.below)*n)}}function ao(e){const{totalMessages:t,residentCount:n,exhausted:a,residentContentHeight:r,currentSpacerHeight:s,viewportHeight:o}=e;let i=e.rowHeightEma;n>0&&r>0&&(i=Xa(i,r/n));const l=e.unloadedRows??t-n,d=a||t<=0||n<=0||l<=0||i===null?0:Math.round(l*i),u=Math.abs(d-s);return u===0?{spacerHeight:s,rowHeightEma:i,applied:!1,scrollTopDelta:0}:d===0||s===0||u>s*Ja||o>0&&u>o?{spacerHeight:d,rowHeightEma:i,applied:!0,scrollTopDelta:d-s}:{spacerHeight:s,rowHeightEma:i,applied:!1,scrollTopDelta:0}}const Qa=Ln,Za=2;function ro(e){const{scrollTop:t,spacerAboveHeight:n,rowHeightEstimate:a,pageSize:r=Qa,nearPages:s=Za}=e;if(n<=0||t>=n)return"serial";const o=Ce(a??Number.NaN);return(n-Math.max(0,t))/o>s*r?"seek":"serial"}const bt=200,er=1;function so(e,t,n=bt){const a=t.timestamp-n;return[...e.filter(r=>r.timestamp>=a),t]}function oo(e){const{samples:t,viewportHeight:n,windowMs:a=bt,viewportFactor:r=er}=e;if(n<=0||t.length<2)return"gentle";const s=t[t.length-1].timestamp-a,o=t.filter(l=>l.timestamp>=s);if(o.length<2)return"gentle";let i=0;for(let l=1;l<o.length;l+=1)i+=Math.abs(o[l].scrollTop-o[l-1].scrollTop);return i>n*r?"rapid":"gentle"}function io(e){const{scrollTop:t,spacerAboveHeight:n,unloadedRowsAbove:a}=e;if(a<=0||n<=0)return 0;const r=Math.min(1,Math.max(0,t/n));return Math.min(a-1,Math.max(0,Math.floor(r*a)))}function co(e){const{totalMessages:t,residentCount:n,exhausted:a,startOrdinalEstimate:r,detachedFromTail:s}=e,o=Math.max(0,t-n);if(!s)return{above:a?0:o,below:0};const i=Math.max(0,e.hiddenTailCount??0);if(a)return{above:0,below:o+i};if(r!==null){const c=Math.min(o,Math.max(0,Math.round(r)));return{above:c,below:o-c+i}}const l=Math.min(o,Math.max(0,Math.round(e.holeRowsEstimate??0)));return{above:o-l,below:l+i}}function lo(e){const{exhausted:t,historyCount:n,tailCount:a,tailTruncated:r,totalMessages:s}=e;return t?!0:n>0?!1:!r&&s<=a}const tr="intent.drafts.sync",nr="intent.drafts.changed",ar=L({id:C(),type:C(),label:C(),description:C().optional(),content:C().optional(),path:C().optional(),imageData:C().optional(),imageMimeType:C().optional(),attachmentId:C().optional(),attachmentMimeType:C().optional(),attachmentSize:ce().optional(),sourcePath:C().optional(),placementStatus:z("failed").optional(),screen:$n().optional()}),kt=L({text:C(),attachments:Nn(ar)}),G={provenance:C().min(1),workspaceId:C().min(1),agentId:C().min(1)},ne={lifetime:C(),revision:ce().int().nonnegative()};Hn("kind",[L({...G,kind:z("read")}),L({...G,...ne,kind:z("edit"),origin:C().min(1),sequence:ce().int().positive(),snapshot:kt}),L({...G,...ne,kind:z("flush")}),L({...G,...ne,kind:z("clear"),origin:C().min(1)})]);const _t=L({...G,...ne,origin:C(),sequence:ce().int().nonnegative(),snapshot:kt}),rr=L({accepted:Fn(),draft:_t});function sr(e,t,n=t){const a=new Map,r=new Set,s=crypto.randomUUID();let o=0,i=!1;const l=()=>{const f=t();if(i||!f)throw new Error("draft-authority-unavailable");return f},c=()=>{const f=n();if(!f||i)throw new Error("draft-authority-unavailable");return()=>{if(i||n()!==f)throw new Error("draft-authority-changed")}},d=(f,k,_)=>{const I=JSON.stringify([f,k,_]);let S=a.get(I);return S||(S={dirty:0},a.set(I,S)),S},u=(f,k)=>{if(i||f.provenance!==t())return;const _=d(f.provenance,f.workspaceId,f.agentId);if(!(_.value?.lifetime===f.lifetime&&_.value.revision>f.revision)&&(_.value=f,k&&_.dirty===0))for(const I of r)I(f)},g=e.subscribe(f=>{const k=_t.safeParse(f);k.success&&u(k.data,!0)}),p=async(f,k)=>{k();const _=rr.parse(await e.request(f));if(k(),f.provenance!==l()||_.draft.provenance!==f.provenance)throw new Error("draft-authority-changed");if(!_.accepted)throw u(_.draft,!1),new Error("draft-changed-in-another-editor");return _.draft},m=async(f,k)=>{const _=l(),I=c(),S=d(_,f,k);S.tail&&await S.tail;const v=await p({kind:"read",provenance:_,workspaceId:f,agentId:k},I);return u(v,!1),v},w=(f,k,_)=>{const I=l(),S=c(),v=d(I,f,k),B=v.tail??(v.value?Promise.resolve(v.value):p({kind:"read",provenance:I,workspaceId:f,agentId:k},S));v.dirty+=1;const E=B.then(P=>p(_(P),S));return v.tail=E,E.then(P=>{v.dirty-=1,v.tail===E&&(v.tail=void 0),u(P,!0)},()=>{v.dirty-=1,v.tail===E&&(v.tail=void 0)}),E};return{authority:()=>i?null:n(),read:m,async edit(f,k,_,I){const S=++o;return w(k,_,v=>({kind:"edit",provenance:v.provenance,workspaceId:k,agentId:_,lifetime:v.lifetime,revision:v.revision,origin:f,sequence:S,snapshot:I}))},async flush(f,k){const _=l(),I=c(),S=d(_,f,k),v=await(S.tail??(S.value?Promise.resolve(S.value):m(f,k)));await p({kind:"flush",provenance:_,workspaceId:f,agentId:k,lifetime:v.lifetime,revision:v.revision},I)},async clear(f,k){await w(f,k,_=>({kind:"clear",provenance:_.provenance,workspaceId:f,agentId:k,lifetime:_.lifetime,revision:_.revision,origin:s}))},subscribe(f){return r.add(f),()=>{r.delete(f)}},dispose(){i=!0,g(),r.clear(),a.clear()}}}let U=null;async function uo(e,t,n,a,r){const s=U;if(!s)throw new Error("draft-shared-transport-unavailable");const o=()=>{if(U!==s||s.authority()!==r)throw new Error("draft-authority-changed")};o(),await s.edit(e,t,n,a),o(),await s.flush(t,n),o()}async function mo(e,t){await Promise.resolve(),U&&await U.flush(e,t)}function po(){if(!et())return null;const e=sr({request:n=>it(tr,n),subscribe:n=>Mn(a=>{a.method===nr&&n(a.params)})},()=>xn(A.state),()=>Pn(A.state));U=e;const t=e.dispose;return e.dispose=()=>{U===e&&(U=null),t()},e}const vt=new Map;function St(e,t){return`${e}\0${t}`}function fo(e,t){return vt.get(St(e,t))}function ho(e,t,n){vt.set(St(e,t),n)}const go=A.createSelector((e,t,n)=>{const a=e.chatPanelUi.byWorkspaceId[t];return a?R(a.userMessageIndexes,n):void 0}),yo=A.createSelector((e,t,n)=>{const a=e.chatPanelUi.byWorkspaceId[t];return a?R(a.retryAgents,n):void 0});function or(e){e=Math.max(0,e);const t=Math.floor(e/1e3);if(t<10){const s=e/1e3,o=s.toFixed(1);return o.endsWith(".0")?`${Math.round(s)}s`:`${o}s`}if(t<60)return`${t}s`;const n=Math.floor(t/3600),a=Math.floor(t%3600/60),r=t%60;return n>0?`${n}h ${a}m ${r}s`:`${a}m ${r}s`}function wo(e){return or(Math.max(1e3,Math.round(e/1e3)*1e3))}const ir=new Set(["launch","init","session-create","session-load","prompt"]),cr=new Set(["tool-call","tool-waiting"]);function lr(e){let t=null;for(const n of e)(!t||n.timestamp>=t.timestamp)&&(t=n);return t}function bo(e){return e&&ir.has(e)?"pulse":e&&cr.has(e)?"twist":"bloom"}const Mt="stalled";function ko(e,t){const n=lr(e);return!n||n.phase!==Mt||typeof t=="number"&&t>n.timestamp?null:n}function _o(e){let t=null;for(const n of e)n.phase!==Mt&&(!t||n.timestamp>=t.timestamp)&&(t=n);return t}const Ve={get title(){return h.chat_streamingStatus_sessionCorrupted_title()},get message(){return h.chat_streamingStatus_sessionCorrupted_message()}},dr=/^session\/[a-z_]+(?: failed)?:\s*/i;function ur(e){const n=(e.split(`
12
+ `).map(a=>a.trim()).find(Boolean)??"").replace(dr,"");return n.charAt(0).toUpperCase()+n.slice(1)}function vo(e,t){return e?t===!0?{corrupted:!0,title:Ve.title,message:Ve.message,detail:e}:{corrupted:!1,title:h.chat_streamingStatus_responseFailed_label(),message:ur(e),detail:null}:null}const So=A.createSelector((e,t)=>R(e.questionUi.consumers,t)),mr=3e4,J=new Map;function Mo(e,t){const n=J.get(e);n&&clearTimeout(n.timer);const a=setTimeout(()=>J.delete(e),mr);J.set(e,{value:t,timer:a})}function Ao(e){const t=J.get(e);if(t)return clearTimeout(t.timer),J.delete(e),t.value}const At=A.createSelector((e,t,n)=>e.agentWorkers?.byKey[Ht(t,n)]??Nt),pr=A.createSelector((e,t,n)=>{const a=At.select(e,t,n);return a.status==="unsupported"?[]:(a.snapshot?.workers??[]).filter(r=>r.status==="running"||r.status==="unknown")}),Io=A.createSelector((e,t,n)=>{const a=At.select(e,t,n);return a.status==="failed"?!0:a.status!=="ready"||!a.snapshot?!1:a.snapshot.truncated?!0:a.snapshot.support.status!=="supported"&&pr.select(e,t,n).length>0}),fr=1e3,It={requireViewedAndFocused:!0,requireAssistantTail:!0},X=new Map,x=new Map;let j=null;function Ee(e){(e===void 0||j===e)&&(j=null)}const hr=200;function gr(e,t){if(x.delete(e),x.set(e,t),x.size>hr){const n=x.keys().next().value;n!==void 0&&x.delete(n)}}function Tt(e){for(let t=e.length-1;t>=0;t--){const n=e[t];if(!n.isStreaming&&typeof n.id=="string"&&n.id.length>0)return n}return null}function To(e){return Tt(e)?.id??null}function Co(e){De(e,{requireViewedAndFocused:!0})}function Eo(e){De(e,{requireViewedAndFocused:!1})}function Do(e){Ee(),De(e,It)}function Ro(e){j===e&&(X.has(e)||(j=null,Re(e,It)))}function xo(e){for(const t of e)typeof t!="string"||t.length===0||(Ct(t),Ee(t),Re(t,{requireViewedAndFocused:!1}))}function Ct(e){const t=X.get(e);t&&(clearTimeout(t.timer),X.delete(e))}function De(e,t){Ct(e),Ee(e);const n=setTimeout(()=>{X.delete(e),Re(e,t)},fr);X.set(e,{timer:n,gates:t})}let ze=null;function yr(){return ze??=Promise.all([fe(()=>import("./CjpWOZGa.js"),__vite__mapDeps([37,1,2,3,4,5,6,7,8,9,10,11,38,39]),import.meta.url),fe(()=>import("./CVtLV3_x.js").then(e=>e.s),__vite__mapDeps([40,41,8,3,1,2,4,5,6,7,9,10,11,20,21,17,18,22,42,43,44,13]),import.meta.url)]).then(([e,t])=>({appStore:e.store,appClient:t.appClient})),ze}async function Re(e,t){let n=null;try{const{appStore:a,appClient:r}=await yr(),s=a.state;if(t.requireViewedAndFocused&&(s.unreadTracking?.currentlyViewedAgentId!==e||typeof document<"u"&&!document.hasFocus()))return;const o=s.agentSessions?.byAgentId[e];if(!o)return;const i=typeof o.workspaceId=="string"?o.workspaceId:"";if(i.length===0)return;if(t.requireAssistantTail&&s.chatState?.byAgentId[e]?.initialHistoryPending){j=e;return}const l=Tt(o.messages??[]);if(!l){t.requireAssistantTail&&(j=e);return}if(t.requireAssistantTail&&l.role!=="assistant")return;const c=l.id;if(x.get(e)===c)return;gr(e,c),n=c,!(await r.agents.markSeen({workspaceId:i,agentId:e,messageId:c})).success&&x.get(e)===n&&x.delete(e)}catch{n!==null&&x.get(e)===n&&x.delete(e)}}const ie=new Map;function Et(e,t){return`${e}\0${t}`}function Po(e,t){return ie.get(Et(e,t))}function Bo(e,t,n){ie.set(Et(e,t),n)}function Oo(e){if(e.length===0)return;const t=new Set(e);for(const n of[...ie.keys()]){const a=n.slice(n.indexOf("\0")+1);t.has(a)&&ie.delete(n)}}export{ks as $,Gn as A,es as B,ms as C,O as D,cs as E,za as F,ds as G,Pa as H,Ra as I,Xn as J,mo as K,wo as L,fr as M,Ys as N,eo as O,ko as P,Po as Q,bt as R,fo as S,js as T,Cs as U,je as V,Fs as W,Es as X,_o as Y,bo as Z,zs as _,_s as a,Mo as a$,Gs as a0,Ms as a1,As as a2,Ks as a3,rs as a4,sa as a5,Xs as a6,as as a7,lo as a8,Y as a9,vs as aA,Ee as aB,Is as aC,Yr as aD,no as aE,$s as aF,pr as aG,At as aH,Io as aI,Ts as aJ,zr as aK,Gr as aL,Vr as aM,Ps as aN,Os as aO,Bs as aP,Ls as aQ,wt as aR,So as aS,yo as aT,go as aU,Bo as aV,ho as aW,Zs as aX,ns as aY,xs as aZ,co as a_,os as aa,ss as ab,Vs as ac,Xr as ad,io as ae,xo as af,Ro as ag,Co as ah,Eo as ai,Do as aj,To as ak,Ns as al,to as am,Ss as an,ps as ao,Wn as ap,uo as aq,is as ar,bs as as,us as at,Ua as au,ht as av,Qr as aw,qs as ax,ao as ay,Hs as az,we as b,Ws as b0,La as b1,Ao as b2,oa as b3,ts as b4,so as c,ys as d,ws as e,Js as f,Zr as g,xa as h,Jr as i,Us as j,ca as k,ia as l,oo as m,ro as n,Oo as o,Rs as p,Qs as q,gs as r,hs as s,ls as t,po as u,fs as v,vo as w,Ds as x,Ca as y,ge as z};
@@ -1 +1 @@
1
- var De=Object.defineProperty;var Ce=(i,s,e)=>s in i?De(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var E=(i,s,e)=>Ce(i,typeof s!="symbol"?s+"":s,e);import{K as Le,P as ce,a6 as le,as as z,aC as ve}from"./Bm6N2soI.js";import{b_ as we,c$ as ue,cr as de,cq as be}from"./Klbdavqn.js";import{JH as p,Cg as Fe,bJ as ke,i as Ge,LM as me,ir as Ee,bV as Pe,Ec as H,CF as xe,fl as Ve,AL as Ue,e3 as fe,fh as _e,e2 as he,Be,Lq as $e,wy as Xe}from"./B9vHutcJ.js";import{aO as Se,dX as ge,A as K,P as Re,aK as Q}from"./C2UL5Ler.js";import{h as qe}from"./TB9r2XJy.js";import{c as W}from"./ChTqQfQN.js";import{a as We}from"./BdWqymET.js";import{m as j}from"./96V4v2iI.js";import"./3SdAC2_C.js";import{bm as n}from"./CLAmm_T1.js";import"./CcJmuwXr.js";import"./BwNrQXlF.js";import"./BbYWP3Ow.js";import{R as pe}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function ze(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Te="confirmUnslothModelSwitch";function He(i){if(!i||typeof i!="object")return!1;const{agentId:s,agentName:e,workspaceId:t,workspaceTitle:r}=i;return typeof s=="string"&&typeof e=="string"&&typeof t=="string"&&(r===null||typeof r=="string")}function Ke(i){for(let s=i,e=0;s&&e<4;e++){const t=s.data;if(t&&typeof t=="object"){const{code:r,currentModel:a,requestedModel:l,agents:o}=t;if(r==="unsloth-model-switch-confirmation-required"&&typeof a=="string"&&typeof l=="string"&&Array.isArray(o)&&o.every(He))return{currentModel:a,requestedModel:l,agents:o}}s=s.cause}}function bt(i){if(!i||!(Te in i))return i;const{[Te]:s,...e}=i;return Object.keys(e).length>0?e:void 0}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new We("PerformanceOptimizer"),w=class w{constructor(){E(this,"metricsBuffer");E(this,"metricsIndex",0);E(this,"metricsCount",0);E(this,"MAX_METRICS",500);E(this,"TARGET_RESPONSE_TIME",100);E(this,"memoCache",new Map);E(this,"MEMO_TTL",6e4);E(this,"MAX_CACHE_SIZE",100);E(this,"cacheHits",0);E(this,"cacheMisses",0);E(this,"pendingRequests",new Map);E(this,"requestQueue",[]);E(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let o=0;o<s.length;o+=r){const _=s.slice(o,o+r).map((c,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(c);d(k)},g)})}),u=await Promise.all(_);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const _=this.getMemoized(a);if(_!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),_;this.cacheMisses++}if(t.coalesce){const _=this.pendingRequests.get(s);if(_)return V.debug("Request coalesced",{operation:s}),_}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const o=await l;t.memoize&&this.memoize(a,o);const f=Z.now()-r;return this.recordMetric(s,f,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),f>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(f),target:this.TARGET_RESPONSE_TIME}),o}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const c=this.metricsBuffer[(e+u)%this.MAX_METRICS];c&&s.push(c)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,c)=>u.duration-c.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const o=a/s.length,f=Math.floor(t.length*.95),_=Math.floor(t.length*.99);return{avgResponseTime:Math.round(o),p95ResponseTime:Math.round(t[f]?.duration||0),p99ResponseTime:Math.round(t[_]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};E(w,"instance");let te=w;const Qe=te.getInstance(),Ae={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},J={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},je={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function Ze(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Je(i,s){return Ze(i).every(t=>t in s)}function Oe(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function ee(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function et(i,s){return s&&J[i]&&Je(J[i],s)?Oe(J[i],s):je[i]||n.errors_userFriendly_fallback_error()}function tt(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?Ae[e]:Ae.GENERAL}const st={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function it(i){return st[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var N=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(N||{});class q extends Error{constructor(e,t,r={},a){super(e);E(this,"code");E(this,"context");E(this,"recoverySuggestions");E(this,"userMessage");E(this,"isRecoverable");E(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return et(e,this.context)}getDefaultRecoverySuggestions(e){return it(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return tt(this.code)}formatMessage(e){return Oe(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const rt={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function re(i){const s=i.toLowerCase();for(const e of rt.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const at="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=pe.DEFAULT_ATTEMPTS,retryDelay:a=pe.BASE_DELAY,exponentialBackoff:l=!0,notify:o=!1,notifyOnRetry:f=!1,context:_={},onError:u,onRetry:c,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const C=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),C}catch(C){if(g=C,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:_}),u?.(g,d),d<=r&&R(g)){const h=l?a*Math.pow(2,d-1):a;f&&j.warning(n.agent_errorBoundary_retrying_message({seconds:h/1e3})),c?.(d),v.info(`[${e}] Retrying in ${h}ms`),await this.sleep(h)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=ee(g?.message||n.agent_errorBoundary_generic_error()),D=g?.message?.toLowerCase()||"",$=D.includes("no available models")||D.includes("all models exhausted")||D.includes("all models unavailable");throw o&&!$&&j.error(P),new q(P,N.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:_})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&j.error(ee(a.message)),new q(ee(a.message),N.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return re(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof q?[N.NETWORK_ERROR,N.STREAM_TIMEOUT,N.STREAM_CONNECTION_FAILED,N.PROVIDER_CONNECTION_FAILED,N.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new q(`${t} timed out after ${e}ms`,N.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,o=[],f=[];for(let _=0;_<s.length;_+=r){const u=s.slice(_,_+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")o.push(R.value);else{const d=R.reason;if(f.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return f.length>0&&v.warn(`[${l}] Completed with ${f.length} errors`),{results:o,errors:f}}};E(b,"instance");let se=b;const nt=se.getInstance(),ie=W("browser/index"),F=new Map,B=new Map;let U;function ot(i,s,e){for(const t of s)try{t(e)}catch(r){ie.error("Error in agent subscriber callback",{agentId:i,error:r})}}function ct(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Se.select(e,t);B.get(t)!==a&&(B.set(t,a),ot(t,r,a))}})}function lt(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ft(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),ct();const a=p.state,l=Se.select(a,i);return r&&B.set(i,l),l?ie.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):ie.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const o=F.get(i);o&&(o.delete(s),o.size===0&&(F.delete(i),B.delete(i))),lt()}}const y=W("ErrorRecovery"),ye={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||re(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class ut{constructor(){E(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class dt extends ut{constructor(){super(...arguments);E(this,"activeRecoveries",new Map);E(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=ye.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let o,f=t.initialBackoffMs,_=0;for(let u=1;u<=t.maxRetries;u++){if(_=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const c=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:c,attempts:u,totalTime:Date.now()-a}}catch(c){o=c,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:o.message});const R=o.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:o.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:o.message});break}if(re(o.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:o.message});break}if(!t.shouldRetry(o,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:o.message});break}if(u<t.maxRetries){const g=Math.random()*.2*f,d=Math.min(f+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:o.message}),await this.delay(d,l.signal),f=Math.min(f*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(o,_),this.emit("recovery:failure",{operationId:r,attempts:_,duration:Date.now()-a,error:o?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:o,attempts:_,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const o=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",o);const f=r;r=()=>{t.removeEventListener("abort",o),f()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const mt=new dt,O=new Ye({category:"WorkspaceMetrics"}),Et=100;class ft{constructor(){E(this,"metrics",new Map);E(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>Et;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const _t=new ft,M=W("AgentSend");function A(i){p.dispatch(i)}function Ie(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ht(i){const s=Ie(i)&&i.success===!0&&"data"in i?i.data:i;return!Ie(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(at)}async function kt(i,s,e,t={}){const r=ge.select(p.state,e.id);if(!r)return;const a=Le(i,e.id),l=t.submission,o=!!l&&we.select(p.state,l.scope)?.supported===!0,f=(c,R,g=!1)=>{l&&A(Xe(l.scope,l.id,c,Date.now(),R,g))};let _=!1;const u=()=>(!l||_||be.select(p.state,l))&&r===ge.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return Qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let c=await p.dispatch(Fe(e.id,i));if(u()){if(!c)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));c={...c,isStreaming:c.isStreaming??!1};{if(c&&(c.status==="pending"||!c.id)&&!c.backendSessionId&&c.activationState!==K.ACTIVE&&c.activationState!==K.ACTIVATING){const h=e.id.startsWith("optimistic-"),Y=e.worktreePath||e.repositoryPath||e.path;if(!h&&Y){M.info("Activating pending session in sendMessage",{agentId:i,status:c.status,activationState:c.activationState,hasBackendSessionId:!!c.backendSessionId});const x=await p.dispatch(ke(e.id,i));if(!u())return;x&&(c=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else c&&c.status==="pending"&&c.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:c.backendSessionId,activationState:c.activationState}),c={...c,status:Ge.Active,activationState:K.ACTIVE},A(me({...c,workspaceId:e.id})));if(!c)throw new Error(`Failed to get or create session for agent ${i}`);A(me({...c,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??ce(),k=t.messageMetadata?.[Re],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[Re]:k}:{}},D={id:Ee(ue()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};o||(l&&(f("rejected"),_=!0),A(Pe(c.id,D))),A(H(c.id,!0));let $=!1,C;try{o||await p.dispatch(xe(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=Ee(`msg_${ue()}`),Y=ce(),x=async()=>nt.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:c.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(m=>({type:m.type,mimeType:m.mimeType,dataLength:m.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(m=>({type:m.type,fileName:m.fileName,mimeType:m.mimeType,attachmentId:m.attachmentId,size:m.size}))||[]});const Me=t.model??t.modelId??c.model??void 0;A(Ve(i));const Ne=le(i,e.id),ne=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await qe("agent.sendMessage",{agentId:i,...o&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Me,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:Y,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(m=>{if(u())throw Ke(m)&&(C=m),m});if(u()){if(ht(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:c.id}),f("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const m=T.error,I=typeof m=="string"?m:m?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:c.id,queuedMessageId:T.queuedMessage?.id}),(!o||!l||!de.select(p.state,l))&&A(H(c.id,!1)),o||A(Ue(c.id,D.id)),o){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=fe(s,t),X=Q.select(p.state,i,e.id).find(oe=>oe.id===I.id||oe.turnId===L);A(_e(i,I.id,S,L,he(X??I,S),!X&&!!l&&de.select(p.state,l),ne))}f("accepted",I,!0),z(i,e.id);return}const m=T.queuedMessage;if(m){const I=T.turnId,G=typeof I=="string"?I:m.turnId;let L=m;if(u()&&le(i,e.id)===Ne){const S=Q.select(p.state,i,e.id),X=ze(S,m);A(Be(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:m.id}),await z(i,e.id).catch(()=>{}),L=Q.select(p.state,i,e.id).find(S=>S.id===m.id||S.turnId===G));if(u()&&typeof G=="string"){const S=fe(s,t);A(_e(i,m.id,S,G,he(L??m,S),!L,ne))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:m.id})}return}}o&&(f("accepted"),z(i,e.id),ve(i,e.id)),_t.incrementMessageSent(e.id)}},"send message",{retries:o?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),ae=o?await x().then(()=>({success:!0,error:void 0})):await mt.executeWithRecovery(x,ye.streaming,`send-message-${i}`);if(!ae.success)throw ae.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(H(c.id,!1)),!o&&t.messageMetadata&&A($e(c.id,D.id,{metadata:P})),o&&f($||C?"rejected":"uncertain"),C??h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Te as U,Ft as a,ee as c,ze as r,kt as s,Ke as u,bt as w};
1
+ var De=Object.defineProperty;var Ce=(i,s,e)=>s in i?De(i,s,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[s]=e;var E=(i,s,e)=>Ce(i,typeof s!="symbol"?s+"":s,e);import{K as Le,P as ce,a6 as le,as as z,aC as ve}from"./COJ7FcW0.js";import{b_ as we,c$ as ue,cr as de,cq as be}from"./B4kHSLJr.js";import{JH as p,Cg as Fe,bJ as ke,i as Ge,LM as me,ir as Ee,bV as Pe,Ec as H,CF as xe,fl as Ve,AL as Ue,e3 as fe,fh as _e,e2 as he,Be,Lq as $e,wy as Xe}from"./CiKoEJ2m.js";import{aO as Se,dX as ge,A as K,P as Re,aK as Q}from"./iQDlfKDR.js";import{h as qe}from"./CT8vPg_p.js";import{c as W}from"./ChTqQfQN.js";import{a as We}from"./BdWqymET.js";import{m as j}from"./C3jMXj_V.js";import"./3SdAC2_C.js";import{bm as n}from"./CtfEuoOH.js";import"./B26ZHg3s.js";import"./CGmYraIa.js";import"./BFfRQORP.js";import{R as pe}from"./B5aYN90J.js";import{L as Ye}from"./CSiaiLHL.js";function ze(i,s){return i.some(e=>e.id===s.id)?i.map(e=>e.id===s.id?{...s,...s.author==null&&e.author!==void 0?{author:e.author}:{}}:e):[...i,s]}const Te="confirmUnslothModelSwitch";function He(i){if(!i||typeof i!="object")return!1;const{agentId:s,agentName:e,workspaceId:t,workspaceTitle:r}=i;return typeof s=="string"&&typeof e=="string"&&typeof t=="string"&&(r===null||typeof r=="string")}function Ke(i){for(let s=i,e=0;s&&e<4;e++){const t=s.data;if(t&&typeof t=="object"){const{code:r,currentModel:a,requestedModel:l,agents:o}=t;if(r==="unsloth-model-switch-confirmation-required"&&typeof a=="string"&&typeof l=="string"&&Array.isArray(o)&&o.every(He))return{currentModel:a,requestedModel:l,agents:o}}s=s.cause}}function bt(i){if(!i||!(Te in i))return i;const{[Te]:s,...e}=i;return Object.keys(e).length>0?e:void 0}const Z=typeof performance<"u"?performance:{now:()=>Date.now()},V=new We("PerformanceOptimizer"),w=class w{constructor(){E(this,"metricsBuffer");E(this,"metricsIndex",0);E(this,"metricsCount",0);E(this,"MAX_METRICS",500);E(this,"TARGET_RESPONSE_TIME",100);E(this,"memoCache",new Map);E(this,"MEMO_TTL",6e4);E(this,"MAX_CACHE_SIZE",100);E(this,"cacheHits",0);E(this,"cacheMisses",0);E(this,"pendingRequests",new Map);E(this,"requestQueue",[]);E(this,"cleanupInterval",null);this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.startCacheCleanup(),V.info("PerformanceOptimizer initialized")}static getInstance(){return w.instance||(w.instance=new w),w.instance}reset(){this.metricsBuffer=new Array(this.MAX_METRICS).fill(null),this.metricsIndex=0,this.metricsCount=0,this.memoCache.clear(),this.pendingRequests.clear(),this.requestQueue=[],this.cacheHits=0,this.cacheMisses=0}clearCache(){this.memoCache.clear(),this.cacheHits=0,this.cacheMisses=0}async processBatch(s,e,t={}){const{batchSize:r=10,concurrency:a=4}=t,l=[];for(let o=0;o<s.length;o+=r){const _=s.slice(o,o+r).map((c,R)=>{const g=Math.floor(R/a)*10;return new Promise(d=>{setTimeout(async()=>{const k=await e(c);d(k)},g)})}),u=await Promise.all(_);l.push(...u)}return l}startCacheCleanup(){this.cleanupInterval=setInterval(()=>{this.cleanupCache()},3e4)}stopCacheCleanup(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null)}cleanupCache(){const s=Date.now(),e=[];this.memoCache.forEach((t,r)=>{s-t.timestamp>this.MEMO_TTL&&e.push(r)}),e.forEach(t=>this.memoCache.delete(t)),this.memoCache.size>this.MAX_CACHE_SIZE&&Array.from(this.memoCache.entries()).sort((a,l)=>a[1].hits-l[1].hits||a[1].timestamp-l[1].timestamp).slice(0,this.memoCache.size-this.MAX_CACHE_SIZE).forEach(([a])=>this.memoCache.delete(a))}async track(s,e,t={}){const r=Z.now();try{const a=t.cacheKey||s;if(t.memoize){const _=this.getMemoized(a);if(_!==void 0)return this.cacheHits++,V.debug("Memoized result used",{operation:s,cacheKey:a,hits:this.cacheHits}),_;this.cacheMisses++}if(t.coalesce){const _=this.pendingRequests.get(s);if(_)return V.debug("Request coalesced",{operation:s}),_}let l;t.coalesce?(l=t.timeout?this.withTimeout(e(),t.timeout):e(),this.pendingRequests.set(s,l)):l=t.timeout?this.withTimeout(e(),t.timeout):e();const o=await l;t.memoize&&this.memoize(a,o);const f=Z.now()-r;return this.recordMetric(s,f,!0,{strategy:t.priority||"normal",memoized:t.memoize||!1,coalesced:t.coalesce||!1}),f>this.TARGET_RESPONSE_TIME&&V.warn("Operation exceeded target time",{operation:s,duration:Math.round(f),target:this.TARGET_RESPONSE_TIME}),o}catch(a){const l=Z.now()-r;throw this.recordMetric(s,l,!1,{error:a instanceof Error?a.message:"Unknown error"}),a}finally{t.coalesce&&this.pendingRequests.delete(s)}}getStats(){if(this.metricsCount===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const s=[],e=this.metricsCount<this.MAX_METRICS?0:this.metricsIndex;for(let u=0;u<this.metricsCount;u++){const c=this.metricsBuffer[(e+u)%this.MAX_METRICS];c&&s.push(c)}if(s.length===0)return{avgResponseTime:0,p95ResponseTime:0,p99ResponseTime:0,successRate:100,slowOperations:[]};const t=s.sort((u,c)=>u.duration-c.duration);let r=0,a=0;const l=new Set;for(const u of s)a+=u.duration,u.success&&r++,u.duration>this.TARGET_RESPONSE_TIME&&l.add(u.operation);const o=a/s.length,f=Math.floor(t.length*.95),_=Math.floor(t.length*.99);return{avgResponseTime:Math.round(o),p95ResponseTime:Math.round(t[f]?.duration||0),p99ResponseTime:Math.round(t[_]?.duration||0),successRate:r/s.length*100,slowOperations:Array.from(l)}}getCacheStats(){const s=this.cacheHits+this.cacheMisses;return{size:this.memoCache.size,hitRate:s>0?this.cacheHits/s*100:0,hits:this.cacheHits,misses:this.cacheMisses}}getMemoized(s){const e=this.memoCache.get(s);if(e){if(Date.now()-e.timestamp>this.MEMO_TTL){this.memoCache.delete(s);return}return e.hits++,e.value}}memoize(s,e){const t=JSON.stringify(e).length;this.memoCache.set(s,{value:e,timestamp:Date.now(),hits:0,size:t}),this.memoCache.size>this.MAX_CACHE_SIZE&&this.cleanupCache()}async withTimeout(s,e){return Promise.race([s,new Promise((t,r)=>setTimeout(()=>r(new Error(`Operation timed out after ${e}ms`)),e))])}recordMetric(s,e,t,r){this.metricsBuffer[this.metricsIndex]={operation:s,duration:e,timestamp:Date.now(),success:t,metadata:r},this.metricsIndex=(this.metricsIndex+1)%this.MAX_METRICS,this.metricsCount<this.MAX_METRICS&&this.metricsCount++,e>this.TARGET_RESPONSE_TIME&&V.warn("Slow operation detected",{operation:s,duration:`${e.toFixed(2)}ms`,target:`${this.TARGET_RESPONSE_TIME}ms`,metadata:r})}};E(w,"instance");let te=w;const Qe=te.getInstance(),Ae={AGENT_CREATION:"https://docs.example.com/agent-creation",STREAMING:"https://docs.example.com/streaming-issues",STORAGE:"https://docs.example.com/storage-troubleshooting",MEMORY:"https://docs.example.com/memory-management",PROVIDER:"https://docs.example.com/provider-setup",GENERAL:"https://docs.example.com/help"},J={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_template({agentName:"{agentName}",details:"{details}"})},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_template({agentName:"{agentName}"})},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_template({details:"{details}"})},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_template({details:"{details}"})},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_template({sessionId:"{sessionId}"})},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_template()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_template({details:"{details}"})},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_template({details:"{details}"})},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_template({timeout:"{timeout}"})},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_template({attempt:"{attempt}",maxAttempts:"{maxAttempts}"})},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_template({attempts:"{attempts}"})},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_template({details:"{details}"})},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_template({details:"{details}"})},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_template({maxLength:"{maxLength}",currentLength:"{currentLength}"})},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_template({provider:"{provider}"})},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_template({provider:"{provider}",details:"{details}"})},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_template({provider:"{provider}"})},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_template({details:"{details}"})},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_template({details:"{details}"})},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_template({lastBackup:"{lastBackup}"})},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_template({currentUsage:"{currentUsage}",limit:"{limit}"})},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_template({count:"{count}",window:"{window}"})},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_template({current:"{current}",max:"{max}"})}},je={get AGENT_CREATION_FAILED(){return n.errors_catalog_agentCreationFailed_friendly()},get AGENT_ALREADY_EXISTS(){return n.errors_catalog_agentAlreadyExists_friendly()},get INVALID_AGENT_CONFIG(){return n.errors_catalog_invalidAgentConfig_friendly()},get INVALID_CONFIG(){return n.errors_catalog_invalidConfig_friendly()},get SESSION_NOT_FOUND(){return n.errors_catalog_sessionNotFound_friendly()},get SESSION_ALREADY_ACTIVE(){return n.errors_catalog_sessionAlreadyActive_friendly()},get SESSION_INITIALIZATION_FAILED(){return n.errors_catalog_sessionInitializationFailed_friendly()},get STREAM_CONNECTION_FAILED(){return n.errors_catalog_streamConnectionFailed_friendly()},get STREAM_TIMEOUT(){return n.errors_catalog_streamTimeout_friendly()},get STREAM_INTERRUPTED(){return n.errors_catalog_streamInterrupted_friendly()},get STREAM_RECOVERY_FAILED(){return n.errors_catalog_streamRecoveryFailed_friendly()},get MESSAGE_SEND_FAILED(){return n.errors_catalog_messageSendFailed_friendly()},get MESSAGE_VALIDATION_FAILED(){return n.errors_catalog_messageValidationFailed_friendly()},get MESSAGE_TOO_LONG(){return n.errors_catalog_messageTooLong_friendly()},get PROVIDER_NOT_FOUND(){return n.errors_catalog_providerNotFound_friendly()},get PROVIDER_CONNECTION_FAILED(){return n.errors_catalog_providerConnectionFailed_friendly()},get PROVIDER_PROCESS_DIED(){return n.errors_catalog_providerProcessDied_friendly()},get STORAGE_READ_FAILED(){return n.errors_catalog_storageReadFailed_friendly()},get STORAGE_WRITE_FAILED(){return n.errors_catalog_storageWriteFailed_friendly()},get STORAGE_CORRUPTED(){return n.errors_catalog_storageCorrupted_friendly()},get MEMORY_LIMIT_EXCEEDED(){return n.errors_catalog_memoryLimitExceeded_friendly()},get RATE_LIMIT_EXCEEDED(){return n.errors_catalog_rateLimitExceeded_friendly()},get CONCURRENT_LIMIT_EXCEEDED(){return n.errors_catalog_concurrentLimitExceeded_friendly()}};function Ze(i){return(i.match(/{(\w+)}/g)||[]).map(e=>e.slice(1,-1))}function Je(i,s){return Ze(i).every(t=>t in s)}function Oe(i,s={}){return i.replace(/{(\w+)}/g,(e,t)=>String(s[t]??e))}function ee(i){const s=n.errors_cleanMessage_fallback_error();if(!i)return s;let e=i;return e=e.replace(/^.*?failed(?:\s+to\s+.*?)?\s+after\s+\d+\s+attempts:\s*/i,""),e=e.replace(/^Error invoking remote method '[^']+':(\s*Error:)?\s*/i,""),e=e.replace(/^(Error:\s*)+/i,""),e=e.replace(/\n\s*at .+/g,""),e=e.replace(/\s+/g," ").trim(),e||s}function et(i,s){return s&&J[i]&&Je(J[i],s)?Oe(J[i],s):je[i]||n.errors_userFriendly_fallback_error()}function tt(i){const e={AGENT_CREATION_FAILED:"AGENT_CREATION",AGENT_ALREADY_EXISTS:"AGENT_CREATION",INVALID_AGENT_CONFIG:"AGENT_CREATION",STREAM_CONNECTION_FAILED:"STREAMING",STREAM_TIMEOUT:"STREAMING",STREAM_INTERRUPTED:"STREAMING",STREAM_RECOVERY_FAILED:"STREAMING",STORAGE_READ_FAILED:"STORAGE",STORAGE_WRITE_FAILED:"STORAGE",STORAGE_CORRUPTED:"STORAGE",MEMORY_LIMIT_EXCEEDED:"MEMORY",RATE_LIMIT_EXCEEDED:"MEMORY",CONCURRENT_LIMIT_EXCEEDED:"MEMORY",PROVIDER_NOT_FOUND:"PROVIDER",PROVIDER_CONNECTION_FAILED:"PROVIDER",PROVIDER_PROCESS_DIED:"PROVIDER"}[i];return e?Ae[e]:Ae.GENERAL}const st={AGENT_CREATION_FAILED:[{action:"retry",description:"Try creating the agent again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify agent configuration in settings",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient memory and disk space",automatic:!1,priority:"medium"}],AGENT_ALREADY_EXISTS:[{action:"rename",description:"Choose a different name for the agent",automatic:!1,priority:"high"},{action:"delete-existing",description:"Delete the existing agent first",automatic:!1,priority:"medium"}],INVALID_AGENT_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],INVALID_CONFIG:[{action:"review-config",description:"Review and correct the configuration",automatic:!1,priority:"high"},{action:"use-defaults",description:"Reset to default configuration",automatic:!1,priority:"medium"}],SESSION_NOT_FOUND:[{action:"start-new",description:"Start a new agent session",automatic:!1,priority:"high"},{action:"check-history",description:"Check session history for recent sessions",automatic:!1,priority:"medium"}],SESSION_ALREADY_ACTIVE:[{action:"wait",description:"Wait for the current session to complete",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel the active session first",automatic:!1,priority:"high"}],SESSION_INITIALIZATION_FAILED:[{action:"retry",description:"Try initializing the session again",automatic:!1,priority:"high"},{action:"check-resources",description:"Ensure sufficient resources are available",automatic:!1,priority:"medium"}],MESSAGE_SEND_FAILED:[{action:"retry",description:"Try sending the message again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],MESSAGE_VALIDATION_FAILED:[{action:"review-config",description:"Review and correct the message format",automatic:!1,priority:"high"},{action:"check-config",description:"Check configuration for valid message format",automatic:!1,priority:"medium"}],MESSAGE_TOO_LONG:[{action:"retry",description:"Shorten the message and try again",automatic:!1,priority:"high"},{action:"batch",description:"Split the message into multiple parts",automatic:!1,priority:"medium"}],PROVIDER_NOT_FOUND:[{action:"check-config",description:"Verify provider is properly configured",automatic:!1,priority:"high"},{action:"recreate",description:"Install or reinstall the provider",automatic:!1,priority:"high"}],PROVIDER_CONNECTION_FAILED:[{action:"retry",description:"Try connecting to the provider again",automatic:!1,priority:"high"},{action:"check-config",description:"Verify provider configuration",automatic:!1,priority:"high"}],STORAGE_READ_FAILED:[{action:"retry",description:"Try reading the data again",automatic:!1,priority:"high"},{action:"restore",description:"Restore from a recent backup",automatic:!1,priority:"medium"}],STORAGE_WRITE_FAILED:[{action:"retry",description:"Try saving again",automatic:!1,priority:"high"},{action:"check-resources",description:"Check available disk space",automatic:!1,priority:"high"}],STREAM_CONNECTION_FAILED:[{action:"retry",description:"Try connecting again",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your network connection",automatic:!1,priority:"high"}],STREAM_RECOVERY_FAILED:[{action:"restart",description:"Restart the agent",automatic:!1,priority:"high"},{action:"check-config",description:"Check error logs for more details",automatic:!1,priority:"medium"}],STREAM_INTERRUPTED:[{action:"reconnect",description:"Attempting automatic reconnection",automatic:!0,priority:"high"},{action:"retry",description:"Retry sending the message",automatic:!1,priority:"high"},{action:"check-connection",description:"Check your internet connection",automatic:!1,priority:"medium"}],STREAM_TIMEOUT:[{action:"wait",description:"Wait for agent to complete processing",automatic:!1,priority:"high"},{action:"cancel",description:"Cancel current operation",automatic:!1,priority:"medium"},{action:"increase-timeout",description:"Increase timeout in settings",automatic:!1,priority:"low"}],PROVIDER_PROCESS_DIED:[{action:"restart",description:"Restart agent process",automatic:!0,priority:"high"},{action:"recreate",description:"Create new agent session",automatic:!1,priority:"high"}],STORAGE_CORRUPTED:[{action:"restore",description:"Restore from backup",automatic:!1,priority:"high"},{action:"reset",description:"Reset agent data",automatic:!1,priority:"medium"}],MEMORY_LIMIT_EXCEEDED:[{action:"cleanup",description:"Close unused agents",automatic:!1,priority:"high"},{action:"increase-limit",description:"Increase memory limit in settings",automatic:!1,priority:"medium"}],RATE_LIMIT_EXCEEDED:[{action:"wait",description:"Wait before making more requests",automatic:!1,priority:"high"},{action:"batch",description:"Batch requests together",automatic:!1,priority:"medium"}],CONCURRENT_LIMIT_EXCEEDED:[{action:"close-agents",description:"Close some running agents",automatic:!1,priority:"high"},{action:"queue",description:"Queue operation for later",automatic:!1,priority:"medium"}]};function it(i){return st[i]||[{action:"retry",description:"Try the operation again",automatic:!1,priority:"high"}]}var N=(i=>(i.AGENT_CREATION_FAILED="AGENT_CREATION_FAILED",i.AGENT_ALREADY_EXISTS="AGENT_ALREADY_EXISTS",i.INVALID_AGENT_CONFIG="INVALID_AGENT_CONFIG",i.INVALID_CONFIG="INVALID_CONFIG",i.SESSION_NOT_FOUND="SESSION_NOT_FOUND",i.SESSION_ALREADY_ACTIVE="SESSION_ALREADY_ACTIVE",i.SESSION_INITIALIZATION_FAILED="SESSION_INITIALIZATION_FAILED",i.STREAM_CONNECTION_FAILED="STREAM_CONNECTION_FAILED",i.STREAM_TIMEOUT="STREAM_TIMEOUT",i.STREAM_INTERRUPTED="STREAM_INTERRUPTED",i.STREAM_RECOVERY_FAILED="STREAM_RECOVERY_FAILED",i.MESSAGE_SEND_FAILED="MESSAGE_SEND_FAILED",i.MESSAGE_VALIDATION_FAILED="MESSAGE_VALIDATION_FAILED",i.MESSAGE_TOO_LONG="MESSAGE_TOO_LONG",i.PROVIDER_NOT_FOUND="PROVIDER_NOT_FOUND",i.PROVIDER_CONNECTION_FAILED="PROVIDER_CONNECTION_FAILED",i.PROVIDER_PROCESS_DIED="PROVIDER_PROCESS_DIED",i.PROVIDER_UNAVAILABLE="PROVIDER_UNAVAILABLE",i.PROVIDER_ERROR="PROVIDER_ERROR",i.STORAGE_READ_FAILED="STORAGE_READ_FAILED",i.STORAGE_WRITE_FAILED="STORAGE_WRITE_FAILED",i.STORAGE_CORRUPTED="STORAGE_CORRUPTED",i.STORAGE_ERROR="STORAGE_ERROR",i.STORAGE_QUOTA_EXCEEDED="STORAGE_QUOTA_EXCEEDED",i.MEMORY_LIMIT_EXCEEDED="MEMORY_LIMIT_EXCEEDED",i.RATE_LIMIT_EXCEEDED="RATE_LIMIT_EXCEEDED",i.CONCURRENT_LIMIT_EXCEEDED="CONCURRENT_LIMIT_EXCEEDED",i.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",i.RESOURCE_EXHAUSTED="RESOURCE_EXHAUSTED",i.NETWORK_ERROR="NETWORK_ERROR",i.PERMISSION_DENIED="PERMISSION_DENIED",i.OPERATION_FAILED="OPERATION_FAILED",i.VALIDATION_ERROR="VALIDATION_ERROR",i.INVALID_RESPONSE="INVALID_RESPONSE",i.STATE_CORRUPTION="STATE_CORRUPTION",i.CONTEXT_OVERFLOW="CONTEXT_OVERFLOW",i))(N||{});class q extends Error{constructor(e,t,r={},a){super(e);E(this,"code");E(this,"context");E(this,"recoverySuggestions");E(this,"userMessage");E(this,"isRecoverable");E(this,"cause");this.name="AgentError",this.code=t,this.context={...r,timestamp:new Date,stackTrace:this.stack},this.userMessage=a?.userMessage||this.getDefaultUserMessage(t),this.recoverySuggestions=a?.recoverySuggestions||this.getDefaultRecoverySuggestions(t),this.isRecoverable=a?.isRecoverable??this.isErrorRecoverable(t),a?.cause&&(this.cause=a.cause)}getDefaultUserMessage(e){return et(e,this.context)}getDefaultRecoverySuggestions(e){return it(e)}isErrorRecoverable(e){return["STREAM_INTERRUPTED","STREAM_TIMEOUT","MESSAGE_SEND_FAILED","PROVIDER_PROCESS_DIED","STORAGE_READ_FAILED","STORAGE_WRITE_FAILED"].includes(e)}getHelpLink(){return tt(this.code)}formatMessage(e){return Oe(e,this.context)}toJSON(){return{name:this.name,code:this.code,message:this.message,userMessage:this.userMessage,context:this.context,recoverySuggestions:this.recoverySuggestions,isRecoverable:this.isRecoverable,helpLink:this.getHelpLink(),stack:this.stack}}}const rt={NON_RETRYABLE_ERRORS:["EACCES","EPERM","ENOSPC","EMFILE","permission","memory","fatal","process died","not available on your current plan","agent binary","rate limit","too many requests","hit your limit","you've hit your limit","quota exceeded"]};function re(i){const s=i.toLowerCase();for(const e of rt.NON_RETRYABLE_ERRORS)if(s.includes(e.toLowerCase()))return!0;return!1}const at="Agent already has an in-flight prompt. Message was not delivered.",v=W("ErrorBoundary"),b=class b{constructor(){}static getInstance(){return b.instance||(b.instance=new b),b.instance}async wrap(s,e,t={}){const{retries:r=pe.DEFAULT_ATTEMPTS,retryDelay:a=pe.BASE_DELAY,exponentialBackoff:l=!0,notify:o=!1,notifyOnRetry:f=!1,context:_={},onError:u,onRetry:c,shouldRetry:R=this.defaultShouldRetry}=t;let g=null,d=0;for(d=1;d<=r+1;d++)try{v.debug(`[${e}] Attempt ${d}/${r+1}`);const C=await s();return d>1&&v.info(`[${e}] Succeeded after ${d} attempts`),C}catch(C){if(g=C,v.error(`[${e}] Attempt ${d} failed`,{error:g.message,attempt:d,maxAttempts:r+1,context:_}),u?.(g,d),d<=r&&R(g)){const h=l?a*Math.pow(2,d-1):a;f&&j.warning(n.agent_errorBoundary_retrying_message({seconds:h/1e3})),c?.(d),v.info(`[${e}] Retrying in ${h}ms`),await this.sleep(h)}else break}const k=`${e} failed after ${d} attempt${d===1?"":"s"}: ${g?.message}`,P=ee(g?.message||n.agent_errorBoundary_generic_error()),D=g?.message?.toLowerCase()||"",$=D.includes("no available models")||D.includes("all models exhausted")||D.includes("all models unavailable");throw o&&!$&&j.error(P),new q(P,N.OPERATION_FAILED,{originalError:g?.message,detailedMessage:k,attempts:d,context:_})}async wrapVoid(s,e,t={}){await this.wrap(s,e,t)}wrapSync(s,e,t={}){try{return s()}catch(r){const a=r;throw v.error(`[${e}] Failed`,{error:a.message,context:t.context}),t.notify&&j.error(ee(a.message)),new q(ee(a.message),N.OPERATION_FAILED,t.context)}}defaultShouldRetry(s){const e=s.message.toLowerCase();return re(s.message)?!1:e.includes("network")||e.includes("timeout")?!0:s instanceof q?[N.NETWORK_ERROR,N.STREAM_TIMEOUT,N.STREAM_CONNECTION_FAILED,N.PROVIDER_CONNECTION_FAILED,N.PROVIDER_UNAVAILABLE].includes(s.code):!(e.includes("invalid")||e.includes("interrupted")||e.includes("cancel")||e.includes("not found")||e.includes("not available")||e.includes("404")||e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||e.includes("413")||e.includes("too long for the agent")||e.includes("request entity too large")||e.includes("payload too large")||e.includes("content too large")||e.includes("body too large")||e.includes("unauthorized")||e.includes("forbidden")||e.includes("401")||e.includes("403"))}sleep(s){return new Promise(e=>setTimeout(e,s))}async withTimeout(s,e,t){return Promise.race([s(),new Promise((r,a)=>setTimeout(()=>a(new q(`${t} timed out after ${e}ms`,N.STREAM_TIMEOUT)),e))])}async batchOperations(s,e,t={}){const{concurrency:r=5,continueOnError:a=!0,operationName:l="batch operation"}=t,o=[],f=[];for(let _=0;_<s.length;_+=r){const u=s.slice(_,_+r);(await Promise.allSettled(u.map(R=>e(R)))).forEach((R,g)=>{if(R.status==="fulfilled")o.push(R.value);else{const d=R.reason;if(f.push({item:u[g],error:d}),v.error(`[${l}] Batch item failed`,{item:u[g],error:d.message}),!a)throw d}})}return f.length>0&&v.warn(`[${l}] Completed with ${f.length} errors`),{results:o,errors:f}}};E(b,"instance");let se=b;const nt=se.getInstance(),ie=W("browser/index"),F=new Map,B=new Map;let U;function ot(i,s,e){for(const t of s)try{t(e)}catch(r){ie.error("Error in agent subscriber callback",{agentId:i,error:r})}}function ct(){if(U)return;let i=!1;U=p.createSelector(e=>e.agentSessions)().subscribe(()=>{if(!i){i=!0;return}if(F.size===0)return;const e=p.state;for(const[t,r]of F){const a=Se.select(e,t);B.get(t)!==a&&(B.set(t,a),ot(t,r,a))}})}function lt(){F.size>0||!U||(U(),U=void 0,B.clear())}function Ft(i,s,e){let t=F.get(i);const r=!t;t||(t=new Set,F.set(i,t)),t.add(s),ct();const a=p.state,l=Se.select(a,i);return r&&B.set(i,l),l?ie.debug("[subscribeToAgent] Initial callback data",{agentId:i,workspaceId:e??"current",hasSession:!0}):ie.debug("[subscribeToAgent] No session found",{agentId:i,workspaceId:e??"current"}),s(l),()=>{const o=F.get(i);o&&(o.delete(s),o.size===0&&(F.delete(i),B.delete(i))),lt()}}const y=W("ErrorRecovery"),ye={network:{maxRetries:3,initialBackoffMs:1e3,maxBackoffMs:1e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("network")||s.includes("fetch")||s.includes("connection")||s.includes("timeout")}},streaming:{maxRetries:5,initialBackoffMs:500,maxBackoffMs:5e3,backoffMultiplier:1.5,shouldRetry:(i,s)=>{if(s>=5)return!1;const e=i.message.toLowerCase();return e.includes("no available models")||e.includes("all models exhausted")||e.includes("all models unavailable")||re(i.message)?!1:e.includes("stream")||e.includes("chunk")||e.includes("incomplete")}},persistence:{maxRetries:2,initialBackoffMs:100,maxBackoffMs:1e3,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("save")||s.includes("write")||s.includes("persist")}},rateLimit:{maxRetries:3,initialBackoffMs:5e3,maxBackoffMs:3e4,backoffMultiplier:2,shouldRetry:i=>{const s=i.message.toLowerCase();return s.includes("rate")||s.includes("limit")||s.includes("429")}}};class ut{constructor(){E(this,"listeners",new Map)}on(s,e){let t=this.listeners.get(s);t||(t=new Set,this.listeners.set(s,t)),t.add(e)}off(s,e){this.listeners.get(s)?.delete(e)}emit(s,...e){this.listeners.get(s)?.forEach(t=>{try{t(...e)}catch(r){y.error(`Error in event listener for ${s}:`,r)}})}removeAllListeners(){this.listeners.clear()}}class dt extends ut{constructor(){super(...arguments);E(this,"activeRecoveries",new Map);E(this,"recoveryStats",new Map)}async executeWithRecovery(e,t=ye.network,r){const a=Date.now(),l=new AbortController;r&&(this.cancelRecovery(r),this.activeRecoveries.set(r,l));let o,f=t.initialBackoffMs,_=0;for(let u=1;u<=t.maxRetries;u++){if(_=u,l.signal.aborted){y.info(`Recovery cancelled for operation ${r}`);break}try{y.debug(`Attempting operation (attempt ${u}/${t.maxRetries})`,{operationId:r});const c=await e();return this.updateStats(r,!0),this.emit("recovery:success",{operationId:r,attempt:u,duration:Date.now()-a}),r&&this.activeRecoveries.delete(r),{success:!0,data:c,attempts:u,totalTime:Date.now()-a}}catch(c){o=c,y.warn(`Operation failed (attempt ${u}/${t.maxRetries})`,{operationId:r,error:o.message});const R=o.message.toLowerCase();if(R.includes("interrupted")||R.includes("cancelled")||R.includes("canceled")){y.debug("User-initiated interruption/cancellation, not retrying",{operationId:r,error:o.message});break}if(R.includes("no available models")||R.includes("all models exhausted")||R.includes("all models unavailable")){y.debug("All models exhausted, not retrying",{operationId:r,error:o.message});break}if(re(o.message)){y.debug("Fatal error detected, not retrying",{operationId:r,error:o.message});break}if(!t.shouldRetry(o,u)){y.debug("Error not retryable, stopping recovery",{operationId:r,error:o.message});break}if(u<t.maxRetries){const g=Math.random()*.2*f,d=Math.min(f+g,t.maxBackoffMs);t.onRetry?.(u,d),this.emit("recovery:retry",{operationId:r,attempt:u,delay:d,error:o.message}),await this.delay(d,l.signal),f=Math.min(f*t.backoffMultiplier,t.maxBackoffMs)}}}return this.updateStats(r,!1),t.onFailure?.(o,_),this.emit("recovery:failure",{operationId:r,attempts:_,duration:Date.now()-a,error:o?.message}),r&&this.activeRecoveries.delete(r),{success:!1,error:o,attempts:_,totalTime:Date.now()-a}}cancelRecovery(e){const t=this.activeRecoveries.get(e);t&&(t.abort(),this.activeRecoveries.delete(e),y.info(`Cancelled recovery for operation ${e}`))}cancelAllRecoveries(){for(const[e,t]of this.activeRecoveries)t.abort(),y.info(`Cancelled recovery for operation ${e}`);this.activeRecoveries.clear()}getStats(e){if(e)return this.recoveryStats.get(e)||{successes:0,failures:0};const t={};for(const[r,a]of this.recoveryStats)t[r]=a;return t}clearStats(e){e?this.recoveryStats.delete(e):this.recoveryStats.clear()}isRetryable(e,t){const r=e.message.toLowerCase();if(t)switch(t){case"NETWORK":return r.includes("network")||r.includes("fetch");case"TIMEOUT":return r.includes("timeout")||r.includes("timed out");case"RATE_LIMIT":return r.includes("rate")||r.includes("limit")||r.includes("429");case"TEMPORARY":return r.includes("temporary")||r.includes("transient");case"CONFLICT":return r.includes("conflict")||r.includes("concurrent");default:return!1}return this.isRetryable(e,"NETWORK")||this.isRetryable(e,"TIMEOUT")||this.isRetryable(e,"RATE_LIMIT")||this.isRetryable(e,"TEMPORARY")||this.isRetryable(e,"CONFLICT")}delay(e,t){return new Promise((r,a)=>{const l=setTimeout(r,e);if(t){const o=()=>{clearTimeout(l),a(new Error("Delay aborted"))};t.addEventListener("abort",o);const f=r;r=()=>{t.removeEventListener("abort",o),f()}}})}updateStats(e,t){if(!e)return;const r=this.recoveryStats.get(e)||{successes:0,failures:0};t?r.successes++:r.failures++,this.recoveryStats.set(e,r)}dispose(){this.cancelAllRecoveries(),this.recoveryStats.clear(),this.removeAllListeners()}}const mt=new dt,O=new Ye({category:"WorkspaceMetrics"}),Et=100;class ft{constructor(){E(this,"metrics",new Map);E(this,"operations",new Map)}startWorkspaceCreation(s){const e=Date.now();for(this.metrics.delete(s),this.metrics.set(s,{workspaceId:s,creationStarted:e});this.metrics.size>Et;){const t=this.metrics.keys().next().value;if(t===void 0)break;this.metrics.delete(t)}O.info("Started tracking workspace creation",{workspaceId:s})}recordMilestone(s,e){const t=this.metrics.get(s);if(!t){O.warn("No metrics found for workspace",{workspaceId:s,milestone:e});return}const r=Date.now();switch(e){case"optimisticNavigation":t.optimisticNavigation=r;break;case"realWorkspaceCreated":t.realWorkspaceCreated=r;break;case"agentCreated":t.agentCreated=r;break;case"agentReady":t.agentReady=r;break;case"firstMessageSent":t.firstMessageSent=r;break;case"firstResponseReceived":t.firstResponseReceived=r;break;case"firstChunkReceived":t.firstChunkReceived=r;break;case"totalDuration":t.totalDuration=r;break;case"workspaceId":case"creationStarted":O.warn("Cannot update milestone",{milestone:e});return}const a=r-t.creationStarted;O.info(`Milestone: ${e}`,{workspaceId:s,elapsed:`${a}ms`,timestamp:r}),e==="firstResponseReceived"&&(t.totalDuration=r-t.creationStarted,this.logSummary(s))}startOperation(s,e){this.operations.set(s,{startTime:Date.now(),metadata:e})}endOperation(s,e){const t=this.operations.get(s);if(!t)return O.warn("Operation not found",{operationId:s}),null;const r=Date.now();return t.endTime=r,t.duration=r-t.startTime,e&&(t.metadata={...t.metadata,...e}),O.info("Operation completed",{operationId:s,duration:`${t.duration}ms`,metadata:t.metadata}),this.operations.delete(s),t.duration}getMetrics(s){return this.metrics.get(s)}logSummary(s){const e=this.metrics.get(s);if(!e)return;const t={workspaceId:s,totalDuration:`${e.totalDuration}ms`,stages:{optimisticNavigation:e.optimisticNavigation?`${e.optimisticNavigation-e.creationStarted}ms`:"N/A",realWorkspaceCreation:e.realWorkspaceCreated?`${e.realWorkspaceCreated-e.creationStarted}ms`:"N/A",agentCreation:e.agentCreated?`${e.agentCreated-e.creationStarted}ms`:"N/A",agentReady:e.agentReady?`${e.agentReady-e.creationStarted}ms`:"N/A",firstMessage:e.firstMessageSent?`${e.firstMessageSent-e.creationStarted}ms`:"N/A",firstResponse:e.firstResponseReceived?`${e.firstResponseReceived-e.creationStarted}ms`:"N/A"}};O.info("=== Workspace Creation Metrics Summary ===",t),O.info("Workspace Creation Metrics:",t)}clearMetrics(s){this.metrics.delete(s)}incrementAgentCreated(s){const e=this.metrics.get(s);e&&(e.agentCreated=Date.now(),O.info("Agent created",{workspaceId:s}))}incrementMessageSent(s){const e=this.metrics.get(s);e&&!e.firstMessageSent&&(e.firstMessageSent=Date.now(),O.info("First message sent",{workspaceId:s}))}}const _t=new ft,M=W("AgentSend");function A(i){p.dispatch(i)}function Ie(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function ht(i){const s=Ie(i)&&i.success===!0&&"data"in i?i.data:i;return!Ie(s)||s.success!==!1?!1:typeof s.error=="string"&&s.error.includes(at)}async function kt(i,s,e,t={}){const r=ge.select(p.state,e.id);if(!r)return;const a=Le(i,e.id),l=t.submission,o=!!l&&we.select(p.state,l.scope)?.supported===!0,f=(c,R,g=!1)=>{l&&A(Xe(l.scope,l.id,c,Date.now(),R,g))};let _=!1;const u=()=>(!l||_||be.select(p.state,l))&&r===ge.select(p.state,e.id)&&a.isCurrent(p.state.agentSessions?.byAgentId[i]?.workspaceId);return Qe.track(`sendMessage:${a.key}:${i}:${l?.id??"legacy"}`,async()=>{if(!u())return;M.debug(`Sending message to agent ${i}`,{contentLength:s.length,hasContextReferences:!!t.contextReferences?.length,model:t.model});let c=await p.dispatch(Fe(e.id,i));if(u()){if(!c)throw new Error(n.agent_streamLifecycle_sessionNotFound_error({agentId:i}));c={...c,isStreaming:c.isStreaming??!1};{if(c&&(c.status==="pending"||!c.id)&&!c.backendSessionId&&c.activationState!==K.ACTIVE&&c.activationState!==K.ACTIVATING){const h=e.id.startsWith("optimistic-"),Y=e.worktreePath||e.repositoryPath||e.path;if(!h&&Y){M.info("Activating pending session in sendMessage",{agentId:i,status:c.status,activationState:c.activationState,hasBackendSessionId:!!c.backendSessionId});const x=await p.dispatch(ke(e.id,i));if(!u())return;x&&(c=x)}else throw M.warn("Cannot activate agent - workspace not ready",{agentId:i,workspaceId:e.id,isOptimistic:h,hasWorktreePath:!!e.worktreePath,hasRepositoryPath:!!e.repositoryPath,hasPath:!!e.path}),new Error(n.agent_streamLifecycle_spaceNotReady_error())}else c&&c.status==="pending"&&c.backendSessionId&&(M.info("Fixing status for already-activated session",{agentId:i,backendSessionId:c.backendSessionId,activationState:c.activationState}),c={...c,status:Ge.Active,activationState:K.ACTIVE},A(me({...c,workspaceId:e.id})));if(!c)throw new Error(`Failed to get or create session for agent ${i}`);A(me({...c,workspaceId:e.id}));const g=[{type:"text",text:s}];if(t.imageBlocks)for(const h of t.imageBlocks)g.push({type:"image",...h.data!==void 0?{data:h.data}:{},...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.attachmentId!==void 0?{attachmentId:h.attachmentId}:{}});if(t.fileBlocks)for(const h of t.fileBlocks)g.push({type:"file",attachmentId:h.attachmentId,fileName:h.fileName,...h.mimeType!==void 0?{mimeType:h.mimeType}:{},...h.size!==void 0?{size:h.size}:{}});const d=t.userAppMessageId??ce(),k=t.messageMetadata?.[Re],P={...t.contextReferences?.length?{contextReferences:t.contextReferences}:{},...k!==void 0?{[Re]:k}:{}},D={id:Ee(ue()),appMessageId:d,role:"user",contentBlocks:g,timestamp:new Date().toISOString(),metadata:{...P,...t.messageMetadata??{}}};o||(l&&(f("rejected"),_=!0),A(Pe(c.id,D))),A(H(c.id,!0));let $=!1,C;try{o||await p.dispatch(xe(e.id,i,!0,{allowTruncation:t.resetHistory}));const h=Ee(`msg_${ue()}`),Y=ce(),x=async()=>nt.wrap(async()=>{if(!u())return;M.info("Agent Service: Sending message to backend with image and file blocks",{agentId:i,sessionId:c.id,hasImageBlocks:!!t.imageBlocks,imageBlocksCount:t.imageBlocks?.length||0,imageBlockDetails:t.imageBlocks?.map(m=>({type:m.type,mimeType:m.mimeType,dataLength:m.data?.length||0}))||[],hasFileBlocks:!!t.fileBlocks,fileBlocksCount:t.fileBlocks?.length||0,fileBlockDetails:t.fileBlocks?.map(m=>({type:m.type,fileName:m.fileName,mimeType:m.mimeType,attachmentId:m.attachmentId,size:m.size}))||[]});const Me=t.model??t.modelId??c.model??void 0;A(Ve(i));const Ne=le(i,e.id),ne=p.state.chatState?.byAgentId[i]?.attemptGeneration??0,T=await qe("agent.sendMessage",{agentId:i,...o&&l?{messageId:l.id}:{},workspaceId:e.id,content:s,model:Me,contextReferences:t.contextReferences,imageBlocks:t.imageBlocks,fileBlocks:t.fileBlocks,noteIds:t.noteIds,stdinContext:t.stdinContext,assistantMessageId:h,userAppMessageId:d,assistantAppMessageId:Y,priority:t.priority,...t.messageMetadata?{messageMetadata:t.messageMetadata}:{}}).catch(m=>{if(u())throw Ke(m)&&(C=m),m});if(u()){if(ht(T)){M.info("Backend dropped duplicate in-flight prompt",{agentId:i,sessionId:c.id}),f("rejected");return}if(T&&typeof T=="object"&&"success"in T){if(!T.success){const m=T.error,I=typeof m=="string"?m:m?.message;throw $=!0,new Error(I||n.agent_streamLifecycle_sendToBackendFailed_error())}if("queued"in T&&T.queued===!0){if(M.info("sendMessage auto-queued by daemon (mid-turn or turn-startup race)",{agentId:i,sessionId:c.id,queuedMessageId:T.queuedMessage?.id}),(!o||!l||!de.select(p.state,l))&&A(H(c.id,!1)),o||A(Ue(c.id,D.id)),o){const I=T.queuedMessage,G=T.turnId,L=typeof G=="string"?G:I?.turnId;if(I&&typeof L=="string"){const S=fe(s,t),X=Q.select(p.state,i,e.id).find(oe=>oe.id===I.id||oe.turnId===L);A(_e(i,I.id,S,L,he(X??I,S),!X&&!!l&&de.select(p.state,l),ne))}f("accepted",I,!0),z(i,e.id);return}const m=T.queuedMessage;if(m){const I=T.turnId,G=typeof I=="string"?I:m.turnId;let L=m;if(u()&&le(i,e.id)===Ne){const S=Q.select(p.state,i,e.id),X=ze(S,m);A(Be(i,X,e.id))}else u()&&(M.debug("queued-response queue seed superseded by an authoritative snapshot; reconciling via hydrate",{agentId:i,queuedMessageId:m.id}),await z(i,e.id).catch(()=>{}),L=Q.select(p.state,i,e.id).find(S=>S.id===m.id||S.turnId===G));if(u()&&typeof G=="string"){const S=fe(s,t);A(_e(i,m.id,S,G,he(L??m,S),!L,ne))}else u()&&M.warn("auto-queued sendMessage response carried no turnId; retry record not parked",{agentId:i,queuedMessageId:m.id})}return}}o&&(f("accepted"),z(i,e.id),ve(i,e.id)),_t.incrementMessageSent(e.id)}},"send message",{retries:o?0:2,notify:!1,context:{agentId:i,workspace:e.id}}),ae=o?await x().then(()=>({success:!0,error:void 0})):await mt.executeWithRecovery(x,ye.streaming,`send-message-${i}`);if(!ae.success)throw ae.error||new Error(n.agent_streamLifecycle_sendFailed_error())}catch(h){if(!u())return;throw A(H(c.id,!1)),!o&&t.messageMetadata&&A($e(c.id,D.id,{metadata:P})),o&&f($||C?"rejected":"uncertain"),C??h}}}},{memoize:!1,coalesce:!0,priority:"high"})}export{Te as U,Ft as a,ee as c,ze as r,kt as s,Ke as u,bt as w};
@@ -1,4 +1,4 @@
1
- var d=Object.defineProperty;var f=(e,s,t)=>s in e?d(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var n=(e,s,t)=>f(e,typeof s!="symbol"?s+"":s,t);import{aV as p,o as g,aT as c,l as u}from"./Bm6N2soI.js";import{h as b}from"./DEB8jcix.js";function m(e,s,t,r=!1){const o=[0];if(t.decorations?.some(i=>typeof i.start=="number"||typeof i.end=="number")===!0)for(let i=e.indexOf(`
1
+ var d=Object.defineProperty;var f=(e,s,t)=>s in e?d(e,s,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[s]=t;var n=(e,s,t)=>f(e,typeof s!="symbol"?s+"":s,t);import{aV as p,o as g,aT as c,l as u}from"./COJ7FcW0.js";import{h as b}from"./DEB8jcix.js";function m(e,s,t,r=!1){const o=[0];if(t.decorations?.some(i=>typeof i.start=="number"||typeof i.end=="number")===!0)for(let i=e.indexOf(`
2
2
  `);i!==-1;i=e.indexOf(`
3
3
  `,i+1))o.push(i+1);const a={type:"element",tagName:"code",properties:{},children:[]},h=p(s.tokens,{decorations:t.decorations,mergeWhitespaces:t.mergeWhitespaces,lineOffsets:o,cacheHtmlStyles:r});for(let i=0;i<h.length;i++)i>0&&a.children.push({type:"text",value:`
4
4
  `}),a.children.push(h[i]);const l={type:"root",children:[{type:"element",tagName:"pre",properties:{class:"diffs",style:s.rootStyle===!1?void 0:s.rootStyle??[s.fg!=null?`color:${s.fg}`:"",s.bg!=null?`background-color:${s.bg}`:""].filter(Boolean).join(";"),tabIndex:0},children:[a]}]};return b(l)}var O=class{constructor(e,s){n(this,"name");n(this,"themeResolver");n(this,"disposed",!1);this.name=e,this.themeResolver=s,g(e)}codeToHtml(e,s){return m(e,this.codeToTokens(e,s),s,this.name==="highlights")}get isDisposed(){return this.disposed}dispose(){this.disposed||(this.disposed=!0,this.releaseResources(),c())}assertNotDisposed(){if(this.disposed)throw new u}},v=class{constructor(){n(this,"disposed",!1);n(this,"stableOffset",0);n(this,"unstable",[]);n(this,"pendingCarriageReturn","")}enqueue(e){this.assertActive(),e=this.pendingCarriageReturn+e,this.pendingCarriageReturn=e.endsWith("\r")?"\r":"",this.pendingCarriageReturn!==""&&(e=e.slice(0,-1));const s=this.unstable.length,t=[],{unstable:r,tailLength:o}=this.tokenizeChunk(e,t);return this.pendingCarriageReturn!==""&&r.push({content:"\r",offset:this.stableOffset+o}),this.unstable=r,{recall:s,stable:t,unstable:r}}pushLineBreak(e,s,t){for(let r=0;r<t.length;r++)e.push({content:t[r],offset:this.stableOffset+s+r});this.stableOffset+=s+t.length}close(){const e=this.unstable;return this.dispose(),{stable:e}}clear(){this.assertActive(),this.stableOffset=0,this.unstable=[],this.pendingCarriageReturn="",this.resetSource()}dispose(){this.disposed||(this.disposed=!0,this.unstable=[],this.releaseSource())}copyStateTo(e){e.stableOffset=this.stableOffset,e.unstable=this.unstable.slice(),e.pendingCarriageReturn=this.pendingCarriageReturn}assertActive(){if(this.disposed)throw new Error("stream tokenizer is disposed")}};export{v as B,O as D};
@@ -1 +1 @@
1
- import{Y as a,aM as e}from"./DPttSllj.js";const t={note:a,changes:e},c={note:"note",changes:"changes","local-changes":"changes","chat-changes":"changes","activity-changes":"changes"};function o(n){return c[n]??null}export{t as R,o as g};
1
+ import{Y as a,aM as e}from"./COofQgO0.js";const t={note:a,changes:e},c={note:"note",changes:"changes","local-changes":"changes","chat-changes":"changes","activity-changes":"changes"};function o(n){return c[n]??null}export{t as R,o as g};