@intent-hq/web 2.383.4 → 2.383.6

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 (252) hide show
  1. package/package.json +1 -1
  2. package/web/app/immutable/chunks/{RFsxwSsB.js → -jC6R53Y.js} +1 -1
  3. package/web/app/immutable/chunks/{Co4vj0dC.js → 11IPfP64.js} +1 -1
  4. package/web/app/immutable/chunks/{Dkwe3T9x.js → 1a7PBgFk.js} +1 -1
  5. package/web/app/immutable/chunks/{DnJ4jlPB.js → 2BBUaa8p.js} +1 -1
  6. package/web/app/immutable/chunks/{t0y-kHkY.js → 3gdcau2g.js} +1 -1
  7. package/web/app/immutable/chunks/3lsVHf6U.js +10 -0
  8. package/web/app/immutable/chunks/{DrvBnHFf.js → 606ykLjp.js} +3 -3
  9. package/web/app/immutable/chunks/{B8-Q1tED.js → 6D8I0EJP.js} +1 -1
  10. package/web/app/immutable/chunks/{35Pj1tWu.js → 6mKf423T.js} +1 -1
  11. package/web/app/immutable/chunks/{Cv7maMEX.js → 7EHgRnzQ.js} +1 -1
  12. package/web/app/immutable/chunks/{CiMmbOsB.js → 7g_E9v8v.js} +1 -1
  13. package/web/app/immutable/chunks/{DxxuJILr.js → 8o9CPlKy.js} +6 -6
  14. package/web/app/immutable/chunks/{f24VwgrA.js → 90dwRRI_.js} +1 -1
  15. package/web/app/immutable/chunks/9bpkKfDs.js +1 -0
  16. package/web/app/immutable/chunks/{No1eCFy3.js → B-4NNXpn.js} +1 -1
  17. package/web/app/immutable/chunks/{D6dlPeEM.js → B0-WaGMs.js} +1 -1
  18. package/web/app/immutable/chunks/{B1poZr5t.js → B0iC7Hp2.js} +1 -1
  19. package/web/app/immutable/chunks/{gTlamSLB.js → B2REQkHq.js} +3 -3
  20. package/web/app/immutable/chunks/{BAKPnd3w.js → B2w13ngc.js} +1 -1
  21. package/web/app/immutable/chunks/{C6mS8uZB.js → B50rrLDJ.js} +1 -1
  22. package/web/app/immutable/chunks/{DoRDI0_k.js → B51SeJXG.js} +1 -1
  23. package/web/app/immutable/chunks/{CSB4cQlc.js → B5R37z34.js} +3 -3
  24. package/web/app/immutable/chunks/{Dk14zZxI.js → B5lAxopi.js} +1 -1
  25. package/web/app/immutable/chunks/{L_tYoUCb.js → B9ZFoPLo.js} +1 -1
  26. package/web/app/immutable/chunks/{c5QZsH9t.js → B9qXV8kb.js} +1 -1
  27. package/web/app/immutable/chunks/{C_KuQ05a.js → BAwmUXtg.js} +1 -1
  28. package/web/app/immutable/chunks/{C7d9ZbWc.js → BBIYuEK_.js} +1 -1
  29. package/web/app/immutable/chunks/{CY8jnGs7.js → BBdixUsX.js} +1 -1
  30. package/web/app/immutable/chunks/{wVIKqVlE.js → BDATxlJG.js} +4 -4
  31. package/web/app/immutable/chunks/{BoIrWOoc.js → BFKNHcgD.js} +1 -1
  32. package/web/app/immutable/chunks/{CO5zWp8I.js → BFPO9C1I.js} +1 -1
  33. package/web/app/immutable/chunks/{BLL1wBVI.js → BHzfXdU-.js} +1 -1
  34. package/web/app/immutable/chunks/{BxEf7uwl.js → BMF9dBr3.js} +1 -1
  35. package/web/app/immutable/chunks/{B4WuQori.js → BMWq5Cem.js} +1 -1
  36. package/web/app/immutable/chunks/{DOL2D_mf.js → BNK8isss.js} +1 -1
  37. package/web/app/immutable/chunks/{CHtJr32B.js → BNbuor20.js} +1 -1
  38. package/web/app/immutable/chunks/{DA5opfEp.js → BPjvgJzJ.js} +1 -1
  39. package/web/app/immutable/chunks/{DvmLmn-C.js → BRdwblgo.js} +1 -1
  40. package/web/app/immutable/chunks/{BgxuPkk9.js → BTtB75CV.js} +1 -1
  41. package/web/app/immutable/chunks/BWu0YXkV.js +1 -0
  42. package/web/app/immutable/chunks/{CqcqWJoa.js → BY98dnH8.js} +1 -1
  43. package/web/app/immutable/chunks/{CvjFWjQI.js → BYBhz2vc.js} +3 -3
  44. package/web/app/immutable/chunks/{DRYK6Su3.js → BYsxLCZX.js} +1 -1
  45. package/web/app/immutable/chunks/{DH-1Jck3.js → BZxyR-1L.js} +1 -1
  46. package/web/app/immutable/chunks/{Dh9P66ji.js → BdReS-5Z.js} +1 -1
  47. package/web/app/immutable/chunks/{-ZE0BKMJ.js → BhFoVE_t.js} +1 -1
  48. package/web/app/immutable/chunks/{TwdEefIb.js → Bhl-6bQ6.js} +1 -1
  49. package/web/app/immutable/chunks/{Bs9K_x5H.js → BkPSRIlH.js} +1 -1
  50. package/web/app/immutable/chunks/{BAtDEUM7.js → BlU12h14.js} +1 -1
  51. package/web/app/immutable/chunks/{BMGB0uZU.js → BlU2v4uc.js} +1 -1
  52. package/web/app/immutable/chunks/{BIsvX0dB.js → BmRtsF0k.js} +3 -3
  53. package/web/app/immutable/chunks/{Dlk4BhFg.js → BnG797lq.js} +1 -1
  54. package/web/app/immutable/chunks/{CDK_hSiv.js → BotfI-oJ.js} +1 -1
  55. package/web/app/immutable/chunks/{K6lw4N0L.js → Bp4RMAg2.js} +1 -1
  56. package/web/app/immutable/chunks/{bXVL0d4u.js → BpIice81.js} +1 -1
  57. package/web/app/immutable/chunks/{B1PlU8Mp.js → BsHKPA8J.js} +2 -2
  58. package/web/app/immutable/chunks/{EK6zOAHM.js → BsOWc0fD.js} +1 -1
  59. package/web/app/immutable/chunks/BsuKoRte.js +1 -0
  60. package/web/app/immutable/chunks/{F-AjnQny.js → Bx7gEyNR.js} +1 -1
  61. package/web/app/immutable/chunks/{vELdnnGk.js → BxQcCpea.js} +1 -1
  62. package/web/app/immutable/chunks/{CtTTJ9Pl.js → BxTLs9JS.js} +1 -1
  63. package/web/app/immutable/chunks/{BdJ_iWAp.js → ByGaQPue.js} +1 -1
  64. package/web/app/immutable/chunks/{CvQK16ac.js → BzuFQ4uC.js} +1 -1
  65. package/web/app/immutable/chunks/{DU-k_hXE.js → C-HPMTfc.js} +1 -1
  66. package/web/app/immutable/chunks/{6Bqipt1r.js → C-LBvoL7.js} +1 -1
  67. package/web/app/immutable/chunks/{ozVAo4aX.js → C1JG3JxG.js} +1 -1
  68. package/web/app/immutable/chunks/{Bt7Q47HI.js → C2307jRD.js} +1 -1
  69. package/web/app/immutable/chunks/{6oqjp0oY.js → C2XGUcnW.js} +1 -1
  70. package/web/app/immutable/chunks/{DCRuihKm.js → C2jYl_tm.js} +2 -2
  71. package/web/app/immutable/chunks/{CkA2ItLw.js → C3Cs4xcH.js} +1 -1
  72. package/web/app/immutable/chunks/{518Fef2L.js → C3kvbgti.js} +1 -1
  73. package/web/app/immutable/chunks/{C4QKwtCH.js → C429ViPJ.js} +1 -1
  74. package/web/app/immutable/chunks/{Bi3RVGsg.js → C5I-aQNv.js} +1 -1
  75. package/web/app/immutable/chunks/{DgL848jV.js → C6UuYHLt.js} +1 -1
  76. package/web/app/immutable/chunks/{_SYFiE9N.js → C7Q9MjK0.js} +1 -1
  77. package/web/app/immutable/chunks/{oBUj9ZOr.js → C8iCqYhc.js} +1 -1
  78. package/web/app/immutable/chunks/{CUJZhB5z.js → C9Ea_4DW.js} +1 -1
  79. package/web/app/immutable/chunks/{Bty1UglO.js → CAXPT_Gw.js} +1 -1
  80. package/web/app/immutable/chunks/{C3cn2j3y.js → CAgJTEqX.js} +1 -1
  81. package/web/app/immutable/chunks/{DL8v_XLP.js → CBh3oApX.js} +2 -2
  82. package/web/app/immutable/chunks/{BFzamEtR.js → CChkl_5h.js} +1 -1
  83. package/web/app/immutable/chunks/{DC8keNAk.js → CCjzzCpy.js} +1 -1
  84. package/web/app/immutable/chunks/{D51XIZYq.js → CDLANF8s.js} +1 -1
  85. package/web/app/immutable/chunks/{Bvp3gPe2.js → CDr_0i5Z.js} +1 -1
  86. package/web/app/immutable/chunks/{BYq9VtBF.js → CENp25rd.js} +1 -1
  87. package/web/app/immutable/chunks/{BV1ipkUL.js → CHTaR4fl.js} +1 -1
  88. package/web/app/immutable/chunks/{B_Fn14Ok.js → CHoUTmhW.js} +1 -1
  89. package/web/app/immutable/chunks/{Y-O_IvTW.js → CIWayVej.js} +1 -1
  90. package/web/app/immutable/chunks/{DsGUBv3k.js → CQwOMyxz.js} +1 -1
  91. package/web/app/immutable/chunks/{yFcbscNn.js → CRdOY_2z.js} +1 -1
  92. package/web/app/immutable/chunks/{DKHY8q_S.js → CTP1vzdq.js} +1 -1
  93. package/web/app/immutable/chunks/{CRZZ_hOy.js → CW0Mb2k4.js} +1 -1
  94. package/web/app/immutable/chunks/{mbHeC_bT.js → CXqdP_ch.js} +1 -1
  95. package/web/app/immutable/chunks/{B2Ym4lhl.js → CYkPVUDx.js} +1 -1
  96. package/web/app/immutable/chunks/{CPr4uSCV.js → Cb0qNR4H.js} +1 -1
  97. package/web/app/immutable/chunks/{Czxip--U.js → CbazPhvO.js} +1 -1
  98. package/web/app/immutable/chunks/{CMHU_cf0.js → CdyTEe8y.js} +1 -1
  99. package/web/app/immutable/chunks/{CmrjfWYI.js → Ce1_P2yR.js} +1 -1
  100. package/web/app/immutable/chunks/{Cqg6DAOX.js → CeGEVvKd.js} +2 -2
  101. package/web/app/immutable/chunks/{HRIwLWKn.js → CfOfDsl2.js} +1 -1
  102. package/web/app/immutable/chunks/{B48XhjTD.js → CgCfiUM-.js} +2 -2
  103. package/web/app/immutable/chunks/{C8y9EItt.js → Chp6TQgb.js} +1 -1
  104. package/web/app/immutable/chunks/{Dw1ghJA6.js → CjJvlfCr.js} +4 -4
  105. package/web/app/immutable/chunks/{tZyAiGvb.js → ClIBKxjv.js} +1 -1
  106. package/web/app/immutable/chunks/{Bw9sjqWK.js → Cm4ptdH4.js} +1 -1
  107. package/web/app/immutable/chunks/{OtomGvb3.js → CmAb18no.js} +1 -1
  108. package/web/app/immutable/chunks/{BaujsV9k.js → Cppy6ZYG.js} +1 -1
  109. package/web/app/immutable/chunks/{BTrqJIJZ.js → Cq_r_CYV.js} +1 -1
  110. package/web/app/immutable/chunks/{0Z36NhH2.js → CqcYFh8j.js} +1 -1
  111. package/web/app/immutable/chunks/{FzlZUztb.js → CttA-M7l.js} +1 -1
  112. package/web/app/immutable/chunks/{CGwsFBBd.js → Cv71FrWX.js} +1 -1
  113. package/web/app/immutable/chunks/{CO3Ad3gs.js → Cyc867L5.js} +1 -1
  114. package/web/app/immutable/chunks/{Ca13FruI.js → D0a_zKAq.js} +1 -1
  115. package/web/app/immutable/chunks/{12yXK53O.js → D1gev-Oa.js} +1 -1
  116. package/web/app/immutable/chunks/{DTuql3Rj.js → D32iIfZB.js} +1 -1
  117. package/web/app/immutable/chunks/{BTa8GIiv.js → D3KbOo9x.js} +2 -2
  118. package/web/app/immutable/chunks/{D_Xpj-6r.js → D5TRf27k.js} +1 -1
  119. package/web/app/immutable/chunks/{Djp7mdlG.js → D6x1PvJt.js} +1 -1
  120. package/web/app/immutable/chunks/{BpboU9n2.js → D85Dkv1L.js} +1 -1
  121. package/web/app/immutable/chunks/{MIFcwWBB.js → D93FnkSV.js} +1 -1
  122. package/web/app/immutable/chunks/{Bvi-fRGz.js → DA3JhNUa.js} +1 -1
  123. package/web/app/immutable/chunks/{CIEu92Dv.js → DA6FwFPA.js} +3 -3
  124. package/web/app/immutable/chunks/{D_vQVrz1.js → DAi59CB_.js} +1 -1
  125. package/web/app/immutable/chunks/{CFr8iZKI.js → DAj3--4v.js} +1 -1
  126. package/web/app/immutable/chunks/{fiz8N_zQ.js → DCL0Px6m.js} +1 -1
  127. package/web/app/immutable/chunks/{BnSzQmM2.js → DDWXzJJL.js} +1 -1
  128. package/web/app/immutable/chunks/{DrIA1Azf.js → DDxtqhsd.js} +1 -1
  129. package/web/app/immutable/chunks/{CY4fyoCV.js → DEe4pSnF.js} +1 -1
  130. package/web/app/immutable/chunks/{Dsr4GELp.js → DFUCAM2K.js} +1 -1
  131. package/web/app/immutable/chunks/{5sSmbvC-.js → DGdXhwsJ.js} +1 -1
  132. package/web/app/immutable/chunks/{BP5uGGO_.js → DHLXX1td.js} +1 -1
  133. package/web/app/immutable/chunks/{BypvqIQM.js → DHbAORA3.js} +1 -1
  134. package/web/app/immutable/chunks/{B4SiDSWP.js → DI_O2uCQ.js} +1 -1
  135. package/web/app/immutable/chunks/{Ctbo6mXV.js → DJcj8WvN.js} +1 -1
  136. package/web/app/immutable/chunks/{Dgfo6hku.js → DML-1n7e.js} +1 -1
  137. package/web/app/immutable/chunks/{jIe9AFY3.js → DMtuN9wu.js} +1 -1
  138. package/web/app/immutable/chunks/{CATo12kv.js → DODT78Qk.js} +2 -2
  139. package/web/app/immutable/chunks/{B1QCl1Po.js → DOXAHHuz.js} +2 -2
  140. package/web/app/immutable/chunks/{DTTFQasE.js → DPTzvpZC.js} +2 -2
  141. package/web/app/immutable/chunks/{CzXxUwZ9.js → DPpIdNvg.js} +1 -1
  142. package/web/app/immutable/chunks/{CtDWHhd5.js → DSpm6A1W.js} +2 -2
  143. package/web/app/immutable/chunks/{KcJe_B2f.js → DT4Cgjmu.js} +1 -1
  144. package/web/app/immutable/chunks/{Y3tz73Wx.js → DTFjA6nd.js} +1 -1
  145. package/web/app/immutable/chunks/{CruNSA_k.js → DTpKHtQ2.js} +1 -1
  146. package/web/app/immutable/chunks/{CjZzZn8W.js → DUJWrM6V.js} +4 -4
  147. package/web/app/immutable/chunks/{CHLX1QZz.js → DXn0DuET.js} +1 -1
  148. package/web/app/immutable/chunks/{cmJ0YuhX.js → DYVqPPax.js} +1 -1
  149. package/web/app/immutable/chunks/{eElW3aeh.js → DZ84MPQO.js} +1 -1
  150. package/web/app/immutable/chunks/{Cxdjn52l.js → Day2rmDJ.js} +1 -1
  151. package/web/app/immutable/chunks/{Cpi4W9SM.js → DayBneSF.js} +1 -1
  152. package/web/app/immutable/chunks/{CvWPR84D.js → DdYRxRPc.js} +1 -1
  153. package/web/app/immutable/chunks/{Bt7IO3Ki.js → DfNht_cf.js} +1 -1
  154. package/web/app/immutable/chunks/{YjYi8jsS.js → DhHELjW9.js} +1 -1
  155. package/web/app/immutable/chunks/{QeBH-DWE.js → Dhy-QJgd.js} +1 -1
  156. package/web/app/immutable/chunks/{KYuLFpkq.js → DiNBgjb1.js} +1 -1
  157. package/web/app/immutable/chunks/{C1EvfTg-.js → DjNVz8pO.js} +1 -1
  158. package/web/app/immutable/chunks/{6-uYidyP.js → DkDSK_05.js} +3 -3
  159. package/web/app/immutable/chunks/{DCK8dPAL.js → DkME16PR.js} +1 -1
  160. package/web/app/immutable/chunks/{BmTMWrby.js → DlUZpQ7U.js} +1 -1
  161. package/web/app/immutable/chunks/{CSRYV6LQ.js → Dnp239cR.js} +1 -1
  162. package/web/app/immutable/chunks/{w8vA4Z3z.js → DoDP-NJt.js} +1 -1
  163. package/web/app/immutable/chunks/{BfojStRz.js → DpPV7WHr.js} +1 -1
  164. package/web/app/immutable/chunks/{BP3Sccje.js → DpX9aeiZ.js} +1 -1
  165. package/web/app/immutable/chunks/{UqfcQTtt.js → DqUfbKVJ.js} +1 -1
  166. package/web/app/immutable/chunks/{DIdM8saJ.js → DrK3Y0uD.js} +2 -2
  167. package/web/app/immutable/chunks/{Cqa6LF3b.js → DrWDRmYR.js} +1 -1
  168. package/web/app/immutable/chunks/{CJj7ZaOk.js → DsevRTZh.js} +1 -1
  169. package/web/app/immutable/chunks/{DrxfcnSy.js → DsffLoT8.js} +1 -1
  170. package/web/app/immutable/chunks/{CZ1onE9g.js → DswCtQ8W.js} +1 -1
  171. package/web/app/immutable/chunks/{BNF7dSgi.js → DtmCgGP_.js} +2 -2
  172. package/web/app/immutable/chunks/{x81_VdcZ.js → Dvrtbry_.js} +1 -1
  173. package/web/app/immutable/chunks/{QMwjEX1-.js → DwEGyXAz.js} +1 -1
  174. package/web/app/immutable/chunks/{BPL5Fo2b.js → Dx3nOa5s.js} +1 -1
  175. package/web/app/immutable/chunks/{qCXYeue5.js → Dx_8-INB.js} +1 -1
  176. package/web/app/immutable/chunks/{BcpfdNy8.js → FITmaVUJ.js} +1 -1
  177. package/web/app/immutable/chunks/{Dbiz8ybb.js → FKyiybGz.js} +1 -1
  178. package/web/app/immutable/chunks/{DH3NAcDJ.js → IcuTx12D.js} +1 -1
  179. package/web/app/immutable/chunks/{Drv2Rza_.js → JbVFIGCp.js} +13 -13
  180. package/web/app/immutable/chunks/{CAvYeStH.js → JvS7MGpw.js} +1 -1
  181. package/web/app/immutable/chunks/{DQ_mNIfK.js → L0wFy8_j.js} +1 -1
  182. package/web/app/immutable/chunks/{D8ohaX19.js → NE3LtfEb.js} +1 -1
  183. package/web/app/immutable/chunks/{C3vHP-qn.js → RnZ98Lx7.js} +1 -1
  184. package/web/app/immutable/chunks/{BNcG1DWU.js → RwU8EQ7-.js} +1 -1
  185. package/web/app/immutable/chunks/{C4JbSg3f.js → SB0XkB7s.js} +1 -1
  186. package/web/app/immutable/chunks/{CbqxWBi7.js → T-y84UQ-.js} +1 -1
  187. package/web/app/immutable/chunks/{CP-xkzkH.js → UmmBf5TK.js} +1 -1
  188. package/web/app/immutable/chunks/{S845NCb3.js → VxaCN40t.js} +1 -1
  189. package/web/app/immutable/chunks/{DeQ_Nnwi.js → WIWu6pzv.js} +1 -1
  190. package/web/app/immutable/chunks/{CDGoCDAX.js → ZAGtf4QC.js} +4 -4
  191. package/web/app/immutable/chunks/{BxJ6X-Sl.js → ZNxS70ti.js} +1 -1
  192. package/web/app/immutable/chunks/{DYguRX86.js → Zc9S8AIT.js} +1 -1
  193. package/web/app/immutable/chunks/{tr-2J8Mf.js → _LtUY0jS.js} +1 -1
  194. package/web/app/immutable/chunks/{DwL1A1su.js → _WGu_9si.js} +1 -1
  195. package/web/app/immutable/chunks/{PIgqsYsQ.js → _Z48PZPG.js} +1 -1
  196. package/web/app/immutable/chunks/{DtF9DVpp.js → _szCylN8.js} +1 -1
  197. package/web/app/immutable/chunks/{D_Eq4qPA.js → bQJcjDVH.js} +1 -1
  198. package/web/app/immutable/chunks/{OFhgRaUm.js → bq2jN3Y4.js} +1 -1
  199. package/web/app/immutable/chunks/{CDjpuJh0.js → c6a4q1y9.js} +1 -1
  200. package/web/app/immutable/chunks/{D37getya.js → ceYukiuF.js} +1 -1
  201. package/web/app/immutable/chunks/{BJWnaGKs.js → dpO6awDJ.js} +1 -1
  202. package/web/app/immutable/chunks/{Bc3KFcWc.js → e2T92U2C.js} +3 -3
  203. package/web/app/immutable/chunks/{Di84urxA.js → eJ7uL4LD.js} +1 -1
  204. package/web/app/immutable/chunks/{BMv9rEVV.js → gXSh3Rqp.js} +1 -1
  205. package/web/app/immutable/chunks/{BeOwB_6G.js → iDB1itc7.js} +1 -1
  206. package/web/app/immutable/chunks/{-Mic_e6k.js → lkgbZnYm.js} +1 -1
  207. package/web/app/immutable/chunks/{CjTo2K46.js → nA0tsFRt.js} +1 -1
  208. package/web/app/immutable/chunks/{CQHTACis.js → oZzpgNB8.js} +1 -1
  209. package/web/app/immutable/chunks/{TMWKDIeD.js → okU6lEoA.js} +1 -1
  210. package/web/app/immutable/chunks/{Boyio2o8.js → pAMHAQGK.js} +1 -1
  211. package/web/app/immutable/chunks/{B2nCyo89.js → pQ6IdBCz.js} +1 -1
  212. package/web/app/immutable/chunks/{TLsmZI1o.js → qEaQygdG.js} +1 -1
  213. package/web/app/immutable/chunks/{BSKFIBj2.js → ram0Xoqf.js} +1 -1
  214. package/web/app/immutable/chunks/{CCqqosml.js → rpEVAvPW.js} +1 -1
  215. package/web/app/immutable/chunks/{CSVgdt55.js → sABlNrvu.js} +1 -1
  216. package/web/app/immutable/chunks/{DEU72krH.js → syIfkUtY.js} +2 -2
  217. package/web/app/immutable/chunks/{BnaEYx3G.js → umMyGIUt.js} +1 -1
  218. package/web/app/immutable/chunks/{HlXIpYIa.js → vpidVnoK.js} +1 -1
  219. package/web/app/immutable/chunks/{CE15e5UF.js → w2q0NJFW.js} +1 -1
  220. package/web/app/immutable/chunks/{CBp-yM36.js → wUEfWFO0.js} +1 -1
  221. package/web/app/immutable/chunks/{hHMYoFyG.js → wjh5cuBI.js} +1 -1
  222. package/web/app/immutable/chunks/{CnEpmcA-.js → x8QjiOrF.js} +1 -1
  223. package/web/app/immutable/chunks/{usXRXUNe.js → xCOOeB5y.js} +1 -1
  224. package/web/app/immutable/entry/{app.CQjcFUvX.js → app.DTU8Ib8_.js} +2 -2
  225. package/web/app/immutable/entry/start.vqAdlzsb.js +1 -0
  226. package/web/app/immutable/nodes/{0.BZ6BuxeE.js → 0.DSHPaYBf.js} +1 -1
  227. package/web/app/immutable/nodes/{1.DxAIVMOr.js → 1.DKliZtsI.js} +1 -1
  228. package/web/app/immutable/nodes/{10.UdD3v_c2.js → 10.mXAnRqVu.js} +5 -5
  229. package/web/app/immutable/nodes/{11.DFg9W_ST.js → 11.BNoZ2Awp.js} +1 -1
  230. package/web/app/immutable/nodes/{13.CCKyw-_o.js → 13.C6TyTlAm.js} +1 -1
  231. package/web/app/immutable/nodes/{14.BD92xFv4.js → 14.CHiqNDyF.js} +1 -1
  232. package/web/app/immutable/nodes/{15.7ofOw_b1.js → 15.CklBb62Z.js} +1 -1
  233. package/web/app/immutable/nodes/{16.CVCm-nfj.js → 16.Dyi9KYXl.js} +1 -1
  234. package/web/app/immutable/nodes/{17.CjKvJw8X.js → 17.CH042Yj8.js} +1 -1
  235. package/web/app/immutable/nodes/{18.DDY8Eqsn.js → 18.DVg5DSa7.js} +1 -1
  236. package/web/app/immutable/nodes/{19.C7CCQoBf.js → 19.BxZ4y2DZ.js} +2 -2
  237. package/web/app/immutable/nodes/{2.DuqlsYHB.js → 2.DZmz8fq0.js} +4 -4
  238. package/web/app/immutable/nodes/{20.CLsq1QLL.js → 20.Byg15mRq.js} +1 -1
  239. package/web/app/immutable/nodes/{3.DRC75TZt.js → 3.umir6RZQ.js} +1 -1
  240. package/web/app/immutable/nodes/{4.DKVGzRd0.js → 4.BN-AJGgH.js} +1 -1
  241. package/web/app/immutable/nodes/{5.DY0hRGuv.js → 5.BbafFHWz.js} +1 -1
  242. package/web/app/immutable/nodes/{6.TN7w_X2Z.js → 6.Zsgk8jus.js} +1 -1
  243. package/web/app/immutable/nodes/{7.swMVj6u3.js → 7.ChjI-TG1.js} +1 -1
  244. package/web/app/immutable/nodes/{8.DlrgL_9b.js → 8.DPKyN2xT.js} +1 -1
  245. package/web/app/immutable/nodes/{9.CSFgmDLj.js → 9.Ds0Wbr5E.js} +4 -4
  246. package/web/app/version.json +1 -1
  247. package/web/index.html +12 -12
  248. package/web/app/immutable/chunks/BIVeXMBl.js +0 -1
  249. package/web/app/immutable/chunks/CWoaP7UR.js +0 -10
  250. package/web/app/immutable/chunks/D-zjf2Af.js +0 -1
  251. package/web/app/immutable/chunks/DkCny-Z-.js +0 -1
  252. package/web/app/immutable/entry/start.BSd130By.js +0 -1
@@ -1,4 +1,4 @@
1
- var rs=Object.defineProperty;var sn=n=>{throw TypeError(n)};var ss=(n,e,t)=>e in n?rs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>ss(n,typeof e!="symbol"?e+"":e,t),bt=(n,e,t)=>e.has(n)||sn("Cannot "+t);var A=(n,e,t)=>(bt(n,e,"read from private field"),t?t.call(n):e.get(n)),V=(n,e,t)=>e.has(n)?sn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Ie=(n,e,t,r)=>(bt(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),kt=(n,e,t)=>(bt(n,e,"access private method"),t);import{d as ar,b as os,C as is}from"./B5aYN90J.js";import{bm as T}from"./C0QTy0Sy.js";import{fU as as,as as ve,r_ as cr,i as cs,h as It,bq as ur,Cp as us,ag as ls,q as it,m5 as ds,ns as fs,Jv as ps,$ as St,ac as wt,tU as gs,av as ys,E as ms,au as hs,j as vs,aL as bs,aM as ks,aS as Is,aF as Ss,aO as ws,aK as As,aR as Ts,aJ as Es,aN as Cs,aP as Rs,aI as _s,aQ as Ms,aD as Ps,aH as Os,aG as xs,n_ as lr,iC as dr,br as De,it as Ns,ib as Bs,b0 as Ls}from"./tr-2J8Mf.js";import{M as ae,O as ce,h as u,p as js,q as Ds,L as Us,i as Jt,k as Oe,U as qs,a as Fs,N as $s,e as Ws,s as Gs,r as Hs}from"./DCRuihKm.js";import{b as on,B as Yt}from"./C7LIHk5_.js";import{c as Ne}from"./ChTqQfQN.js";import{bV as Vs,br as zs,aD as ye,bH as At}from"./3SdAC2_C.js";import{a as Ks}from"./BdWqymET.js";import{i as ee}from"./BBWuirRW.js";import{L as Js}from"./DONrLvvt.js";import{i as Ys,C as fr,g as Zs}from"./DypB-Dwi.js";import{g as Qs}from"./DwL1A1su.js";import{R as Xs,G as eo,b as to}from"./Bqd7fdCF.js";import{r as te,b as no,i as ro}from"./uXuxG9cN.js";import{o as Be,s as P,c as so,n as ne,b as oo,r as Tt}from"./CIyUrgF0.js";import{Z as io}from"./CrD0jtXE.js";const ao=["high","medium","low"],co=["pending","in_progress","completed"],uo=256;function Z(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function lo(n){return Z(n)?typeof n.content=="string"&&ao.includes(n.priority)&&co.includes(n.status):!1}function pr(n){return Z(n)&&n.type==="plan"&&Array.isArray(n.entries)&&n.entries.length<=uo&&n.entries.every(lo)}function an(n){return n?.type==="plan"?pr(n):typeof n=="object"&&n!==null&&(typeof n.type=="string"&&["text","code","tool_use","tool_result","thinking","image","audio","video","file","nav-link","proposal","plan"].includes(n.type)||n.kind==="nav-link"&&typeof n.target=="string"||ar(n.kind)&&!!n.preview)}const fo=/\.(?:mp4|webm|mov|m4v)$/i,po=/^video\/[a-z0-9][a-z0-9.+-]*$/i,go=new Set(["video/mp4","video/webm","video/quicktime","video/x-m4v","video/m4v"]);function Ft(n){if(typeof n!="string")return;const e=n.split(";",1)[0].trim().toLowerCase();return po.test(e)?e:void 0}function yo(n,e){if(typeof n!="string"||n.length===0||n!==n.trim())return null;let t;try{t=new URL(n)}catch{return null}if(t.protocol!=="https:"||t.username||t.password)return null;const r=Ft(e),s=r&&go.has(r)?r:void 0;return!s&&!fo.test(t.pathname)?null:{kind:"remote",url:n,...s?{mimeType:s}:{}}}function mo(n,e){if(typeof n!="string"||!n.startsWith("intent://local/")||!e||!/^[A-Za-z0-9._-]+$/.test(e)||n.includes("?")||n.includes("#"))return null;const r=n.slice(9).split("/").slice(1);let s,o;if(r[0]==="file")s=e,o=r.slice(1);else if(r.length>=3&&r[1]==="file"){try{s=decodeURIComponent(r[0])}catch{return null}if(s!==e)return null;o=r.slice(2)}else return null;const i=[];for(const l of o){let d;try{d=decodeURIComponent(l)}catch{return null}if(!d||d==="."||d===".."||d.includes("/")||d.includes("\\")||d.includes("\0"))return null;i.push(d)}if(i.length===0||/^[A-Za-z]:/.test(i[0]))return null;const a=i[i.length-1].toLowerCase(),c=a.endsWith(".mp4")?"video/mp4":a.endsWith(".webm")?"video/webm":null;return c?{kind:"workspace",url:`workspace-file://${s}/${i.map(encodeURIComponent).join("/")}`,mimeType:c}:null}function Et(n,e,t){return yo(n,e)??mo(n,t)}function Ue(n,e,t){return{type:"video",source:e,...typeof n.id=="string"?{id:n.id}:{},...Z(n.metadata)?{metadata:n.metadata}:{},...typeof t=="string"&&t.length>0?{fileName:t}:{}}}function ho(n,e){if(!Z(n))return null;const t=n.type;if((t==="file"||t==="blob")&&typeof n.data=="string"&&n.data){const r=Ft(n.mimeType);if(r)return Ue(n,{kind:"inline",data:n.data,mimeType:r},n.fileName)}if(t==="resource"&&Z(n.resource)){const r=n.resource,s=Ft(r.mimeType);if(s&&typeof r.blob=="string"&&r.blob)return Ue(n,{kind:"inline",data:r.blob,mimeType:s},r.name);const o=Et(r.uri,r.mimeType,e);return o?Ue(n,o,r.name):null}if(t==="resource_link"){const r=Et(n.uri,n.mimeType,e);return r?Ue(n,r,n.name):null}if(t==="file"){const r=Et(n.url??n.uri,n.mimeType,e);return r?Ue(n,r,n.fileName):null}return null}function cn(n,e){if(!Array.isArray(n))return n;let t=!1;const r=n.map(s=>{const o=gr(s,e);return o!==s&&(t=!0),o});return t?r:n}function gr(n,e){const t=ho(n,e);if(t)return t;if(!Z(n)||n.type!=="tool_result")return n;const r=cn(n.output,e),s=cn(n.content,e);return r===n.output&&s===n.content?n:{...n,output:r,content:s}}function Uu(n,e,t){if(e!=="assistant")return n;let r=!1;const s=n.map(o=>{const i=gr(o,t);return i!==o&&(r=!0),i});return r?s:n}function vo(n){return n.kind==="inline"?`inline:${n.mimeType}:${n.data}`:`${n.kind}:${n.url}`}function qu(n){const e=new Set;function t(r){let s=!1;const o=[];for(const i of r){if(Z(i)&&i.type==="video"&&Z(i.source)){const a=i.source,c=vo(a);if(e.has(c)){s=!0;continue}e.add(c)}if(Z(i)&&i.type==="tool_result"){const a=Array.isArray(i.output)?t(i.output):i.output,c=Array.isArray(i.content)?t(i.content):i.content;if(a!==i.output||c!==i.content){o.push({...i,output:a,content:c}),s=!0;continue}}o.push(i)}return s?o:r}return t(n)}const bo=new Set(["text","code","tool_use","tool_result","thinking","image","audio","file","nav-link","proposal","plan"]);function ko(n){return{content:n.content,priority:n.priority,status:n.status}}function Io(n){if(!pr(n))throw new Error(`Invalid plan block: required bounded 'entries' snapshot missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);return{type:"plan",...typeof n.id=="string"?{id:n.id}:{},entries:n.entries.map(ko)}}const un=/^image\/[a-z0-9][a-z0-9.+-]*$/i;function So(n){const e=Object.prototype.hasOwnProperty.call(n,"data"),t=typeof n.data=="string",r=n.dataTruncated!==void 0,s=n.dataIsThumbnail!==void 0,o=n.dataBytes!==void 0;if(Object.prototype.hasOwnProperty.call(n,"attachmentId")){if(typeof n.attachmentId!="string"||n.attachmentId.trim().length===0||e||r||s||o||n.mimeType!==void 0&&(typeof n.mimeType!="string"||!un.test(n.mimeType)))throw new Error("Invalid image attachment reference (PROTOCOL §5.5)");return}if(typeof n.mimeType!="string"||!un.test(n.mimeType))throw new Error(`Invalid image block: required image 'mimeType'. Received: ${JSON.stringify(n)}`);if(e&&!t)throw new Error(`Invalid image block: present 'data' must be a string. Received: ${JSON.stringify(n)}`);if(!r){if(!t||s||o)throw new Error(`Invalid image block: full images require 'data' without slim flags. Received: ${JSON.stringify(n)}`);return}if(n.dataTruncated!==!0||!Number.isSafeInteger(n.dataBytes)||n.dataBytes<0||(t?n.dataIsThumbnail!==!0:s))throw new Error(`Invalid image block: malformed slim projection metadata. Received: ${JSON.stringify(n)}`)}function wo(n){if(!n||typeof n!="object")throw new Error("Invalid block: must be an object");const e=os(n);if(e)return{type:"proposal",kind:e.kind,payload:e.payload,preview:e.preview,applyToolCallId:e.applyToolCallId,proposal:e,id:n.id,metadata:n.metadata};if(n.kind==="nav-link"&&typeof n.target=="string")return{type:"nav-link",kind:"nav-link",target:n.target,label:n.label,id:n.id,metadata:n.metadata};if((n.type==="proposal"||ar(n.kind))&&n.preview){const t=n.proposal??{kind:n.kind,payload:n.payload??{},preview:n.preview,applyToolCallId:n.applyToolCallId};return{type:"proposal",kind:t.kind,payload:t.payload,preview:t.preview,applyToolCallId:t.applyToolCallId,proposal:t,id:n.id,metadata:n.metadata}}if(typeof n.type!="string")throw new Error(`Invalid ContentBlock: missing canonical 'type' field (PROTOCOL §7). Received: ${JSON.stringify(n)}`);if(!bo.has(n.type))throw new Error(`Invalid ContentBlock: unknown 'type' "${n.type}" (PROTOCOL §7). Received: ${JSON.stringify(n)}`);return Ao(n),To(n)}function Ao(n){if(n.text===void 0&&typeof n.content=="string")throw new Error(`Invalid ContentBlock: legacy 'content' field is not part of PROTOCOL §7 (use 'text'). Received: ${JSON.stringify(n)}`);if(n.name===void 0&&typeof n.toolName=="string")throw new Error(`Invalid ContentBlock: legacy 'toolName' field is not part of PROTOCOL §7 (use 'name'). Received: ${JSON.stringify(n)}`);if(n.type==="tool_result"&&n.tool_use_id===void 0&&typeof n.toolCallId=="string")throw new Error(`Invalid ContentBlock: tool_result must use 'tool_use_id' (PROTOCOL §7). Received: ${JSON.stringify(n)}`);if(n.is_error===void 0&&n.isError!==void 0)throw new Error(`Invalid ContentBlock: legacy 'isError' field is not part of PROTOCOL §7 (use 'is_error'). Received: ${JSON.stringify(n)}`)}function To(n){switch(n.type){case"text":case"thinking":if(typeof n.text!="string")throw new Error(`Invalid ${n.type} block: required 'text' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"tool_use":if(typeof n.name!="string")throw new Error(`Invalid tool_use block: required 'name' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"tool_result":if(typeof n.tool_use_id!="string")throw new Error(`Invalid tool_result block: required 'tool_use_id' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"image":So(n);break;case"audio":if(typeof n.data!="string"||typeof n.mimeType!="string")throw new Error(`Invalid ${n.type} block: required 'data'/'mimeType' fields missing. Received: ${JSON.stringify(n)}`);break;case"file":if(typeof n.attachmentId!="string"||n.attachmentId.length===0||typeof n.fileName!="string"||n.fileName.length===0)throw new Error(`Invalid file block: required 'attachmentId'/'fileName' fields missing (PROTOCOL §5.5). Received: ${JSON.stringify(n)}`);break;case"code":case"nav-link":case"proposal":break;case"plan":return Io(n)}return{...n}}const Eo=["user","assistant","tool","system","error"];function yr(n){return typeof n=="number"&&Number.isInteger(n)&&n>0}function mr(n){if(!n||typeof n!="object")return null;const e=n;return yr(e.position)?e:null}function Co(n){const{position:e,queueSize:t}=n;return yr(t)&&t>=e?T.shared_mergeQueue_positionOfTotal_label({position:e,total:t}):T.shared_mergeQueue_position_label({position:e})}function Ro(n){if(typeof n!="number"||!Number.isFinite(n)||n<0)return null;const e=Math.max(1,Math.ceil(n/60));return e<60?T.shared_mergeQueue_etaMinutes_label({minutes:e}):T.shared_mergeQueue_etaHours_label({hours:Math.floor(e/60),minutes:e%60})}function Fu(n){const e=mr(n);if(!e)return null;const t=Ro(e.estimatedTimeToMerge),r=Co(e);return t?`${r} · ${t}`:r}const hr=-32602,$t="not-found";function $u(n){if(!n||typeof n!="object"||n.rpcCode!==hr)return!1;const e=n.data;return!e||typeof e!="object"?!1:e.code===$t}function _o(n){if(!n||typeof n!="object")return!1;const{message:e,rpcCode:t,code:r,data:s}=n,o=s&&typeof s=="object"?s.code:void 0;return r===$t||o===$t?!0:t===hr&&typeof e=="string"&&/not found/i.test(e)}function Mo(n){if(n.notificationsMuted===!0||as(n)!=="topLevel"||n.lastMessageRole!=="assistant")return!1;const e=ln(n.lastMessageId);return e===void 0?!1:e!==ln(n.metadata?.lastSeenMessageId)}function ln(n){return typeof n=="string"&&n.length>0?n:void 0}const Po=1e3;async function ut(n,e,t){const r=e??{},s=await n(Object.keys(r).length>0?r:void 0);if(!s||typeof s!="object")return s;const o=s[t];let i=s.nextToken;if(typeof i!="string"||i.length===0)return s;const a=Array.isArray(o)?[...o]:[];for(let c=1;typeof i=="string"&&i.length>0&&!(c>=Po);c+=1){const l=await n({...r,nextToken:i}),d=l&&typeof l=="object"?l[t]:void 0;Array.isArray(d)&&a.push(...d),i=l&&typeof l=="object"?l.nextToken:void 0}return{...s,[t]:a,nextToken:null}}const Wu=1e3,Oo="goal",xo=/^\p{White_Space}*\/goal(?:\p{White_Space}|$)/u;function Gu(n){return xo.test(n)}const No=new Set(["set","updated","unchanged","shown"]),Bo=new Set(["set","updated","unchanged","cleared"]),Lo=new Set(["set","updated","unchanged","shown","cleared"]);function Ge(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Zt(n){return n===null?null:typeof n=="string"?n:void 0}function Qt(n){if(!Ge(n))return;const{principalId:e,displayName:t,login:r}=n;if(!(typeof e!="string"||e.trim().length===0))return{principalId:e,displayName:typeof t=="string"?t:null,login:typeof r=="string"?r:null}}function vr(n,e){const t=n?Qt(e):void 0;return t?{goalSetBy:t}:{}}function jo(n){if(!Ge(n)||!Ge(n.command))return null;const{name:e,action:t,goal:r,goalSetBy:s,noticeMessageId:o}=n.command,i=Zt(r);return e!==Oo||typeof t!="string"||!No.has(t)||i===void 0?null:{action:t,goal:i,...vr(i,s),...typeof o=="string"?{noticeMessageId:o}:{}}}function Do(n){if(!Ge(n))return null;const{action:e,goal:t,goalSetBy:r,noticeMessageId:s}=n,o=Zt(t);return typeof e!="string"||!Bo.has(e)||o===void 0?null:{action:e,goal:o,...vr(o,r),...typeof s=="string"?{noticeMessageId:s}:{}}}function Hu(n){const e=n?.metadata;if(!e||e.type!=="goal_command")return null;const t=e.action;if(typeof t!="string"||!Lo.has(t))return null;const r=Zt(e.goal)??null,s=e.fromPrincipalId;return{action:t,goal:r&&r.length>0?r:null,...typeof s=="string"&&s.length>0?{fromPrincipalId:s}:{}}}function Vu(n){if(!Object.prototype.hasOwnProperty.call(n,"goal"))return{present:!1};const e=n.goal;if(e===null)return{present:!0,goal:void 0,goalSetBy:void 0};if(typeof e=="string"){const t=e.length>0?e:void 0;return{present:!0,goal:t,goalSetBy:t?Qt(n.goalSetBy):void 0}}return{present:!1}}function dn(n){const e=n&&typeof n=="object"&&typeof n.message=="string"?n.message:void 0;if((n&&typeof n=="object"?n.rpcCode:void 0)!==-32602)return{kind:"failed",...e?{message:e}:{}};const r=n.data,s=Ge(r)?r.code:void 0;return s==="goal-too-long"?{kind:"tooLong"}:s==="goal-attachments-not-allowed"?{kind:"attachments"}:s==="agent-retired"?{kind:"retired"}:s==="workspace-retired"?{kind:"workspaceRetired"}:{kind:"invalid",message:e??""}}const Uo="application/vnd.intent.secret-request+json";function qo(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.requestId=="string"&&e.requestId.length>0&&typeof e.agentId=="string"&&typeof e.name=="string"&&e.name.length>0&&typeof e.reason=="string"}function Fo(n){if(!n||typeof n!="object")return!1;const e=n;if(e.type!=="resource")return!1;const t=e.resource;return typeof t=="object"&&t!==null&&t.mimeType===Uo}function zu(n){if(!Fo(n))return null;const e=n.resource.text;if(typeof e!="string")return null;try{const t=JSON.parse(e);return qo(t)?t:null}catch{return null}}function br(n){return!!n&&typeof n=="object"&&typeof n.name=="string"}function kr(n){return br(n)&&typeof n.requestId=="string"}function $o(n){const e=n?.outcome;return kr(n)&&(e==="provided"||e==="declined")}function Wo(n){if(!n||typeof n!="object")return null;const e=n,t=r=>Array.isArray(e[r])?e[r]:[];return{secrets:t("secrets").filter(br).map(({name:r})=>({name:r})),pendingRequests:t("pendingRequests").filter(kr).map(({requestId:r,name:s})=>({requestId:r,name:s})),answeredRequests:t("answeredRequests").filter($o).map(({requestId:r,name:s,outcome:o})=>({requestId:r,name:s,outcome:o}))}}const Go=Ne("DeltaSubscription");function Ho(n,e){if(n!=="subscription.push"||!e||typeof e!="object")return null;const t=e,r=typeof t.subscriptionId=="string"?t.subscriptionId:void 0,s=typeof t.seq=="number"?t.seq:void 0;if(!r||s===void 0)return null;if(t.kind==="snapshot")return{subscriptionId:r,kind:"snapshot",seq:s,snapshot:Array.isArray(t.snapshot)?t.snapshot:[],...typeof t.nextToken=="string"&&t.nextToken.length>0?{nextToken:t.nextToken}:{}};if(t.kind==="delta"){const o=t.delta&&typeof t.delta=="object"?t.delta:{};return{subscriptionId:r,kind:"delta",seq:s,delta:{added:Array.isArray(o.added)?o.added:[],updated:Array.isArray(o.updated)?o.updated:[],removedIds:Array.isArray(o.removedIds)?o.removedIds.map(i=>String(i)):[]}}}return null}class fn{constructor(e,t){y(this,"items",new Map);y(this,"removedSinceSnapshot",new Set);y(this,"changedSinceSnapshot",new Set);y(this,"expectedSeq",0);y(this,"seeded",!1);y(this,"epochValue",0);this.getId=e,this.normalize=t}reset(){this.items.clear(),this.removedSinceSnapshot.clear(),this.changedSinceSnapshot.clear(),this.expectedSeq=0,this.seeded=!1,this.epochValue+=1}get epoch(){return this.epochValue}applySnapshot(e,t){this.items.clear(),this.removedSinceSnapshot.clear(),this.changedSinceSnapshot.clear(),this.epochValue+=1;for(const r of t)this.upsert(r);this.expectedSeq=e+1,this.seeded=!0}applyDelta(e,t){if(!this.seeded||e!==this.expectedSeq)return!1;for(const r of[...t.added??[],...t.updated??[]])if(this.upsert(r),r&&typeof r=="object"){const s=this.getId(r);s&&this.changedSinceSnapshot.add(s)}for(const r of t.removedIds??[])this.items.delete(String(r)),this.removedSinceSnapshot.add(String(r));return this.expectedSeq=e+1,!0}fillFromPage(e){for(const t of e){if(!t||typeof t!="object")continue;const r=this.getId(t);!r||this.items.has(r)||this.removedSinceSnapshot.has(r)||this.upsert(t)}}completeRow(e){const t=this.getId(e);return!t||!this.items.has(t)||this.changedSinceSnapshot.has(t)?!1:(this.upsert(e),!0)}values(){return[...this.items.values()]}upsert(e){if(!e||typeof e!="object")return;const t=e,r=this.getId(t);if(!r)return;const s=this.normalize(t);s!==null&&this.items.set(r,s)}}const Vo=32,zo=1e3,pn=3,Ko=250,Jo=1e3,Yo=3e4;function qe(n){return Math.min(Jo*2**n,Yo)}function Je(n){const{channel:e,getId:t,normalize:r,handler:s}=n,o=e.dynamic,i={...e.params},a=(g,p)=>({subscriptionId:g,...typeof p.workspaceId=="string"?{workspaceId:p.workspaceId}:{}}),c=new fn(t,r);let l=!1,d,m=0,I=0,S=0,h;const w=new Map,R=[],H=g=>{R.push(g),R.length>Vo&&R.shift()},N=g=>{const p=R.filter(f=>f.subscriptionId===g);for(const f of p)R.splice(R.indexOf(f),1);for(const f of p)le(f)},F=()=>{if(!o)return c.values();const g=[];for(const p of w.values())g.push(...p.reconciler.values());return g},B=()=>{l||s(F())},ue=()=>{if(o){for(const g of w.values())if(g.subscriptionId===void 0)return!0;return!1}return d===void 0},$=()=>{R.length>0&&!ue()&&(R.length=0)},U=()=>{if(o)return;h!==void 0&&(clearTimeout(h),h=void 0),m+=1;const g=m;u(e.subscribeMethod,i).then(p=>{const f=p?.subscriptionId;if(g!==m||l){f&&u(e.unsubscribeMethod,a(f,i)).catch(()=>{});return}if(!f){const v=qe(I);I+=1,h=setTimeout(()=>{h=void 0,l||U()},v);return}d=f,I=0,N(f),$()}).catch(()=>{if(g!==m||l)return;const p=qe(I);I+=1,h=setTimeout(()=>{h=void 0,l||U()},p)})},X=()=>{if(o||(m+=1,h!==void 0&&(clearTimeout(h),h=void 0),!d))return;const g=d;d=void 0,u(e.unsubscribeMethod,a(g,i)).catch(()=>{})},D=(g,p)=>{if(!o)return;p.retryTimer!==void 0&&(clearTimeout(p.retryTimer),p.retryTimer=void 0),p.generation+=1;const f=p.generation;u(e.subscribeMethod,p.params).then(v=>{const k=v?.subscriptionId;if(l||w.get(g)!==p||f!==p.generation){k&&u(e.unsubscribeMethod,a(k,p.params)).catch(()=>{});return}if(!k){const E=qe(p.retryAttempt);p.retryAttempt+=1,p.retryTimer=setTimeout(()=>{p.retryTimer=void 0,!l&&w.get(g)===p&&D(g,p)},E);return}p.subscriptionId=k,p.retryAttempt=0,N(k),$()}).catch(()=>{if(l||w.get(g)!==p||f!==p.generation)return;const v=qe(p.retryAttempt);p.retryAttempt+=1,p.retryTimer=setTimeout(()=>{p.retryTimer=void 0,!l&&w.get(g)===p&&D(g,p)},v)})},J=g=>{g.generation+=1,g.retryTimer!==void 0&&(clearTimeout(g.retryTimer),g.retryTimer=void 0);const p=g.subscriptionId;g.subscriptionId=void 0,p&&u(e.unsubscribeMethod,a(p,g.params)).catch(()=>{})},Y=(g,p)=>{p.awaitingResnapshot||(p.awaitingResnapshot=!0,p.seeded=!1,p.reconciler.reset(),J(p),D(g,p),B())},ht=g=>{if(l||!o)return;const p=new Set(g);let f=!1;for(const[v,k]of[...w])p.has(v)||(w.delete(v),J(k),f=!0);for(const v of p){if(w.has(v))continue;const k={generation:0,params:{...o.paramsForId(v)},reconciler:new fn(t,r),seeded:!1,awaitingResnapshot:!1,retryAttempt:0,continuationFailures:0};w.set(v,k),D(v,k),f=!0}f&&B()},Ye=()=>{c.reset(),X(),U()},Le=(g,p,f,v)=>{const k=e.continuation;if(!k)return;const E=g.epoch,C=()=>l||g.epoch!==E;(async()=>{let fe=f;for(let rn=0;fe&&rn<zo;rn+=1){let pe;for(let ge=0;ge<pn;ge+=1){if(ge>0&&(await new Promise(ns=>setTimeout(ns,Ko*2**(ge-1))),C())||(pe=await u(k.method,{...k.params(p),nextToken:fe}).catch(()=>{}),C()))return;if(pe)break}if(!pe){const ge=v.failures();Go.warn(`${k.method} continuation page failed ${pn} times; resubscribing ${e.subscribeMethod} for a fresh snapshot`),v.setFailures(ge+1),setTimeout(()=>{C()||v.resubscribe()},qe(ge));return}const Ze=pe[k.key];g.fillFromPage(Array.isArray(Ze)?Ze:[]),B(),ke(g,Array.isArray(Ze)?Ze:[]),fe=typeof pe.nextToken=="string"&&pe.nextToken?pe.nextToken:null}v.setFailures(0)})()},ke=(g,p)=>{const f=n.complete;if(!f)return;const v=g.epoch;for(const k of p){if(!k||typeof k!="object")continue;const E=f(k);E&&E.then(C=>{l||g.epoch!==v||g.completeRow(C)&&B()}).catch(()=>{})}},le=g=>{if(!l){if(o){for(const[p,f]of w)if(f.subscriptionId===g.subscriptionId){g.kind==="snapshot"?(f.awaitingResnapshot=!1,f.seeded=!0,f.reconciler.applySnapshot(g.seq,g.snapshot??[]),B(),ke(f.reconciler,g.snapshot??[]),g.nextToken&&Le(f.reconciler,f.params,g.nextToken,{failures:()=>f.continuationFailures,setFailures:v=>{f.continuationFailures=v},resubscribe:()=>{w.get(p)===f&&Y(p,f)}})):f.awaitingResnapshot||(f.reconciler.applyDelta(g.seq,g.delta??{})?B():Y(p,f));return}ue()&&H(g);return}if(g.subscriptionId!==d){ue()&&H(g);return}g.kind==="snapshot"?(c.applySnapshot(g.seq,g.snapshot??[]),B(),ke(c,g.snapshot??[]),g.nextToken&&Le(c,i,g.nextToken,{failures:()=>S,setFailures:p=>{S=p},resubscribe:Ye})):c.applyDelta(g.seq,g.delta??{})?B():Ye()}},je=ae(g=>{const p=Ho(g.method,g.params);p&&le(p)}),vt=ce(()=>{if(!l){m+=1,d=void 0,I=0,h!==void 0&&(clearTimeout(h),h=void 0),c.reset(),R.length=0;for(const[g,p]of w)p.generation+=1,p.subscriptionId=void 0,p.seeded=!1,p.awaitingResnapshot=!1,p.retryAttempt=0,p.retryTimer!==void 0&&(clearTimeout(p.retryTimer),p.retryTimer=void 0),p.reconciler.reset(),D(g,p);o||U()}}),de=o?o.subscribeIds(ht):void 0;return o||U(),()=>{l=!0,h!==void 0&&(clearTimeout(h),h=void 0),je(),vt(),de?.(),X();for(const g of w.values())J(g);w.clear()}}const Zo=1e3;function Qo(n){if(!n||typeof n!="object")return;const e=n.nextToken;return typeof e=="string"&&e.length>0?e:void 0}async function Ce(n,e,t){const r=[],s=new Set;let o;for(let i=0;i<Zo;i++){const a=await n(o?{...e,nextToken:o}:e),c=a&&typeof a=="object"?a[t]:void 0;if(Array.isArray(c)&&r.push(...c),o=Qo(a),!o||s.has(o))break;s.add(o)}return r}function Xo(n){const e=new Map,t=[];for(const r of n){const s=r&&typeof r=="object"?r.threadId:void 0;if(typeof s!="string"||!s){t.push(r);continue}e.delete(s),e.set(s,r)}return[...e.values(),...t]}function Ir(n,e){if(!n||typeof n!="object")return null;const t=n;return t.commentsTruncated!==!0||typeof t.threadId!="string"?null:e(t.threadId).then(r=>{if(!r||typeof r!="object")return t;const{rootComment:s,replies:o}=r;if(!s||typeof s!="object"||!Array.isArray(o))return t;const{commentsTruncated:i,...a}=t;return{...a,comments:[s,...o]}},()=>t)}async function ei(n,e,t){const r=Xo(await Ce(n,e,"threads"));return Promise.all(r.map(s=>Ir(s,t)??s))}const ti=1e3;function gn(n){if(!n||typeof n!="object")return;const e="note"in n?n.note:n;return e&&typeof e=="object"?e:void 0}function yn(n){const e=n.nextContentOffset;return n.contentTruncated===!0&&typeof e=="number"&&e>0?e:void 0}async function ni(n,e,t){const r=gn(t);if(!r)return{result:t,retry:!1};let s=yn(r);if(s===void 0)return{result:t,retry:!1};let o=typeof r.content=="string"?r.content:"";for(let S=1;S<ti&&s!==void 0;S++){const h=gn(await n({...e,contentOffset:s}));if(h&&h.rev!==r.rev)return{result:t,retry:!0};if(!h||typeof h.content!="string"||h.contentOffset!==s)return{result:t,retry:!1};o+=h.content,s=yn(h)}if(s!==void 0||new TextEncoder().encode(o).length!==r.contentBytes)return{result:t,retry:!1};const{contentTruncated:i,contentBytes:a,contentOffset:c,nextContentOffset:l,...d}=r,m={...d,content:o};return{result:t&&typeof t=="object"&&"note"in t?{...t,note:m}:m,retry:!1}}async function Sr(n,e){let t;for(let r=0;r<3;r++){t=await n(e);const{result:s,retry:o}=await ni(n,e,t);if(!o)return s}return t}function Q(){const n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():`idk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function _(n){const e=n instanceof Error?n.message:String(n);if(e==="Internal error"&&n&&typeof n=="object"){const t=n.data;if(typeof t=="string"&&t.length>0)return`${e}: ${t}`;if(t&&typeof t=="object"){const r=t.detail;if(typeof r=="string"&&r.length>0)return`${e}: ${r}`}}return e}const ri=-32005;function lt(n){if(!n||typeof n!="object"||n.rpcCode!==ri)return;const e=n.data;if(!(!e||typeof e!="object")&&e.code==="conflict")return{current:e.current}}function si(n){if(!n||typeof n!="object")return;const e=n.noteRev;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function oi(n){if(!n||typeof n!="object")return;const{newContent:e,rev:t}=n;if(typeof e=="string")return typeof t=="number"&&Number.isFinite(t)?{newContent:e,rev:t}:{newContent:e}}async function b(n,e,t){try{const r=await(t!==void 0?u(n,e,t):u(n,e)),s=oi(r),o=si(r)??s?.rev;return{success:!0,...o!==void 0?{noteRev:o}:{},...s!==void 0?{newContent:s.newContent}:{}}}catch(r){const s=lt(r);return s?{success:!1,error:_(r),conflict:s}:ii(r)?{success:!1,error:_(r),contentBaseMismatch:!0}:{success:!1,error:_(r)}}}function ii(n){if(!n||typeof n!="object"||n.rpcCode!==-32602)return!1;const e=n.data;return!!e&&typeof e=="object"&&e.code==="content-base-mismatch"}function ai(n){if(!n||typeof n!="object")return;const e=n,t=e.id;if(typeof t=="string"&&t.length>0)return t;for(const r of["task","note","entity"]){const s=e[r];if(s&&typeof s=="object"){const o=s.id;if(typeof o=="string"&&o.length>0)return o}}}async function Wt(n,e,t){try{const r=await(t!==void 0?u(n,e,t):u(n,e)),s=ai(r);return s!==void 0?{success:!0,id:s}:{success:!0}}catch(r){const s=lt(r);return s?{success:!1,error:_(r),conflict:s}:{success:!1,error:_(r)}}}const ci=2e3;let Re=null,Ae=null;function ui(n,e){console.debug(`[live-support] workspace.list RPC (${n})${e?`: ${e}`:""}`)}function wr(n,e){if(Ae)return Ae;ui(n,e);const t=ut(r=>u("workspace.list",r),void 0,"workspaces").then(r=>{const o=(Array.isArray(r?.workspaces)?r.workspaces:[]).map(i=>String(i.id??i.workspaceId??"")).filter(i=>i.length>0);return Re={ids:o,fetchedAt:Date.now()},o});return Ae=t,t.catch(()=>{}).finally(()=>{Ae===t&&(Ae=null)}),t}async function li(n){return x!==null?[...x]:Re!==null&&Date.now()-Re.fetchedAt<ci?[...Re.ids]:wr(n)}const di=["workspace:created","workspace:updated","workspace:deleted"],fi=250;let x=null,Te=0;const dt=new Map;let pi=0,Ct=null,Rt=null,oe=0,Gt=!1,Ee=!1,_e;function Xt(){const n=x?[...x]:[];for(const e of dt.values())e(n)}function Ar(n,e){Gt=!0;const t=oe;Ae!==null&&(Ee=!0),wr(n,e).then(r=>{oe!==t&&(Te===0||(Ee=!0,x!==null))||(x=new Set(r),oe+=1,Xt())}).catch(()=>{if(x===null)for(const r of dt.values())r([])}).finally(()=>{Gt=!1,Ee&&(Ee=!1,_e=setTimeout(()=>{_e=void 0,Te>0&&Ar("follow-up")},fi))})}function se(n,e){if(_e===void 0){if(Gt){Ee=!0;return}Ar(n,e)}}function mn(n){if(!x){oe+=1,se("defensive-resync","workspace event before seed settled");return}x.has(n)||(x.add(n),oe+=1,Re=null,Xt())}function hn(n){if(!x){oe+=1,se("defensive-resync","workspace event before seed settled");return}x.has(n)&&(x.delete(n),oe+=1,Re=null,Xt())}function gi(n){if(!n||typeof n!="object")return;const e=n.event;return e&&typeof e=="object"?e.data:n.data}function vn(n){if(!n||typeof n!="object")return;const e=n;if(typeof e.workspaceId=="string"&&e.workspaceId.length>0)return e.workspaceId;const t=e.workspace;if(t&&typeof t=="object"){const r=t.id;if(typeof r=="string"&&r.length>0)return r}}function yi(n){if(!n||typeof n!="object")return!1;const e=n.workspace;return!e||typeof e!="object"?!1:e.archived===!0}function mi(n,e){if(!bi(n,e,di))return;const t=Er(e);if(t===void 0){se("defensive-resync","typeless event payload");return}const r=gi(e);if(t==="workspace:created"){const s=vn(r);if(!s){se("defensive-resync",`${t} without workspace id`);return}if(yi(r))return;mn(s);return}if(t==="workspace:deleted"){const s=vn(r);if(!s){se("defensive-resync",`${t} without workspace id`);return}hn(s);return}if(t==="workspace:updated"){const s=r&&typeof r=="object"?r:void 0,o=typeof s?.workspaceId=="string"?s.workspaceId:void 0,i=s?.changes;if(!o||!i||typeof i!="object"){se("defensive-resync",`${t} without workspaceId/changes`);return}const a=i.archived;a===!0?hn(o):a===!1&&mn(o)}}function en(n){let e=!1;Te+=1;const t=pi++;return dt.set(t,n),Te===1?(Ct=ae(r=>mi(r.method,r.params)),Rt=ce(()=>se("reconnect")),se("seed")):x!==null&&n([...x]),()=>{e||(e=!0,dt.delete(t),Te-=1,!(Te>0)&&(Ct?.(),Ct=null,Rt?.(),Rt=null,_e!==void 0&&(clearTimeout(_e),_e=void 0),Ee=!1,x=null,oe+=1))}}const Tr=new Map;function He(n,e){n&&e&&(Tr.set(n,e),ft.delete(n))}const hi=5e3,ft=new Map,_t=new Map;async function vi(n){let e;try{e=await li("resolver")}catch{return null}let t=!0;for(const r of e)try{const s=a=>u("note.list",a);let o;try{o=await Ce(s,{workspaceId:r,projection:"slim",limit:ve},"notes")}catch(a){if(!cr(a))throw a;o=await Ce(s,{workspaceId:r,limit:ve},"notes")}let i=!1;for(const a of o){const c=String(a.id??"");c&&He(c,r),c===n&&(i=!0)}if(i)return r}catch{t=!1}return t&&e.length>0&&ft.set(n,Date.now()),null}async function ie(n){const e=Tr.get(n);if(e)return e;const t=ft.get(n);if(t!==void 0){if(Date.now()-t<hi)return null;ft.delete(n)}const r=_t.get(n);if(r)return r;const s=vi(n).finally(()=>{_t.delete(n)});return _t.set(n,s),s}function Er(n){if(!n||typeof n!="object")return;const e=n.event;if(e&&typeof e=="object"){const r=e.type;if(typeof r=="string")return r}const t=n.type;return typeof t=="string"?t:void 0}function bi(n,e,t){if(n!=="events.event")return!1;const r=Er(e);return r===void 0?!0:t.includes(r)}const Cr=new Map,ki=41943040,Ii=/^response for agent\.getConversation exceeds maximum outbound frame size: ([1-9][0-9]*) bytes > 41943040 bytes$/;function Si(n){if(!n||typeof n!="object")return!1;const e=n;if(e.name!=="BackendError"||typeof e.message!="string")return!1;const t=Ii.exec(e.message);return t!==null&&Number(t[1])>ki}function wi(n,e){n&&e&&Cr.set(n,e)}function Qe(n){const e=new Date().toISOString(),t=String(n.id??""),r=n.acpSessionId?String(n.acpSessionId):null,s=String(n.workspaceId??"");wi(t,s);const o={...n,id:It(t),backendSessionId:r?It(r):null,workspaceId:ur(s),name:String(n.name??t),status:typeof n.status=="string"?n.status:cs.Pending,messages:Array.isArray(n.messages)?n.messages:[],createdAt:String(n.createdAt??e),updatedAt:String(n.updatedAt??e)};return typeof n.retiredAt=="string"&&n.retiredAt.length>0&&(o.retiredAt=n.retiredAt),typeof n.parentAgentId=="string"&&n.parentAgentId.length>0&&(o.parentAgentId=It(n.parentAgentId)),o.usingEarlierProfileSettings=n.usingEarlierProfileSettings===!0?!0:void 0,o.goal=typeof n.goal=="string"&&n.goal.length>0?n.goal:void 0,o.goalSetBy=o.goal?Qt(n.goalSetBy):void 0,o.providerReplacementRequired=Ai(n.providerReplacementRequired),o.permissionPolicy=typeof n.permissionPolicy=="string"||n.permissionPolicy===null?n.permissionPolicy:void 0,o.effectivePermissionPolicy=typeof n.effectivePermissionPolicy=="string"?n.effectivePermissionPolicy:void 0,typeof n.isBackground=="boolean"&&(o.metadata={...o.metadata,isBackground:n.isBackground},o.agentMetadata&&(o.agentMetadata={...o.agentMetadata,isBackground:n.isBackground})),o.hasUnread=Mo(o),o}function Ai(n){if(!n||typeof n!="object")return;const{providerRef:e,reason:t}=n;if(!(typeof e!="string"||e.length===0)&&!(t!=="profile-missing"&&t!=="provider-disabled"))return{providerRef:e,reason:t}}function Ti(n){if(!n||typeof n!="object")return;const{topLevel:e,delegated:t,background:r}=n;if(!(typeof e!="number"||typeof t!="number"||typeof r!="number"))return{topLevel:e,delegated:t,background:r}}function Ei(n){if(!n||typeof n!="object")return;const{running:e,byParent:t,orphaned:r}=n;if(typeof e!="number"||!t||typeof t!="object"||Array.isArray(t))return;const s={};for(const[i,a]of Object.entries(t)){const c=bn(a);if(!c)return;s[i]=c}if(r===void 0)return{running:e,byParent:s};const o=bn(r);if(o)return{running:e,byParent:s,orphaned:o}}function bn(n){if(!n||typeof n!="object")return;const{total:e,running:t}=n;if(!(typeof e!="number"||typeof t!="number"))return{total:e,running:t}}async function kn(n,e){try{return await u(n,e),{ok:!0}}catch(t){const r=t?.data,s=!!r&&typeof r=="object"&&r.code==="secret-request-unknown",o=t instanceof Error?t.message:String(t);return{ok:!1,expired:s,error:o}}}class Ci{constructor(){y(this,"retirementCapabilityRequest",null)}supportsRetirement(e=0){if(this.retirementCapabilityRequest?.generation!==e){const t=u("client.hello",{}).then(r=>r?.server?.capabilities?.agentRetire===1).catch(()=>!1).finally(()=>{this.retirementCapabilityRequest?.promise===t&&(this.retirementCapabilityRequest=null)});this.retirementCapabilityRequest={generation:e,promise:t}}return this.retirementCapabilityRequest.promise}async list(e,t){const{agents:r}=await this.listWithMeta(e,t);return r}async listWithMeta(e,t){const r={workspaceId:e};t?.retiredOnly&&(r.retiredOnly=!0),t?.scope&&t.scope!=="all"&&(r.scope=t.scope),t?.parentAgentId&&(r.parentAgentId=t.parentAgentId),t?.orphanedOnly&&(r.orphanedOnly=!0);const s=await ut(c=>u("agent.list",c),r,"agents"),o=Array.isArray(s?.agents)?s.agents:[],i=Ti(s?.scopeCounts),a=Ei(s?.delegatedCounts);return{agents:o.map(c=>Qe(c)),retiredCount:typeof s?.retiredCount=="number"?s.retiredCount:0,...i?{scopeCounts:i}:{},...a?{delegatedCounts:a}:{}}}async get(e,t){const r=await u("agent.get",{agentId:e,...t!==void 0?{workspaceId:t}:{}}),s=r&&typeof r=="object"&&"agent"in r?r.agent:r;return!s||typeof s!="object"?null:Qe(s)}async getConversation(e,t=is,r,s,o,i){let a=t,c;for(;;){const d={agentId:e,...i!==void 0?{workspaceId:i}:{},limit:a,projection:"slim"};r!==void 0&&(d.nextToken=r),s!==void 0&&(d.aroundMessageId=s),o!==void 0&&(d.aroundIndex=o);try{c=await u("agent.getConversation",d);break}catch(m){if(!Si(m)||!Number.isFinite(a)||a<=1)throw m;a=Math.max(1,Math.floor(a/2))}}return!c||typeof c!="object"?{messages:[],truncated:!1,totalMessages:0,nextToken:null,prevToken:null}:{messages:Array.isArray(c.messages)?c.messages:[],truncated:!!c.truncated,totalMessages:typeof c.totalMessages=="number"?c.totalMessages:0,nextToken:typeof c.nextToken=="string"?c.nextToken:null,prevToken:typeof c.prevToken=="string"?c.prevToken:null}}async getMessageBlock(e,t,r,s){const i=(await u("agent.getMessageBlock",{agentId:e,messageId:t,blockId:r,...s!==void 0?{workspaceId:s}:{}}))?.block;if(!an(i))throw new Error(`agent.getMessageBlock returned no block for message ${t} block ${r}`);return i}async getMessageBlockPage(e,t,r,s,o){const i=await u("agent.getMessageBlock",{agentId:e,messageId:t,blockId:r,...s!==void 0?{workspaceId:s}:{},...o!==void 0?{offset:o}:{}}),a=i?.block;if(!an(a))throw new Error(`agent.getMessageBlock returned no block for message ${t} block ${r}`);const c=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null;return{block:a,truncated:i.truncated===!0,field:typeof i.field=="string"?i.field:null,encoding:i.encoding==="text"||i.encoding==="json"?i.encoding:null,totalBytes:c(i.totalBytes),nextOffset:c(i.nextOffset)}}async listUserMessages(e,t,r,s){const o={agentId:e,...r!==void 0?{workspaceId:r}:{}};t!==void 0&&(o.previewChars=t),s?.limit!==void 0&&(o.limit=s.limit),s?.nextToken!==void 0&&(o.nextToken=s.nextToken);try{const i=await u("agent.listUserMessages",o),c=(Array.isArray(i?.items)?i.items:[]).filter(m=>!!m&&typeof m=="object").map(m=>{const I={id:String(m.id??""),preview:String(m.preview??""),createdAt:String(m.createdAt??"")};return m.metadata&&typeof m.metadata=="object"&&(I.metadata=m.metadata),I}),l=typeof i?.total=="number"?i.total:c.length,d=i?.nextToken;return typeof d=="string"||d===null?{ok:!0,items:c,total:l,nextToken:d}:{ok:!0,items:c,total:l}}catch(i){return{ok:!1,unsupported:!!i&&typeof i=="object"&&"rpcCode"in i&&i.rpcCode===-32601,error:i instanceof Error?i.message:String(i)}}}async create(e){const t={workspaceId:e.workspaceId,idempotencyKey:Q()};e.placement!==void 0&&(t.placement=e.placement),e.model!==void 0&&(t.model=e.model),e.reasoningEffort!==void 0&&(t.reasoningEffort=e.reasoningEffort),e.rememberSpecialist!==void 0&&(t.rememberSpecialist=e.rememberSpecialist),e.specialist!==void 0&&(e.specialist!==null||e.rememberSpecialist)&&(t.specialistId=e.specialist),e.prompt!==void 0&&(t.behaviorPrompt=e.prompt),e.name!==void 0&&(t.name=e.name),e.nameExplicitlySet!==void 0&&(t.nameExplicitlySet=e.nameExplicitlySet),e.provider!==void 0&&(t.provider=e.provider),e.agentType!==void 0&&(t.agentType=e.agentType),e.metadata!==void 0&&(t.metadata=e.metadata),e.workspacePath!==void 0&&(t.workspacePath=e.workspacePath),e.workspaceContext!==void 0&&(t.workspaceContext=e.workspaceContext);const r=await u("agent.create",t),s=r&&typeof r=="object"&&"agent"in r?r.agent:r;if(!s||typeof s!="object")throw new Error("agent.create returned no agent object");const o=s.id;if(typeof o!="string"||o.length===0)throw new Error("agent.create response missing daemon-assigned agent.id");return Qe(s)}async send(e,t,r){if(r??=await this.resolveAgentWorkspaceId(e)??void 0,!r)return{success:!1,error:`Unknown workspace for agent ${e}`};const s=Q();return b("agent.sendMessage",{agentId:e,content:t,workspaceId:r,messageId:s})}async editAndRegenerate(e){const t={agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId,content:e.content};return e.model!==void 0&&(t.model=e.model),e.imageBlocks!==void 0&&(t.imageBlocks=e.imageBlocks),e.fileBlocks!==void 0&&(t.fileBlocks=e.fileBlocks),b("agent.editAndRegenerate",t)}async queue(e,t,r){try{const s={agentId:e,content:t,...r?.workspaceId!==void 0?{workspaceId:r.workspaceId}:{}};r?.messageId!==void 0&&(s.messageId=r.messageId),r?.imageBlocks!==void 0&&(s.imageBlocks=r.imageBlocks),r?.fileBlocks!==void 0&&(s.fileBlocks=r.fileBlocks),r?.messageMetadata!==void 0&&(s.messageMetadata=r.messageMetadata);const o=await u("agent.queueMessage",s);if(o?.success===!1)return{success:!1,error:o.error};const i=o?.queuedMessage,a=typeof o?.turnId=="string"?o.turnId:typeof i?.turnId=="string"?i.turnId:void 0,c={success:!0};return i&&(c.queuedMessage=i),a!==void 0&&(c.turnId=a),c}catch(s){const o=s&&typeof s=="object"?s.rpcCode:void 0,i=o===-32600||o===-32601||o===-32602||on(s);if(r?.messageId!==void 0&&!i)throw s;return{success:!1,error:s instanceof Error?s.message:String(s)}}}async editQueued(e,t,r,s,o){try{const i={agentId:e,messageId:t,content:r,...o!==void 0?{workspaceId:o}:{}};s!==void 0&&(i.editing=s);const c=(await u("agent.editQueuedMessage",i))?.queuedMessage;return c?{success:!0,queuedMessage:c}:{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async sendQueuedNow(e){try{const t=await u("agent.sendQueuedMessageNow",{agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId});return{success:t.success,queued:t.queued,...t.quarantined!==void 0?{quarantined:t.quarantined}:{},...t.queuedMessage?{queuedMessage:t.queuedMessage}:{},...!t.queued&&t.turnId?{turnId:t.turnId}:{}}}catch(t){return{success:!1,error:_(t)}}}async sendQueuedMessagesNow(e){try{const r=(await u("client.hello",{}))?.server?.protocolVersion,s=typeof r=="string"?/^(\d+)\.(\d+)(?:\.\d+)?$/.exec(r):null;if(!s||Number(s[1])<13||Number(s[1])===13&&Number(s[2])<1)return{success:!1,error:T.chat_queuedMessages_sendAllUnsupported_error()};const o=await u("agent.sendQueuedMessagesNow",{agentId:e.agentId,workspaceId:e.workspaceId,messageIds:e.messageIds});return{success:o.success,queued:o.queued,messageIds:o.messageIds,...o.quarantined!==void 0?{quarantined:o.quarantined}:{},...!o.queued&&!o.quarantined&&o.turnId?{turnId:o.turnId}:{}}}catch(t){return{success:!1,error:_(t)}}}async getQueue(e,t){const r=await ut(s=>u("agent.getQueue",s),{agentId:e,...t!==void 0?{workspaceId:t}:{}},"queue");return Array.isArray(r?.queue)?r.queue:[]}async removeQueued(e,t,r){return b("agent.removeQueuedMessage",{agentId:e,messageId:t,...r!==void 0?{workspaceId:r}:{}})}async stop(e,t){return b("agent.stop",{agentId:e,...t!==void 0?{workspaceId:t}:{}})}async cancelSubscriptions(e){const t={agentId:e.agentId,workspaceId:e.workspaceId};return e.subscriptionId!==void 0&&(t.subscriptionId=e.subscriptionId),e.groupId!==void 0&&(t.groupId=e.groupId),b("agent.cancelSubscriptions",t)}async dismissQuestions(e){return b("agent.dismissQuestions",{agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId})}async secretList(e){try{return Wo(await u("secret.list",{workspaceId:e.workspaceId,agentId:e.agentId}))}catch{return null}}async secretProvide(e){return kn("secret.provide",{workspaceId:e.workspaceId,requestId:e.requestId,value:e.value})}async secretDismiss(e){return kn("secret.dismiss",{workspaceId:e.workspaceId,requestId:e.requestId})}async resolveProposal(e){const t={workspaceId:e.workspaceId,agentId:e.agentId,proposalId:e.proposalId,outcome:e.outcome};return e.detail!==void 0&&(t.detail=e.detail),b("agent.resolveProposal",t)}async resolveRpcProposal(e){try{const t=await u("agent.resolveRpcProposal",{workspaceId:e.workspaceId,agentId:e.agentId,proposalId:e.proposalId,decision:e.decision},{timeoutMs:66e4});return{success:!0,outcome:t?.outcome==="applied"?"applied":"dismissed",items:Array.isArray(t?.items)?t.items:[],...t?.expired?{expired:!0}:{}}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async markSeen(e){return b("agent.markSeen",{workspaceId:e.workspaceId,agentId:e.agentId,messageId:e.messageId})}async setReasoningEffort(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{reasoningEffort:e.reasoningEffort}})}async setNotificationsMuted(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{notificationsMuted:e.notificationsMuted}})}async setPinned(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{pinned:e.pinned}})}async sendGoalCommand(e){try{const t=await u("agent.sendMessage",{agentId:e.agentId,workspaceId:e.workspaceId,content:e.content,interpretCommands:!0});if(t&&typeof t=="object"&&t.success===!1){const r=t.error;return{ok:!1,error:{kind:"failed",...typeof r=="string"?{message:r}:{}}}}return{ok:!0,command:jo(t)}}catch(t){return{ok:!1,error:dn(t)}}}async setGoal(e){try{const t=Do(await u("agent.setGoal",{agentId:e.agentId,workspaceId:e.workspaceId,goal:e.goal}));return t?{ok:!0,result:t}:{ok:!1,error:{kind:"failed"}}}catch(t){return{ok:!1,error:dn(t)}}}async setPermissionPolicy(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{permissionPolicy:e.permissionPolicy}})}async setBackground(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{isBackground:e.isBackground}})}async updateSpecialist(e){const t={specialist:e.specialist};e.rememberSpecialist!==void 0&&(t.rememberSpecialist=e.rememberSpecialist),e.model!==void 0&&(t.model=e.model),e.systemPrompt!==void 0&&(t.systemPrompt=e.systemPrompt);const r={agentId:e.agentId,workspaceId:e.workspaceId,changes:t};try{return await u("agent.update",r),{success:!0}}catch(s){if(e.rememberSpecialist!==void 0&&s?.rpcCode===-32602&&_(s).includes("agent.update: unknown field `rememberSpecialist` in `changes`")){const o={...t};return delete o.rememberSpecialist,b("agent.update",{...r,changes:o})}return{success:!1,error:_(s)}}}async rename(e,t,r,s){const o={agentId:e,name:t,...r!==void 0?{workspaceId:r}:{}};return s?.skipIfExplicitlySet===!0&&(o.skipIfExplicitlySet=!0),b("agent.rename",o)}async delete(e,t,r){const s=r?.undoDelayMs;try{const o=await u("agent.delete",{agentId:e,...t!==void 0?{workspaceId:t}:{},...s&&s>0?{undoDelayMs:s}:{}}),i=o?.scheduled===!0,a=typeof o?.deleteAt=="string"?o.deleteAt:void 0;return i&&a?{success:!0,scheduled:!0,deleteAt:a}:{success:!0}}catch(o){return on(o)?{success:!1,forbidden:!0,error:_(o)}:{success:!1,error:_(o)}}}async cancelDelete(e,t){try{return{success:!0,cancelled:(await u("agent.cancelDelete",{agentId:e,...t!==void 0?{workspaceId:t}:{}}))?.cancelled===!0}}catch(r){return{success:!1,error:_(r)}}}async retire(e,t){const r={agentId:e};t!==void 0&&(r.workspaceId=t);try{return await u("agent.retire",r)}catch(s){return{success:!1,error:_(s)}}}async restore(e,t){const r={agentId:e,...t!==void 0?{workspaceId:t}:{}};return b("agent.restore",r)}async retry(e,t){try{const r=await u("agent.retry",{agentId:e,workspaceId:t});if(r?.ok!==!0)return{ok:!1,error:"Agent not in error status"};const s=typeof r.redriven=="boolean"?r.redriven:void 0,o=typeof r.turnId=="string"?r.turnId:void 0;return o!==void 0?{ok:!0,redriven:s,turnId:o}:{ok:!0,redriven:s}}catch(r){const s=r instanceof Error?r.message:"Failed to retry agent spawn";return _o(r)?{ok:!1,notFound:!0,error:s}:{ok:!1,error:s}}}async respondPermission(e,t,r){try{const s=await u("agent.respondPermission",{requestId:e,outcome:t,...r!==void 0?{workspaceId:r}:{}}),o=typeof s?.resolved=="boolean"?s.resolved:void 0;return o!==void 0?{success:!0,resolved:o}:{success:!0}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async listInterrupted(){try{const e=await u("agent.listInterrupted",{});return(Array.isArray(e?.agents)?e.agents:[]).map(r=>{const s=r;return{agentId:String(s.agentId??""),workspaceId:String(s.workspaceId??""),workspaceName:String(s.workspaceName??""),agentName:String(s.agentName??""),prevStatus:String(s.prevStatus??""),interruptedAt:String(s.interruptedAt??"")}})}catch(e){if(e&&typeof e=="object"&&"rpcCode"in e&&e.rpcCode===-32601)return[];throw e}}async resolveInterrupted(e){try{const t=await u("agent.resolveInterrupted",e);return{resumed:Array.isArray(t?.resumed)?t.resumed:[],abandoned:Array.isArray(t?.abandoned)?t.abandoned:[],failed:Array.isArray(t?.failed)?t.failed.map(r=>{const s=r;return{agentId:String(s.agentId??""),error:String(s.error??"")}}):[]}}catch(t){throw t}}async resolveAgentWorkspaceId(e){const t=Cr.get(e);if(t)return t;const r=await this.get(e);if(!r)return null;const s=String(r.workspaceId??"");return s.length>0?s:null}subscribe(e){return Je({channel:{subscribeMethod:"agent.subscribe",unsubscribeMethod:"events.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t})},continuation:{method:"agent.list",key:"agents",params:t=>({workspaceId:t.workspaceId})}},getId:t=>String(t.id??""),normalize:t=>Qe(t),handler:e})}}function Ri(n){return`browser-recent-${n}`}function _i(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.url=="string"&&typeof e.lastVisited=="string"&&(e.title===void 0||typeof e.title=="string")&&(e.favicon===void 0||typeof e.favicon=="string")}function Ku(n){const e=n?.target;return K(e)&&typeof e.clientId=="string"&&e.clientId.length>0&&typeof e.via=="string"?{clientId:e.clientId,via:e.via}:void 0}function K(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function In(n){return K(n)&&n.ok===!0}function Mi(n){return K(n)&&typeof n.action=="string"&&typeof n.success=="boolean"&&(n.error===void 0||typeof n.error=="string")}function Pi(n){return K(n)&&typeof n.clientId=="string"&&K(n.capabilities)&&typeof n.connections=="number"&&Array.isArray(n.transports)&&typeof n.connectedAt=="string"}function Ju(n){return K(n)&&typeof n.clientId=="string"&&K(n.capabilities)}function Oi(n){if(!K(n))return!1;if(n.source==="workspace"){if(typeof n.clientId!="string")return!1}else if(n.source==="default"){if(n.clientId!==void 0)return!1}else return!1;const e=n.resolved;return e===null||K(e)&&typeof e.clientId=="string"}function Rr(n){return K(n)&&typeof n.tabId=="string"&&typeof n.workspaceId=="string"&&typeof n.hostClientId=="string"&&typeof n.url=="string"&&(n.visibility==="visible"||n.visibility==="hidden")&&typeof n.createdAt=="string"&&typeof n.updatedAt=="string"}function xi(n){return Rr(n)&&typeof n.hostConnected=="boolean"}function Ni(n){const e=us.getJSON(Ri(n));return Array.isArray(e)?e.filter(t=>_i(t)).slice(0,ls):[]}class Bi{async recentUrls(e){return Ni(e)}subscribe(e){return e([]),()=>{}}async listTabs(e){const t=await u("browser.listTabs",{workspaceId:e});if(!Array.isArray(t?.tabs)||!t.tabs.every(xi))throw new Error("Invalid browser.listTabs response shape");return t.tabs}async upsertTab(e,t){const r=await u("browser.upsertTab",{workspaceId:e,tab:t});if(!Rr(r?.tab))throw new Error("Invalid browser.upsertTab response shape");return r.tab}async removeTab(e){const t=await u("browser.removeTab",{tabId:e});if(!In(t))throw new Error("Invalid browser.removeTab response shape");return t}async syncTabs(e){const t=await u("browser.syncTabs",{tabs:e});if(!Array.isArray(t?.drop)||!t.drop.every(r=>typeof r=="string"))throw new Error("Invalid browser.syncTabs response shape");return{drop:t.drop}}async navigateTab(e,t){const r=await u("browser.navigateTab",{tabId:e,url:t});if(!Mi(r))throw new Error("Invalid browser.navigateTab response shape");return r}async closeTab(e,t){const r=await u("browser.closeTab",{tabId:e,...t?.force===void 0?{}:{force:t.force}});if(!In(r))throw new Error("Invalid browser.closeTab response shape");return r}}var _r=(n=>(n.AGENT="agent",n))(_r||{}),re,q,ze,z,gt,yt,mt,Pe,Ke,Ht;class Li{constructor(){V(this,Ke);V(this,re);V(this,q,Vs(zs([])));V(this,ze,1e3);V(this,z,[]);V(this,gt,100);V(this,yt,5e3);V(this,mt,null);V(this,Pe,!1);Ie(this,re,new Ks("Renderer",{enableConsole:!0})),typeof window<"u"&&window.electronAPI&&Ie(this,Pe,!0),A(this,Pe)&&Ie(this,mt,setInterval(()=>{kt(this,Ke,Ht).call(this)},A(this,yt)))}get logs(){return ye(A(this,q))}addToStore(e){At(A(this,q),[...ye(A(this,q)),e],!0),ye(A(this,q)).length>A(this,ze)&&At(A(this,q),ye(A(this,q)).slice(-A(this,ze)),!0)}addToPendingLogs(e){A(this,z).push(e),A(this,z).length>=A(this,gt)&&kt(this,Ke,Ht).call(this)}error(e,t,r,s){const o={timestamp:new Date().toISOString(),level:"ERROR",category:e,message:t,context:s,error:r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:void 0};A(this,re).error(t,r instanceof Error?r:void 0,s),this.addToStore(o),this.addToPendingLogs(o)}warn(e,t,r){const s={timestamp:new Date().toISOString(),level:"WARN",category:e,message:t,context:r};A(this,re).warn(t,r),this.addToStore(s),this.addToPendingLogs(s)}info(e,t,r){const s={timestamp:new Date().toISOString(),level:"INFO",category:e,message:t,context:r};A(this,re).info(t,r),this.addToStore(s),this.addToPendingLogs(s)}debug(e,t,r){const s={timestamp:new Date().toISOString(),level:"DEBUG",category:e,message:t,context:r};A(this,re).debug(t,r),this.addToStore(s),this.addToPendingLogs(s)}verbose(e,t,r){this.debug(e,t,r)}getLogs(){return[...ye(A(this,q))]}getLogsByCategory(e){return ye(A(this,q)).filter(t=>t.category===e)}getLogsByLevel(e){return ye(A(this,q)).filter(t=>t.level===e.toUpperCase())}clearLogs(){At(A(this,q),[],!0)}}re=new WeakMap,q=new WeakMap,ze=new WeakMap,z=new WeakMap,gt=new WeakMap,yt=new WeakMap,mt=new WeakMap,Pe=new WeakMap,Ke=new WeakSet,Ht=async function(){if(A(this,z).length===0||!A(this,Pe))return;const e=[...A(this,z)];Ie(this,z,[]);try{await ee(Js.PERSIST_RENDERER_LOGS,e)}catch(t){console.error("[RendererLogger] Failed to persist logs via IPC:",t),Ie(this,z,[...e,...A(this,z)])}};const ji=new Li,Di=2048,Ui=256;let Sn=0,wn=0,An=0;const qi=192,Fi=64;function $i(n){if(n.stage==="render"&&(n.event.includes("not-committed")||n.terminalErrorVisible===!0||n.callbackResult==="ignored"||n.callbackResult==="threw"))return"render";if(n.callbackResult==="threw"||n.storeStreamState==="error"||n.event.includes("failed")||n.event.includes("error")||n.pushKind==="snapshot"&&(n.callbackResult==="ignored"||n.callbackResult==="buffered")&&n.event.startsWith("snapshot-"))return"failure"}function Tn(n){if(!n)return;let e=0xcbf29ce484222325n;for(const t of new TextEncoder().encode(n))e^=BigInt(t),e=BigInt.asUintN(64,e*0x100000001b3n);return e.toString(16).padStart(16,"0")}function L(n){const e=Di-Ui;if(Sn<e)Sn+=1;else{const t=$i(n);if(t==="failure"&&wn<qi)wn+=1;else if(t==="render"&&An<Fi)An+=1;else return}ji.info(_r.AGENT,"stream-lifecycle",n)}const Wi={messages:[],truncated:!1,totalMessages:0},En=5e3,Cn=1e3,Gi=3e4,Hi=256,Vi=new Set(Eo),zi=new Set(["text","code","tool_use","tool_result","thinking","image","audio","file","nav-link","proposal","plan"]);function G(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){if(!G(n))return null;const{target:e,received:t,complete:r}=n;return typeof e!="number"||!Number.isSafeInteger(e)||e<1||e>200||typeof t!="number"||!Number.isSafeInteger(t)||t<0||t>e||typeof r!="boolean"?null:{target:e,received:t,complete:r}}function Mr(n){if(!G(n))return null;try{return wo(n)}catch{return typeof n.type!="string"||n.type.length===0||zi.has(n.type)?null:{...n}}}function Pr(n,e){if(!G(n)||typeof n.id!="string"||n.id.length===0||typeof n.role!="string"||!Vi.has(n.role)||typeof n.timestamp!="string"||n.timestamp.length===0)return null;const t=n.agentId===void 0?e:n.agentId;if(t!==void 0&&(typeof t!="string"||t.length===0)||e!==void 0&&t!==void 0&&t!==e||n.seq!==void 0&&(typeof n.seq!="number"||!Number.isSafeInteger(n.seq)||n.seq<0))return null;const r=Array.isArray(n.contentBlocks)?n.contentBlocks.map(Mr).filter(s=>s!==null):[];return{...n,...t===void 0?{}:{agentId:t},contentBlocks:r}}function Or(n,e){if(!G(n))return Wi;const t=n.agentId===void 0?e:n.agentId,r=t===void 0||typeof t=="string"&&t.length>0&&(e===void 0||t===e);return{messages:Array.isArray(n.messages)?r?n.messages.map(o=>Pr(o,t)).filter(o=>o!==null):[]:[],...n.nextToken===null||typeof n.nextToken=="string"?{nextToken:n.nextToken}:{},truncated:!!n.truncated,totalMessages:typeof n.totalMessages=="number"?n.totalMessages:0}}function Ki(n){if(!n||typeof n!="object")return;const e=n.resumed;return typeof e=="boolean"?e:void 0}function Ji(n,e){if(n!=="subscription.push"||!e||typeof e!="object")return null;const t=e,r=typeof t.subscriptionId=="string"?t.subscriptionId:null,s=typeof t.seq=="number"?t.seq:null;if(!r||s===null||!Number.isSafeInteger(s)||s<0)return null;if(t.kind==="snapshot")return{subscriptionId:r,kind:"snapshot",seq:s,snapshot:t.snapshot};if(t.kind==="history")return{subscriptionId:r,kind:"history",seq:s,history:t.history};if(t.kind==="delta"){const o=t.delta&&typeof t.delta=="object"?t.delta:{};return{subscriptionId:r,kind:"delta",seq:s,delta:{added:Array.isArray(o.added)?o.added:[],updated:Array.isArray(o.updated)?o.updated:[],removedIds:Array.isArray(o.removedIds)?o.removedIds.map(i=>String(i)):[]}}}return null}function Yi(n){if(n.kind==="snapshot"){const t=Or(n.snapshot).messages;for(let r=t.length-1;r>=0;r-=1){const s=t[r];if(s.role==="assistant")return Tn(s.id)}return}const e=[...n.delta?.updated??[],...n.delta?.added??[]];for(let t=e.length-1;t>=0;t-=1){const r=xr(e[t],!0);if(r&&(r.role===void 0||r.role==="assistant"))return Tn(r.messageId)}}function xr(n,e){if(!G(n))return null;const t=n,r=typeof t.messageId=="string"?t.messageId:null;if(!r||!G(t.block)||typeof t.block.id!="string")return null;const s=e&&(t.block.type==="text"||t.block.type==="thinking")&&typeof t.block.textDelta=="string",o=Mr(s?{text:t.block.textDelta,...t.block}:t.block);return o?(s&&!("text"in t.block)&&delete o.text,{messageId:r,...typeof t.role=="string"?{role:t.role}:{},block:o,...typeof t.messageSeq=="number"?{messageSeq:t.messageSeq}:{},...typeof t.timestamp=="string"?{timestamp:t.timestamp}:{},...t.streamingComplete===!0?{streamingComplete:!0}:{},...t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?{metadata:t.metadata}:{},...typeof t.appMessageId=="string"&&t.appMessageId.length>0?{appMessageId:t.appMessageId}:{},...t.author===null||t.author&&typeof t.author=="object"&&!Array.isArray(t.author)?{author:t.author}:{}}):null}function Zi(n,e){const t=e.name??e.toolName??"";if(e.type!=="tool_use"||n.type!=="tool_use"||!e.toolCallId||e.toolCallId!==n.toolCallId||t.length>0)return e;const r=n.metadata?.toolKind;return{...e,name:n.name??n.toolName??"",input:n.input,metadata:{...e.metadata??{},...r!==void 0?{toolKind:r}:{}}}}function Qi(n,e){return n.type!=="text"||!e?.media?n:{...n,media:{...e.media,...n.media??{}}}}function Xi(n){const e=JSON.stringify(n)??"";let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}class ea{constructor(e){y(this,"messages",[]);y(this,"truncated",!1);y(this,"nextToken");y(this,"totalMessages",0);y(this,"streaming",!1);y(this,"expectedSeq",0);y(this,"seeded",!1);y(this,"snapshotFingerprint",0);y(this,"incremental",!1);y(this,"initialHistory");y(this,"initialMessageIds",new Set);this.expectedAgentId=e}reset(){this.messages=[],this.truncated=!1,this.nextToken=void 0,this.totalMessages=0,this.streaming=!1,this.expectedSeq=0,this.seeded=!1,this.snapshotFingerprint=0,this.incremental=!1,this.initialHistory=void 0,this.initialMessageIds.clear()}applySnapshot(e,t){const r=G(t)?t:{},s=r.historyDelivery==="progressive"?Rn(r.initialHistory):void 0,o=Or(t,this.expectedAgentId),i=new Set(o.messages.map(l=>l.id));if(s===null||s&&(s.received!==i.size||!s.complete&&o.messages.length>1))return"invalid";const a=Xi(t);if(this.seeded&&a===this.snapshotFingerprint&&(e+1===this.expectedSeq||e===0&&s!==void 0&&e<this.expectedSeq))return!1;this.snapshotFingerprint=a,this.messages=o.messages,this.truncated=o.truncated,this.nextToken=o.nextToken,this.totalMessages=o.totalMessages;const c=t&&typeof t=="object"?t:{};return this.streaming=this.messages.some(l=>l.isStreaming===!0)||c.isResponding===!0||c.turnInFlight===!0,this.incremental=c.deltaEncoding==="incremental",this.initialHistory=s,this.initialMessageIds=i,this.initialHistory?.complete===!1&&(this.nextToken=void 0),this.expectedSeq=e+1,this.seeded=!0,!0}applyDelta(e,t){if(!this.seeded||e>this.expectedSeq)return"gap";if(e<this.expectedSeq)return"stale";let r=!1,s=!1;for(const o of[...t.added,...t.updated]){const i=xr(o,this.incremental);i&&(this.upsertBlock(i),(i.role===void 0||i.role==="assistant")&&(s=!0,i.streamingComplete&&(r=!0)))}if(t.removedIds.length>0){const o=new Set(t.removedIds);this.messages=this.messages.map(i=>{const a=i.contentBlocks;return!a||!a.some(c=>c.id!==void 0&&o.has(c.id))?i:{...i,contentBlocks:a.filter(c=>c.id===void 0||!o.has(c.id))}})}return r?this.streaming=this.messages.some(o=>o.role==="assistant"&&o.isStreaming===!0):s&&(this.streaming=!0),this.expectedSeq=e+1,"applied"}applyHistory(e,t){if(!this.seeded||e>this.expectedSeq)return"gap";if(e<this.expectedSeq)return"stale";if(!this.initialHistory||this.initialHistory.complete||!G(t))return"gap";const r=Rn(t);if(!r||r.target!==this.initialHistory.target)return"gap";const{received:s,complete:o}=r,i=t.message===void 0?void 0:Pr(t.message,this.expectedAgentId);if(!o&&!i||o&&t.message!==void 0)return"gap";const a=i&&!this.initialMessageIds.has(i.id);return s!==this.initialHistory.received+(a?1:0)||o&&(t.nextToken!==null&&(typeof t.nextToken!="string"||t.nextToken.length===0)||typeof t.truncated!="boolean"||typeof t.totalMessages!="number"||!Number.isSafeInteger(t.totalMessages)||t.totalMessages<s||s<r.target&&t.nextToken!==null)?"gap":(i&&(this.initialMessageIds.add(i.id),this.messages.some(c=>c.id===i.id)||(this.messages=[i,...this.messages].sort((c,l)=>(c.seq??Number.MAX_SAFE_INTEGER)-(l.seq??Number.MAX_SAFE_INTEGER)))),this.initialHistory=r,o&&(this.nextToken=t.nextToken,this.truncated=t.truncated,this.totalMessages=t.totalMessages),this.expectedSeq=e+1,"applied")}transcript(){return{...this.initialHistory?{initialHistory:this.initialHistory}:{},messages:this.messages,truncated:this.truncated,...this.nextToken!==void 0?{nextToken:this.nextToken}:{},totalMessages:this.totalMessages,isStreaming:this.streaming}}materializeBlock(e,t){const{textDelta:r,...s}=e.block,i=this.incremental&&typeof r=="string"&&(s.type==="text"||s.type==="thinking")?{...s,text:(t?.text??"")+r}:e.block;return Qi(i,t)}upsertBlock(e){const t=e.streamingComplete===!0;let r=this.messages.findIndex(l=>l.id===e.messageId);r<0&&(this.messages=[...this.messages,{id:e.messageId,role:e.role??"assistant",contentBlocks:[],timestamp:e.timestamp??new Date().toISOString(),isStreaming:!t}],r=this.messages.length-1,this.totalMessages+=1);const s=this.messages[r],o=[...s.contentBlocks??[]],i=o.findIndex(l=>l.id===e.block.id),a=this.materializeBlock(e,i>=0?o[i]:void 0);i>=0?o[i]=Zi(o[i],a):o.push(a);const c={...s,contentBlocks:o,isStreaming:!t,...t?{streamingComplete:!0}:{}};e.timestamp&&(c.timestamp=e.timestamp),e.messageSeq!==void 0&&(c.seq=e.messageSeq),e.metadata&&(c.metadata=e.metadata),e.appMessageId&&(c.appMessageId=e.appMessageId),"author"in e&&(c.author=e.author),this.messages=[...this.messages.slice(0,r),c,...this.messages.slice(r+1)]}}class ta{subscribe(e,t,r,s){const o=s?.workspaceId,i=o!==void 0?{workspaceId:o}:{},a=new ea(e);let c=!1,l,d=s?.sinceMessageId,m=!1,I,S;const h=f=>{c||f===I||(I=f,r?.(f))},w=()=>{S!==void 0&&(clearTimeout(S),S=void 0)};let R,H=Cn,N=!1;const F=()=>{R!==void 0&&(clearTimeout(R),R=void 0)},B=()=>{F(),N=!1,H=Cn},ue=()=>{c||(h("delayed"),N=!0,F(),R=setTimeout(()=>{R=void 0,!c&&(a.reset(),je(),le())},H),H=Math.min(H*2,Gi))};let $=0,U=0,X=!1,D=!1,J=!1,Y=[];const ht=(f,v=!1)=>{if(!c)try{t({...a.transcript(),...v?{fromHistory:!0}:{}}),L({...f,callbackResult:"delivered"})}catch(k){throw L({...f,callbackResult:"threw"}),k}},Ye=(f,v,k=!1)=>{if(c)return;const E=a.transcript();try{t({...E,fromSnapshot:!0,...f===void 0?{}:{resumed:f},...k?{resetCachedTranscript:!0}:{}}),L({...v,callbackResult:"delivered"})}catch(C){throw L({...v,callbackResult:"threw"}),C}},Le=()=>{w(),a.transcript().initialHistory?.complete===!1&&(S=setTimeout(()=>{S=void 0,m=!0,ue()},En))},ke=f=>{if(c)return;const v={stage:"subscription",event:"push",turnCorrelation:Yi(f),subscriptionGeneration:$,transportGeneration:U,pushKind:f.kind,pushSeq:f.seq};if(l===void 0){Y.push(f),Y.length>Hi&&Y.shift(),L({...v,callbackResult:"buffered"});return}if(f.subscriptionId!==l){L({...v,callbackResult:"ignored"});return}if(f.kind==="snapshot"){D=!1,w(),B(),h("live");const k=Ki(f.snapshot);d=void 0;const E=a.applySnapshot(f.seq,f.snapshot);if(E==="invalid"){m=X,de();return}if(E){const C=m&&k===void 0;m=!1;const fe=X?"reset":"applied";X=!0,Ye(k,{...v,reconcilerResult:fe},C)}else L({...v,reconcilerResult:"duplicate",callbackResult:"not-invoked"});Le(),J&&a.transcript().initialHistory?.complete!==!1&&(J=!1,de())}else if(D)L({...v,callbackResult:"ignored"});else{const k=f.kind==="history"?a.applyHistory(f.seq,f.history):a.applyDelta(f.seq,f.delta??{added:[],updated:[],removedIds:[]});k==="applied"?(f.kind==="history"&&(B(),h("live"),Le()),ht({...v,reconcilerResult:"applied"},f.kind==="history"),f.kind==="history"&&a.transcript().initialHistory?.complete&&J&&(J=!1,de())):k==="gap"?(L({...v,reconcilerResult:"gap",callbackResult:"not-invoked"}),de()):L({...v,reconcilerResult:"stale",callbackResult:"not-invoked"})}},le=()=>{F(),$+=1;const f=$;L({stage:"subscription",event:"registration-start",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),N||h(D?"resyncing":"connecting"),u("chat.subscribe",{agentId:e,...i,deltaEncoding:"incremental",projection:"slim",historyDelivery:"progressive",...d===void 0?{}:{sinceMessageId:d}}).then(v=>{const k=v?.subscriptionId;if($!==f||c){L({stage:"subscription",event:"registration-stale",subscriptionGeneration:f,transportGeneration:U,callbackResult:"ignored"}),k&&u("chat.unsubscribe",{subscriptionId:k,...i}).catch(()=>{});return}l=k,L({stage:"subscription",event:"registration-ack",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),!D&&!N&&h("awaiting-snapshot"),w(),S=setTimeout(()=>{S=void 0,ue()},En);const E=Y.filter(C=>C.subscriptionId===k);Y=[];for(const C of E)ke(C)}).catch(()=>{$===f&&(L({stage:"subscription",event:"registration-failed",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),ue())})},je=()=>{if($+=1,!l)return;const f=l;l=void 0,u("chat.unsubscribe",{subscriptionId:f,...i}).catch(()=>{})},vt=()=>{D=!0,F(),w(),a.reset(),je(),le()},de=()=>{c||D||vt()},g=ae(f=>{const v=Ji(f.method,f.params);if(v){ke(v);return}if(c||f.method!=="events.event"||!G(f.params))return;const k=G(f.params.event)?f.params.event:f.params;if(k.type!=="agent:stream:end"||!G(k.data))return;const E=k.data;if(E.agentId!==e||typeof E.messageId!="string"||E.messageId.length===0||E.stopReason!=="interrupted"&&typeof E.finishReason!="string")return;const C=a.transcript().messages.find(fe=>fe.id===E.messageId);C&&((C.contentBlocks?.length??0)>0||C.seq!==void 0&&C.isStreaming!==!0&&C.streamingComplete!==!1)||(!X||D||l===void 0||S!==void 0||N?J=!0:de())}),p=ce(()=>{c||(m||=X,U+=1,$+=1,L({stage:"subscription",event:"transport-reconnected",subscriptionGeneration:$,transportGeneration:U,callbackResult:"not-invoked"}),l=void 0,D=!1,Y=[],w(),B(),a.reset(),le())});return le(),()=>{c=!0,w(),F(),g(),p(),je()}}}let me=null;class na{async list(e){const t=await u("client.list",...e?[{workspaceId:e}]:[]);if(!Array.isArray(t?.clients)||!t.clients.every(Pi))throw new Error("Invalid client.list response shape");return t.clients}ownClientId(){if(!me){me=u("client.hello",{}).then(t=>{const r=t?.clientId;if(typeof r!="string"||r.length===0)throw new Error("Invalid client.hello response shape: clientId missing");return r});const e=me;e.catch(()=>{me===e&&(me=null)})}return me}}function Yu(){me=null}function tn(n){if(n.authorType!=="user")return{};const e={};if(typeof n.authorPrincipalId=="string"&&n.authorPrincipalId.trim()&&(e.authorPrincipalId=n.authorPrincipalId),Ys(n.authorIdentity)&&n.authorIdentity.externalUserId.trim()){const{provider:t,host:r,externalUserId:s}=n.authorIdentity;e.authorIdentity={provider:t,host:r,externalUserId:s}}return e}function ra(n){const e=n.latestCommentAuthorType==="user"||n.latestCommentAuthorType==="agent"?n.latestCommentAuthorType:void 0,t=tn({authorType:e,authorPrincipalId:n.latestCommentAuthorPrincipalId,authorIdentity:n.latestCommentAuthorIdentity});return{author:typeof n.latestCommentAuthor=="string"?n.latestCommentAuthor:void 0,authorType:e,authorPrincipalId:t.authorPrincipalId,authorIdentity:t.authorIdentity}}function Zu(n){const e=n.author||T.tiptap_comment_unknownAuthor_label(),{authorIdentity:t}=tn(n);if(!t)return e;const{provider:r,host:s,externalUserId:o}=t,i=`${r}@${s} · ${o}`;return T.presence_person_forge_label({name:e,handle:i})}function sa(n){if(!(!n||typeof n!="object"))return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Array.isArray(t)?t.map(r=>String(r)):[String(t)]]))}function oa(n){if(!n||typeof n!="object")return;const e=n;return{before:String(e.before??""),after:String(e.after??"")}}function ia(n){const e=n&&typeof n=="object"?n:{};return{original:String(e.original??""),proposed:String(e.proposed??"")}}function Vt(n,e,t){const r=new Date().toISOString(),s=String(n.id??""),o=typeof n.parentId=="string"&&n.parentId.length>0,i=n.anchor&&typeof n.anchor=="object"?n.anchor:o?void 0:{type:"point"},a=oa(n.anchorContext),c=sa(n.reactions),l={...tn(n),id:s,threadId:String(n.threadId??s),noteId:String(n.noteId??e),...t?{workspaceId:t}:{},content:String(n.content??""),author:String(n.author??""),authorType:n.authorType==="agent"?"agent":"user",status:typeof n.status=="string"?n.status:"open",...i?{anchor:i}:{},createdAt:String(n.createdAt??r),updatedAt:String(n.updatedAt??r),...typeof n.parentId=="string"?{parentId:n.parentId}:{},...n.anchorText!==void 0||n.section!==void 0?{anchorText:String(n.anchorText??n.section??"")}:{},...a?{anchorContext:a}:{},...typeof n.isOrphaned=="boolean"?{isOrphaned:n.isOrphaned}:{},...c?{reactions:c}:{}},d=typeof n.type=="string"?n.type:"comment";switch(d){case"suggestion":return{...l,type:d,suggestionDiff:ia(n.suggestionDiff)};case"session":return{...l,type:d,agentId:String(n.agentId??"")};case"change-request":case"question":return{...l,type:d};case"comment":default:return{...l,type:"comment"}}}async function aa(n,e){const t=e??await ie(n);if(!t)return[];try{const r=await ei(o=>u("comment.list",o),{workspaceId:t,noteId:n,includeComments:!0,limit:it},o=>u("comment.getThread",{workspaceId:t,noteId:n,threadId:o})),s=[];for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(Array.isArray(i.comments))for(const a of i.comments)s.push(Vt(a,n,t));else s.push(Vt({...i,...ra(i)},n,t))}return s}catch{return[]}}class ca{async list(e,t){return aa(e,t)}async add(e,t){return this.runCommentMutation(e,"comment.add",{searchContext:t.searchContext,commentTarget:t.commentTarget,comment:t.comment,...t.type!==void 0?{type:t.type}:{},...t.author!==void 0?{author:t.author}:{},...t.authorType!==void 0?{authorType:t.authorType}:{},...t.commentId!==void 0?{commentId:t.commentId}:{},idempotencyKey:Q()},t.workspaceId)}async respond(e,t){return this.runCommentMutation(e,"comment.respond",{...t.threadId!==void 0?{threadId:t.threadId}:{},...t.commentId!==void 0?{commentId:t.commentId}:{},comment:t.comment,...t.type!==void 0?{type:t.type}:{},...t.authorType!==void 0?{authorType:t.authorType}:{},...t.suggestionOriginal!==void 0?{suggestionOriginal:t.suggestionOriginal}:{},...t.suggestionProposed!==void 0?{suggestionProposed:t.suggestionProposed}:{}},t.workspaceId)}async delete(e,t,r){return this.runCommentMutation(e,"comment.delete",{commentId:t},r)}async runCommentMutation(e,t,r,s){const o=s??await ie(e);return o?b(t,{workspaceId:o,noteId:e,...r}):{success:!1,error:`Cannot resolve workspace for note ${e}`}}subscribe(e,t,r){let s=r;const o={subscribeMethod:"comment.subscribe",unsubscribeMethod:"comment.unsubscribe",continuation:{method:"comment.list",key:"threads",params:i=>({workspaceId:i.workspaceId,noteId:e,includeComments:!0,limit:it})},...r?{params:{workspaceId:r,noteId:e,limit:it}}:{dynamic:{subscribeIds:i=>{let a=!1;return ie(e).then(c=>{a||!c||(s=c,i([c]))}).catch(()=>{}),()=>{a=!0}},paramsForId:i=>({workspaceId:i,noteId:e,limit:it})}}};return Je({channel:o,getId:i=>typeof i.threadId=="string"?i.threadId:"",complete:i=>Ir(i,a=>u("comment.getThread",{workspaceId:s,noteId:e,threadId:a})),normalize:i=>i.noteId!==e||!Array.isArray(i.comments)?null:i.comments.flatMap(a=>{if(!a||typeof a!="object"||Array.isArray(a))return[];const c=a;return typeof c.id!="string"||!c.id||c.threadId!==i.threadId||c.noteId!==void 0&&c.noteId!==e?[]:[Vt(c,e,s)]}),handler:i=>t(i.flat())})}}class ua{async get(e,t){return await u("drafts.get",{workspaceId:e,agentId:t})??null}async set(e,t,r,s){const o={workspaceId:e,agentId:t,text:r};return s&&s.length>0&&(o.attachments=s),await u("drafts.set",o)}async clear(e,t){return await u("drafts.clear",{workspaceId:e,agentId:t})}}const la=300;class da{async list(e){return[...await this.query(e,{limit:la})].reverse()}async query(e,t={}){const r=await u("event.query",{workspaceId:e,...t});return Array.isArray(r)?r:[]}async queryPage(e,t={}){return u("event.query",{workspaceId:e,...t,paginate:!0})}subscribe(e,t){return this.list(e).then(r=>t(r)).catch(()=>t([])),()=>{}}}const fa=new Set([".onnx",".onnx_data",".pt",".pth",".bin",".safetensors",".h5",".hdf5",".pkl",".pickle",".npy",".npz",".model",".weights",".tflite",".mlmodel",".pb",".ckpt",".mat",".parquet",".feather",".arrow",".wasm",".png",".jpg",".jpeg",".gif",".bmp",".ico",".icns",".webp",".tiff",".tif",".svg",".psd",".raw",".heic",".heif",".avif",".mp3",".wav",".ogg",".flac",".aac",".m4a",".wma",".mp4",".mov",".avi",".mkv",".webm",".wmv",".flv",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".tgz",".exe",".dll",".so",".dylib",".a",".o",".obj",".ttf",".otf",".woff",".woff2",".eot",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".pyc",".pyo",".class",".jar",".war",".ear",".node"]),pa=[/package-lock\.json$/,/yarn\.lock$/,/pnpm-lock\.yaml$/,/composer\.lock$/,/Gemfile\.lock$/,/Cargo\.lock$/,/poetry\.lock$/,/\.min\.(js|css)$/,/\.bundle\.(js|css)$/,/[\\/](dist|build|node_modules)[\\/]/];function ga(n){const e=n.lastIndexOf("."),t=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return e>t&&e!==-1?n.slice(e).toLowerCase():""}function ya(n){const e=ga(n);return fa.has(e)}function ma(n){return pa.some(e=>e.test(n))}function Qu(n){return ya(n)?{skip:!0,reason:"binary/media file"}:ma(n)?{skip:!0,reason:"lock/minified/build file"}:{skip:!1}}function ha(n,e=8192){const t=n.subarray(0,Math.min(e,n.length));if(t.includes(0))return!0;let r=0;for(let s=0;s<t.length;s++){const o=t[s];o!==9&&o!==10&&o!==13&&!(o>=32&&o<=126)&&!(o>=194&&o<=244)&&!(o>=128&&o<=191)&&r++}return r/t.length>.3}const Nr=48e4,va=8*1024*1024,_n=40*1024*1024;class Br extends Error{constructor(e){super(`file.read: ${e}: stream did not contain valid UTF-8`),this.name="InvalidUtf8Error"}}function Lr(n){if(typeof n=="string")return{text:n,truncated:!1};if(n&&typeof n=="object"){const{content:e,truncated:t}=n;if(typeof e=="string")return{text:e,truncated:t===!0}}return null}function ba(n){const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}async function jr(n,e,t=u,r=va){const s=[];let o=0,i;for(;;){const l=await t(n,{...e,offset:o,length:r});if(!l||typeof l.content!="string"||!Number.isSafeInteger(l.size)||!Number.isSafeInteger(l.bytesRead))throw new Error(`${n}: invalid chunk response`);if(l.size>_n)throw new Error(`${n}: object is ${l.size} bytes, over the ${_n}-byte limit`);if(i===void 0)i=l.size;else if(l.size!==i)throw new Error(`${n}: object changed while it was read`);const d=ba(l.content);if(d.length!==l.bytesRead)throw new Error(`${n}: content/bytesRead mismatch (${d.length} vs ${l.bytesRead})`);if(s.push(d),o+=d.length,d.length<r||o>=i)break}const a=new Uint8Array(o);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a}async function ka(n,e=u){const t=await e("file.read",{...n,maxBytes:Nr}),r=Lr(t);if(!r)return null;if(!r.truncated)return r.text;const s=await jr("file.readChunk",n,e);try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(s)}catch{throw new Br(n.path)}}async function Xu(n,e=u){const t=await e("git.showFile",{...n,maxBytes:Nr}),r=Lr(t);if(!r)return"";if(!r.truncated)return r.text;const s=await jr("git.showFileChunk",n,e);return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(s)}function Ia(n){for(let e=0;e<n.length;e++){const t=n.charCodeAt(e);if(t<=8||t>=14&&t<=26||t>=28&&t<=31||t===127)return!0}return!1}function Mt(n,e){return{path:n,absolutePath:null,...fs(e),lastUpdated:Date.now(),loading:!1,saving:!1,error:null,truncated:!1}}function Mn(n){const e=n,t=Array.isArray(e)?e:Array.isArray(e?.entries)?e.entries:Array.isArray(e?.files)?e.files:[],r=[];for(const s of t){if(!s||typeof s!="object")continue;const o=s,i=typeof o.name=="string"?o.name:void 0,c=(typeof o.path=="string"?o.path:void 0)??i;if(!c)continue;const l=o.type==="directory"||o.type==="dir"||o.isDirectory===!0,d={name:i??c.split("/").pop()??c,path:c,type:l?"directory":"file"};typeof o.size=="number"&&(d.size=o.size),typeof o.modified=="string"&&(d.modified=o.modified),typeof o.isGitignored=="boolean"&&(d.isGitignored=o.isGitignored),r.push(d)}return r}function Sa(n,e){const t=n.trim();return t==="?"?"??":e?`${t} `:` ${t}`}class wa{async list(e){return[]}async read(e,t,r){try{const s=await ka({workspaceId:e,path:t,...r?.gitRootId?{gitRootId:r.gitRootId}:{}});if(s===null)return null;const o=Ia(s)||ha(new TextEncoder().encode(s.slice(0,8192)));return Mt(t,o?{kind:"restorable-snapshot",content:s,isBinary:!0}:ds(s))}catch(s){if(s instanceof Br)return Mt(t,{kind:"preview-only",isBinary:!0});if(s instanceof Yt&&s.rpcCode===-32603){const o=_(s);if(o.endsWith("stream did not contain valid UTF-8"))return Mt(t,{kind:"preview-only",isBinary:!0});if(!r?.gitRootId&&/\(os error [23]\)$/.test(o))return null}throw s}}async explorerTree(e){const t=await u("file.tree",{workspaceId:e,path:"."});if(!Array.isArray(t))throw new Error("Invalid file.tree response: expected an array");return{name:"",path:"",type:"directory",children:Mn(t)}}async listDirectory(e,t){try{const r=await u("file.list",{workspaceId:e,path:t});return Mn(r)}catch{return[]}}async gitStatusMap(e){try{const t=await u("git.status",{workspaceId:e}),r=Array.isArray(t?.files)?t.files:[],s={};for(const o of r){const i=o,a=String(i.path??"");a&&(s[a]={status:Sa(String(i.status??""),!!i.staged)})}return s}catch{return{}}}async write(e,t,r){return b("file.write",{workspaceId:e,path:t,content:r.content,idempotencyKey:Q()})}async delete(e,t){return b("file.delete",{workspaceId:e,path:t})}async mkdir(e,t){return b("file.mkdir",{workspaceId:e,path:t,idempotencyKey:Q()})}async rename(e,t,r){return b("file.rename",{workspaceId:e,oldPath:t,newPath:r,idempotencyKey:Q()})}}const Aa=48e4;function zt(n){if(!n||typeof n!="object")return;const e=n;if(e.truncated===!0)return e.truncatedReason==="pageBudget"?"pageBudget":"fileTooLarge"}function at(n,e){if(!n||typeof n!="object")return;const t=n[e];return typeof t=="string"&&t?t:void 0}function Ta(n,e){if(!n||typeof n!="object"||at(n,e)!==void 0)return;const t=n.nextToken;return typeof t=="string"&&t?t:void 0}async function Pn(n,e,t,r){const s=[],o=new Set;let i;do{const a=await n(e,i?{...t,nextToken:i}:t);if(!Array.isArray(a))return i?s:void 0;i=void 0;for(const c of a){const l=Ta(c,r);l!==void 0?i=l:s.push(c)}if(i!==void 0){if(o.has(i))break;o.add(i)}}while(i!==void 0);return s}async function Ea(n,e,t,r){const s={...t,maxBytes:t.maxBytes??Aa},o=await Pn(n,e,s,r);if(!o)return[];const i=[...o],a=new Map;i.forEach((S,h)=>{const w=at(S,r);w!==void 0&&a.set(w,h)});let c=i.filter(S=>zt(S)==="pageBudget").map(S=>at(S,r)).filter(S=>S!==void 0);const{path:l,paths:d,...m}=s;let I=!1;for(;c.length>0;){const S=I?c.slice(0,1):c,h=await Pn(n,e,{...m,paths:S},r);if(!h)break;const w=new Set(S),R=new Set;for(const N of h){const F=at(N,r);if(F===void 0||!w.has(F))continue;if(zt(N)==="pageBudget"){R.add(F);continue}const B=a.get(F);B!==void 0&&(i[B]=N)}const H=c.filter(N=>!w.has(N)||R.has(N));if(H.length===c.length){if(I)break;I=!0}else I=!1;c=H}return i}const Ca=15e4;function Dr(n){const t=(Array.isArray(n.files)?n.files:[]).map(r=>{const s=r,o={path:String(s.path??""),status:typeof s.status=="string"?s.status.trim()||St.Modified:St.Modified,staged:!!s.staged};return typeof s.mode=="string"&&(o.mode=s.mode),typeof s.oldSha=="string"&&(o.oldSha=s.oldSha),typeof s.newSha=="string"&&(o.newSha=s.newSha),o});return{branch:String(n.branch??""),ahead:Number(n.ahead??0),behind:Number(n.behind??0),diverged:n.diverged===void 0?Number(n.ahead)>0&&Number(n.behind)>0:!!n.diverged,files:t,hasUncommittedChanges:n.hasUncommittedChanges===void 0?t.length>0:!!n.hasUncommittedChanges,hasUntrackedFiles:n.hasUntrackedFiles===void 0?t.some(r=>r.status===St.Untracked):!!n.hasUntrackedFiles}}function el(n){if(!n||typeof n!="object")return null;const e=n;return typeof e.branch!="string"||typeof e.ahead!="number"||typeof e.behind!="number"||!Array.isArray(e.files)||e.files.some(t=>!t||typeof t!="object"||typeof t.path!="string"||typeof t.status!="string"||typeof t.staged!="boolean")?null:Dr(e)}const Xe=new Map;function On(n,e){const t=ps.state,r=JSON.stringify([Qs(t),Zs(t),t.daemonHealth?.connectionGeneration,n]);if(!e?.forceRefresh){const o=Xe.get(r);if(o)return o}const s=u("git.status",{workspaceId:n,...e?.forceRefresh?{forceRefresh:!0}:{}}).then(o=>!o||typeof o!="object"?null:Dr(o)).catch(()=>null);return Xe.set(r,s),s.then(()=>{Xe.get(r)===s&&Xe.delete(r)}),s}function Ra(n){const e=n&&typeof n=="object"?n:{},t=typeof e.type=="string"?e.type:"Context",s={type:t==="Addition"?wt.Addition:t==="Deletion"?wt.Deletion:wt.Context,content:typeof e.content=="string"?e.content:""};return typeof e.oldNumber=="number"&&(s.oldNumber=e.oldNumber),typeof e.newNumber=="number"&&(s.newNumber=e.newNumber),s}function _a(n){const e=Array.isArray(n)?n:[],t=[];for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=typeof s.path=="string"?s.path:"";if(!o)continue;const a=(Array.isArray(s.hunks)?s.hunks:[]).map(l=>{const d=l&&typeof l=="object"?l:{};return{oldStart:Number(d.oldStart??0),oldLines:Number(d.oldLines??0),newStart:Number(d.newStart??0),newLines:Number(d.newLines??0),lines:Array.isArray(d.lines)?d.lines.map(Ra):[]}}),c=zt(r);t.push(c?{file:o,chunks:a,truncatedReason:c}:{file:o,chunks:a})}return t}function Ma(n){if(typeof n!="string"||!n)return 0;const e=Date.parse(n);return Number.isFinite(e)?e:0}function Pa(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.path=="string"?e.path:"";if(!t)return null;const r={path:t};return typeof e.additions=="number"&&(r.additions=e.additions),typeof e.deletions=="number"&&(r.deletions=e.deletions),typeof e.status=="string"&&(r.status=e.status),r}function Oa(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.hash=="string"?e.hash:"";if(!t)return null;const r=!!e.isPushed,s={hash:t,message:typeof e.message=="string"?e.message:"",author:typeof e.author=="string"?e.author:"",timestamp:Ma(e.date),stage:r?"pushed":"local",isPushed:r};return Array.isArray(e.files)&&(s.files=e.files.map(Pa).filter(o=>o!==null)),typeof e.filesChanged=="number"&&(s.filesChanged=e.filesChanged),typeof e.date=="string"&&(s.date=e.date),typeof e.agentId=="string"&&(s.agentId=e.agentId),typeof e.linkedNoteId=="string"&&(s.linkedNoteId=e.linkedNoteId),s}function xa(n,e){const r=(Array.isArray(n.files)?n.files:[]).map(i=>typeof i=="string"?i:null).filter(i=>i!==null),o=(Array.isArray(n.fileDetails)?n.fileDetails:[]).map(i=>{if(!i||typeof i!="object")return null;const a=i,c=typeof a.path=="string"?a.path:"";return c?{path:c,additions:typeof a.additions=="number"?a.additions:0,deletions:typeof a.deletions=="number"?a.deletions:0}:null}).filter(i=>i!==null);return{commitHash:typeof n.commitHash=="string"?n.commitHash:e,author:typeof n.author=="string"?n.author:"",authorEmail:typeof n.authorEmail=="string"?n.authorEmail:"",date:typeof n.date=="string"?n.date:"",message:typeof n.message=="string"?n.message:"",files:r,fileDetails:o}}const Na=new Set(Object.values(fr)),Ba=new Set(["added","modified","deleted","renamed"]);function La(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.file=="string"?e.file:"",r=typeof e.relativePath=="string"?e.relativePath:t;if(!t&&!r)return null;const s=typeof e.stage=="string"&&Na.has(e.stage)?e.stage:fr.Unstaged,o=typeof e.status=="string"&&Ba.has(e.status)?e.status:void 0,i=e.stats&&typeof e.stats=="object"?e.stats:{},a=e.attribution&&typeof e.attribution=="object"?e.attribution:{};return{id:typeof e.id=="string"&&e.id?e.id:r||t,file:t||r,relativePath:r||t,stage:s,stats:{additions:typeof i.additions=="number"?i.additions:0,deletions:typeof i.deletions=="number"?i.deletions:0},...o?{status:o}:{},attribution:{...a.agent&&typeof a.agent=="object"?{agent:a.agent}:{},...typeof a.manual=="boolean"?{manual:a.manual}:{},timestamp:typeof a.timestamp=="number"?a.timestamp:0},...typeof e.commitHash=="string"?{commitHash:e.commitHash}:{}}}function Pt(n,e){const t=n.map(r=>r.trim()).filter(Boolean);return t.length===0?{ok:!1,failure:{success:!1,error:`No file paths provided; ${e.toLowerCase()} requires explicit paths.`}}:t.some(r=>r==="."||r==="*"||r.includes("--all"))?{ok:!1,failure:{success:!1,error:`${e} all files is not allowed; specify explicit file paths.`}}:{ok:!0,paths:t}}class ja{async originUrl(e){try{const t=await u("git.getRemoteUrl",{repoPath:e,remoteName:"origin"});return typeof t?.url=="string"?t.url:null}catch{return null}}async status(e,t){return On(e,t)}async changes(e){return On(e)}async diffs(e,t){const r={workspaceId:e};t?.path&&(r.path=t.path),t?.paths?.length&&(r.paths=t.paths),t?.staged===!0&&(r.staged=!0),t?.commitHash&&(r.commitHash=t.commitHash),t?.gitRootId&&(r.gitRootId=t.gitRootId);try{const s=await Ea(u,"git.diffs",r,"path");return _a(s)}catch{return[]}}async commitDetails(e,t,r){try{const s=await u("git.commitDetails",{workspaceId:e,commitHash:t,...r?.gitRootId?{gitRootId:r.gitRootId}:{}});return!s||typeof s!="object"?null:xa(s,t)}catch{return null}}async trackedChanges(e){try{const t=await u("file-tracking.getChanges",{workspaceId:e});return(Array.isArray(t?.changes)?t.changes:[]).map(La).filter(s=>s!==null)}catch{return null}}async commits(e,t){try{return(await this.commitsWithBoundary(e,t)).commits}catch{return[]}}async commitsWithBoundary(e,t){const r=await u("file-tracking.loadCommits",{workspaceId:e,...t!==void 0?{includeOlder:t}:{}}),s=Array.isArray(r?.commits)?r.commits:[],o=r?.boundarySha===null||typeof r?.boundarySha=="string"?r.boundarySha:null,i=r?.nextToken===null||typeof r?.nextToken=="string"?r.nextToken:null;return{commits:s.map(Oa).filter(a=>a!==null),boundarySha:o,nextToken:i,...typeof r?.historyIdentity=="string"&&r.historyIdentity?{historyIdentity:r.historyIdentity}:{}}}async getBranches(e,t,r){try{const s=await u("git.getBranches",{...r===void 0?{}:{workspaceId:r},repoPath:e,includeRemote:t});if(!s||typeof s!="object")return null;const o=Array.isArray(s.branches)?s.branches.filter(a=>typeof a=="string"):[],i=Array.isArray(s.remoteBranches)?s.remoteBranches.filter(a=>typeof a=="string"):[];return{branches:o,remoteBranches:i,currentBranch:typeof s.currentBranch=="string"?s.currentBranch:"",defaultBranch:typeof s.defaultBranch=="string"?s.defaultBranch:""}}catch{return null}}async branchStatus(e,t,r){try{const s=await u("git.branchStatus",{...r===void 0?{}:{workspaceId:r},repoPath:e,branchName:t});return!s||typeof s!="object"?null:{branch:typeof s.branch=="string"?s.branch:t,currentBranch:typeof s.currentBranch=="string"?s.currentBranch:"",isCurrentBranch:!!s.isCurrentBranch,ahead:typeof s.ahead=="number"?s.ahead:0,behind:typeof s.behind=="number"?s.behind:0,hasUncommittedChanges:!!s.hasUncommittedChanges}}catch{return null}}async prRefresh(e,t){try{const r=await u("pr.refresh",{workspaceId:e,...t});return!r||typeof r!="object"||typeof r.outcome!="string"||!["skipped","unchanged","linked","updated","unlinked"].includes(r.outcome)?null:{outcome:r.outcome,prNumber:typeof r.prNumber=="number"?r.prNumber:void 0,prUrl:typeof r.prUrl=="string"?r.prUrl:void 0,prStatus:typeof r.prStatus=="string"?r.prStatus:void 0,pullRequests:Array.isArray(r.pullRequests)?r.pullRequests:[]}}catch{return null}}async stage(e,t){const r=Pt(t,"Staging");return r.ok?b("git.stage",{workspaceId:e,paths:r.paths}):r.failure}async unstage(e,t){const r=Pt(t,"Unstaging");return r.ok?b("git.unstage",{workspaceId:e,paths:r.paths}):r.failure}async discard(e,t){const r=Pt(t,"Discarding");return r.ok?b("git.discard",{workspaceId:e,paths:r.paths}):r.failure}async commit(e,t){return t.userRequested?b("git.agentCommit",{workspaceId:e,message:t.message,...t.files!==void 0?{files:t.files}:{},userRequested:t.userRequested}):{success:!1,error:"git.agentCommit requires userRequested: true."}}async pull(e,t,r){try{const s=await u("git.pull",{repoPath:e,branchName:t,...r===void 0?{}:{workspaceId:r}},{timeoutMs:Ca});return s&&typeof s=="object"&&s.ok===!0?{success:!0}:{success:!1,error:s&&typeof s=="object"&&typeof s.error=="string"&&s.error?s.error:"Failed to pull changes"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}const Da=Ne("LiveIntegrationsClient");function Ua(n){return n.merged===!0?"merged":n.state==="closed"?"closed":n.draft===!0?"draft":n.isInMergeQueue===!0?"queued":"open"}class qa{captureRepositoryCheckout(e){return js(e)}async githubUser(e){try{const r=(await u("github.getUser",...e===void 0?[]:[{workspaceId:e}]))?.user;return!r||typeof r.login!="string"||r.login.length===0?null:{login:r.login,name:null,email:null,avatar_url:typeof r.avatarUrl=="string"?r.avatarUrl:""}}catch{return null}}async githubBranches(e,t,r,s){const[o,i]=await Promise.all([u("github.branches.list",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,...r?{prefix:r}:{}}),r?Promise.resolve(void 0):u("github.repos.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t}).then(c=>{const l=c?.repo?.defaultBranch;return typeof l=="string"&&l.length>0?l:void 0},()=>{})]);return{branches:Array.isArray(o?.branches)?o.branches.filter(c=>typeof c=="string"):[],defaultBranch:i}}async githubBranchesCached(e,t,r){try{const s=await u("github.branches.listCached",{owner:e,repo:t,...r===void 0?{}:{workspaceId:r}}),o=Array.isArray(s?.branches)?s.branches.filter(c=>typeof c=="string"):[],i=typeof s?.defaultBranch=="string"&&s.defaultBranch.length>0?s.defaultBranch:void 0,a=s?.source==="cache"||s?.source==="ls-remote"?s.source:void 0;return{cached:s?.cached===!0,branches:o,defaultBranch:i,source:a}}catch{return{cached:!1,branches:[]}}}async githubRepoConfig(e,t,r,s){const o=await u("github.repoConfig.get",{owner:e,repo:t,...r?{ref:r}:{},...s===void 0?{}:{workspaceId:s}}),i=o?.config&&typeof o.config=="object"&&!Array.isArray(o.config)?o.config:null;return i===null&&o?.config!=null&&Da.warn("github.repoConfig.get returned a non-object config; treating as null",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t}),{config:i,exists:o?.exists===!0}}captureRepositoryResource(e){return Ds(e)}async githubPullRequest(e,t,r,s){const i=(await u("github.pulls.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,number:r}))?.pull;if(!i)throw new Error(`Pull request ${e}/${t}#${r} not found`);const a=Ua(i),c=a==="queued"?mr(i.mergeQueue):null;return{owner:e,repo:t,number:i.number,title:i.title,state:a,author:i.user.login,createdAt:i.createdAt,updatedAt:i.updatedAt,url:i.htmlUrl,headRef:i.headRef,baseRef:i.baseRef,...c?{mergeQueue:c}:{}}}async githubIssue(e,t,r,s){const i=(await u("github.issues.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,number:r}))?.issue;if(!i)throw new Error(`Issue ${e}/${t}#${r} not found`);return{owner:e,repo:t,number:i.number,title:i.title,state:i.state,author:i.user.login,createdAt:i.createdAt,updatedAt:i.updatedAt,url:i.htmlUrl}}async linearIssues(e){try{return(await u("linear.authStatus",...e===void 0?[]:[{workspaceId:e}]))?.authenticated!==!0?[]:(await u("linear.listIssues",...e===void 0?[]:[{workspaceId:e}])).issues}catch{return[]}}async sentryIssues(e){try{return(await u("sentry.authStatus",...e===void 0?[]:[{workspaceId:e}]))?.authenticated!==!0?[]:(await u("sentry.listIssues",...e===void 0?[]:[{workspaceId:e}])).issues}catch{return[]}}subscribe(e){let t=!1;return this.githubUser().then(r=>{t||e({githubUser:r})}),()=>{t=!0}}}const Fa=["cli-missing","prerequisite-missing"];function $a(n){return Fa.some(e=>e===n)}function Wa(n){if(!(typeof n?.warning!="string"||!n.warning))return $a(n.warningKind)?n.warningKind:void 0}function tl(n){const{providerId:e,providerRef:t,forceRefresh:r,workspaceId:s}=n??{};if(typeof e!="string"||!e)return;const o={providerId:gs(e,t)};return typeof s=="string"&&s&&(o.workspaceId=s),r===!0&&(o.forceRefresh=!0),o}function nl(n){const e=n?.providerId;return{success:!1,error:T.providers_modelsClient_unsupportedProvider_error({id:String(e??"")})}}function rl(n){const e={success:!0,data:Ur(n)};typeof n?.warning=="string"&&n.warning&&(e.warning=n.warning),n?.stale===!0&&(e.stale=!0);const t=Wa(n);return t&&(e.warningKind=t),e}function Ga(n){if(typeof n?.id!="string"||!n.id||typeof n?.name!="string"||!n.name)return null;const e={value:n.id,label:n.name};return typeof n.description=="string"&&(e.description=n.description),typeof n.modelGroupPriority=="number"&&(e.modelGroupPriority=n.modelGroupPriority),typeof n.costTier=="number"&&(e.costTier=n.costTier),Array.isArray(n.badges)&&(e.badges=n.badges),Array.isArray(n.effortLevels)&&(e.effortLevels=n.effortLevels),n.isDefault===!0&&(e.isDefault=!0),n.isLegacyModel===!0&&(e.isLegacyModel=!0),typeof n.priority=="number"&&(e.priority=n.priority),e}function Ur(n){return Array.isArray(n?.models)?n.models.flatMap(e=>Ga(e)??[]):[]}class Ha{async list(e,t){try{const r=e||t?await u("models.list",{...e?{providerId:e}:{},...t?{workspaceId:t}:{}}):await u("models.list");return e&&r.providerId!==e?[]:Ur(r)}catch{return[]}}subscribe(e){let t=!1;return this.list().then(r=>{t||e(r)}),()=>{t=!0}}}function Kt(n){if(typeof n=="number"&&Number.isFinite(n)&&n>=0)return Math.trunc(n);if(typeof n=="string"&&n.length>0){const e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.trunc(e)}return null}function Va(n){if(!n||typeof n!="object")return null;const e=n,t=Kt(e.v);if(t===null)return null;const r=e.author&&typeof e.author=="object"?e.author:null,s=r?{id:String(r.id??""),name:String(r.name??""),type:typeof r.type=="string"?r.type:vs.System}:void 0;return{versionId:String(t),versionNumber:t,content:String(e.content??""),title:String(e.title??""),...s?{author:s}:{},createdAt:String(e.date??"")}}class za extends Error{constructor(){super("Truncated note read capability is unknown: no acknowledged hello yet"),this.name="NoteCapabilityUnknownError"}}function Ka(n){return n instanceof Error?n.message===T.agent_placement_unavailable()?!1:n.name!=="UnbridgedMockIpcChannelError":!0}const Ja=30,Ya=100;function Fe(n,e){const t=new Date().toISOString(),r=String(n.id??"");return{...n,id:hs(r),workspaceId:ur(String(n.workspaceId??e)),title:String(n.title??""),content:String(n.content??""),contentType:typeof n.contentType=="string"?n.contentType:ms.Markdown,tags:Array.isArray(n.tags)?n.tags:[],isPinned:!!(n.isPinned??n.is_pinned??!1),isArchived:!!(n.isArchived??n.is_archived??!1),visibility:typeof n.visibility=="string"?n.visibility:ys.Workspace,rev:typeof n.rev=="number"?n.rev:void 0,contentPreview:typeof n.contentPreview=="string"?n.contentPreview:void 0,contentLength:typeof n.contentLength=="number"?n.contentLength:void 0,contentTruncated:n.contentTruncated===!0?!0:void 0,contentBytes:n.contentTruncated===!0&&typeof n.contentBytes=="number"?n.contentBytes:void 0,createdAt:String(n.createdAt??n.created_at??t),updatedAt:String(n.updatedAt??n.updated_at??t)}}class Za{async list(e,t){const r=o=>u("note.list",o);let s;if(t?.projection==="slim")try{s=await Ce(r,{workspaceId:e,projection:"slim",limit:ve},"notes")}catch(o){if(!cr(o))throw o;s=await Ce(r,{workspaceId:e,limit:ve},"notes")}else s=await Ce(r,{workspaceId:e,limit:ve},"notes");return s.map(o=>{const i=Fe(o,e);return He(String(i.id),e),i})}async supportsTruncatedRead(){for(let e=0;e<Ja;e++){try{const r=(await Us())?.server?.capabilities;if(r)return r.noteTruncatedRead===1}catch(t){if(!Ka(t))return!1}await new Promise(t=>setTimeout(t,Ya))}throw new za}async get(e,t,r){const s=t??await ie(e);if(!s)return null;try{const o=r?.maxContentBytes!==void 0?await u("note.get",{workspaceId:s,noteId:e,maxContentBytes:r.maxContentBytes}):await Sr(a=>u("note.get",a),{workspaceId:s,noteId:e}),i=o&&typeof o=="object"&&"note"in o?o.note:o;return!i||typeof i!="object"?null:Fe(i,s)}catch{return null}}async create(e){return Wt("note.create",{...e,idempotencyKey:Q()})}async setContent(e,t,r,s,o){return this.runNoteMutation(e,"note.setContent",{content:t,...o?.baseContentBytes!==void 0?{baseContentBytes:o.baseContentBytes}:{}},r,s)}async add(e,t,r,s,o){return this.runNoteMutation(e,"note.add",{content:t,...r?.heading!==void 0?{heading:r.heading}:{},...r?.position!==void 0?{position:r.position}:{}},s,o)}async edit(e,t,r,s,o){return this.runNoteMutation(e,"note.edit",{old:t,new:r},s,o)}async editLines(e,t,r,s,o,i){return this.runNoteMutation(e,"note.editLines",{start:t,end:r,content:s},o,i)}async delete(e,t,r){return this.runNoteMutation(e,"note.delete",{},t,r)}async updateMetadata(e,t,r,s){return this.runNoteMutation(e,"note.updateMetadata",{...t.title!==void 0?{title:t.title}:{},...t.tags!==void 0?{tags:t.tags}:{}},r,s)}async listVersions(e,t){const r=await u("note.listVersions",{workspaceId:e,noteId:t});return!Array.isArray(r)||r.length===0?[]:(await Promise.all(r.map(o=>{const i=Kt(o.v);return i===null?Promise.resolve(null):u("note.getVersion",{workspaceId:e,noteId:t,v:i}).then(a=>Va(a)).catch(()=>null)}))).filter(o=>o!==null)}async restoreVersion(e,t,r){const s=Kt(r);if(s===null)return{success:!1,error:`Invalid version id: ${r}`};try{const o=await u("note.restoreVersion",{workspaceId:e,noteId:t,v:s});return{success:!0,note:o&&typeof o=="object"&&o.note&&typeof o.note=="object"?Fe(o.note,e):void 0}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}async runNoteMutation(e,t,r,s,o){const i=o??await ie(e);if(!i)return{success:!1,error:`Cannot resolve workspace for note ${e}`};const a=await b(t,{workspaceId:i,noteId:e,...r,...s!==void 0?{expectedVersion:s}:{}}),c=a.conflict?.current;return c&&typeof c=="object"?{...a,conflict:{current:Fe(c,i)}}:a}subscribe(e){return Je({channel:{subscribeMethod:"note.subscribe",unsubscribeMethod:"note.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t,limit:ve})},continuation:{method:"note.list",key:"notes",params:t=>({workspaceId:t.workspaceId,limit:ve})}},getId:t=>String(t.id??""),normalize:t=>{const r=String(t.workspaceId??"");if(!r)return null;const s=Fe(t,r);return He(String(s.id),r),s},handler:e})}}class Qa{async catalog(e){const t=bs.parse(e?{workspaceId:e}:{}),r=await u(Ps,t);return ks.parse(r)}async listProfiles(e){const t=await u(Os,e?{baseProviderId:e}:{});return Is.parse(t)}async createProfile(e){const t=await u(Ss,{baseProviderId:e.baseProviderId,name:e.name,...e.env?{env:e.env}:{},...e.backup!==void 0?{backup:e.backup}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return ws.parse(t)}async updateProfile(e){const t=await u(As,{profileId:e.profileId,...e.name!==void 0?{name:e.name}:{},...e.env?{env:e.env}:{},...e.backup!==void 0?{backup:e.backup}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return Ts.parse(t)}async updateDefault(e){const t=await u(Es,{baseProviderId:e.baseProviderId,...e.name!==void 0?{name:e.name}:{},...e.env?{env:e.env}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return Cs.parse(t)}async deleteProfile(e){const t=await u(xs,{profileId:e});return Rs.parse(t)}async reorderProfiles(e){const t=await u(_s,{baseProviderId:e.baseProviderId,profileIds:e.profileIds});return Ms.parse(t)}}const Xa=200;function Ot(n){return n?{remoteAgentId:n.remoteAgentId}:{}}class ec{async supportsLifecycle(){return(await u("client.hello",{}))?.server?.capabilities?.scriptLifecycle===1}async requireActiveLists(){const e=await u("client.hello",{});if(e.server?.capabilities?.scriptActiveLists!==1)throw new Error(T.scripts_list_unsupported_error());return{fullPages:e.server?.capabilities?.boundedReads===1}}async list(e,t){const{fullPages:r}=await this.requireActiveLists(),s=[],o=new Set;let i;do{const a=await u("script.list",{workspaceId:e,archive:t?.archive??"active",...r?{limit:Xa,...i?{cursor:i}:{}}:{}});if(!Array.isArray(a?.scripts))throw new Error(T.scripts_list_load_error());for(const l of a.scripts)s.push(tc(l)?await xn(e,l.id):l);const c=r?a.nextCursor:void 0;if(typeof c=="string"&&c&&!o.has(c))o.add(c),i=c;else{if(c!=null)throw new Error(T.scripts_list_load_error());i=void 0}}while(i);return s}async listPage(e,t){await this.requireActiveLists();const r=await u("script.list",{workspaceId:e,archive:"active",view:"summary",limit:100,...t});if(r?.view!=="summary"||!Array.isArray(r.scripts))throw new Error(T.scripts_list_unsupported_error());return r}async get(e,t){return await this.requireActiveLists(),xn(e,t)}async archive(e,t,r){if(!r?.capabilityVerified&&!await this.supportsLifecycle())throw new Error(T.scripts_list_unsupported_error());return u("script.archive",{workspaceId:e,scriptIds:t})}async restore(e,t,r){if(!r?.capabilityVerified&&!await this.supportsLifecycle())throw new Error(T.scripts_list_unsupported_error());return u("script.restore",{workspaceId:e,scriptIds:t})}async create(e,t){try{if(t.scriptId!==void 0)throw new Error("Use scriptsClient.update to edit an existing script.");const r=await u("script.create",{workspaceId:e,name:t.name,command:t.command,mode:t.mode,...t.purpose!==void 0?{purpose:t.purpose}:{},...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{},...t.category!==void 0?{category:t.category}:{},...t.autoStart!==void 0?{autoStart:t.autoStart}:{},...t.healthUrl!==void 0?{healthUrl:t.healthUrl}:{},...t.readyPattern!==void 0?{readyPattern:t.readyPattern}:{}}),s=typeof r?.id=="string"?r.id:void 0;return{success:!0,...s?{id:s}:{},...r?{script:r}:{}}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}async start(e,t){return b("script.start",{workspaceId:e,scriptId:t})}async stop(e,t,r){return b("script.stop",{workspaceId:e,scriptId:t,...Ot(r)})}async restart(e,t,r){return b("script.restart",{workspaceId:e,scriptId:t,...Ot(r)})}async output(e,t,r,s){try{const o=await u("script.output",{workspaceId:e,scriptId:t,...r!==void 0?{maxLines:r}:{},...Ot(s)});return typeof o=="string"?o:""}catch{return""}}async status(e,t){try{const r=await u("script.status",{workspaceId:e,scriptId:t});return r&&typeof r=="object"?r:null}catch{return null}}async run(e,t,r){try{const s=await u("script.run",{workspaceId:e,scriptId:t,...r?.maxLines!==void 0?{maxLines:r.maxLines}:{},...r?.timeoutSeconds!==void 0?{timeoutSeconds:r.timeoutSeconds}:{}});return s&&typeof s=="object"?s:null}catch{return null}}subscribe(e){return e([]),()=>{}}}function tc(n){return Object.entries(n).some(([e,t])=>e.endsWith("Omitted")&&t===!0)}const nc=3,rc=4096;async function xn(n,e){for(let t=0;t<nc;t++){const r=await u("script.get",{workspaceId:n,scriptId:e});if(r?.commandTruncated!==!0)return r;const s=r.commandBytes;let o=r.command,i=r.nextCommandOffset,a=!1,c=1;for(;typeof i=="number";){if(++c>rc)throw new Error(T.scripts_list_load_error());const h=await u("script.get",{workspaceId:n,scriptId:e,commandOffset:i});if(h?.commandBytes!==s||h.commandOffset!==i||h.updatedAt!==r.updatedAt){a=!0;break}o+=h.command;const w=h.nextCommandOffset;if(typeof w=="number"&&w<=i)throw new Error(T.scripts_list_load_error());i=w}if(a)continue;if(new TextEncoder().encode(o).length!==s)throw new Error(T.scripts_list_load_error());const{commandTruncated:l,commandBytes:d,commandOffset:m,nextCommandOffset:I,...S}=r;return{...S,command:o}}throw new Error(T.scripts_list_load_error())}const sc=["stdio","http","sse"],oc=["oauth","header","none"];function xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Nn(n){const e=new WeakSet;try{const t=JSON.stringify(n,(r,s)=>!xe(s)&&!Array.isArray(s)?s:e.has(s)?"[Circular]":(e.add(s),Array.isArray(s)?s:Object.keys(s).sort().reduce((o,i)=>(o[i]=s[i],o),{})));return t===void 0?void 0:t}catch{return}}function qr(n,e,t){if(n==null)return e;if(typeof n=="string")return n||e;if(n instanceof Error)return n.message||e;if(xe(n)){if(t.has(n))return Nn(n)??e;t.add(n);for(const r of["message","error","reason","details"])if(r in n)return qr(n[r],e,t)}return Nn(n)??String(n||e)}function sl(n,e){return qr(n,e,new WeakSet)}function Se(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function ic(n){if(Array.isArray(n)){const e=n.filter(t=>typeof t=="string");return e.length>0?e:void 0}if(typeof n=="string"){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>0?e:void 0}}function Bn(n){if(!xe(n))return;const e=Object.entries(n).filter(t=>typeof t[1]=="string");return Object.fromEntries(e)}function ac(n){return oc.includes(n)?n:void 0}function ol(n){switch(n){case"running":return"connected";case"starting":return"configured";case"stopped":return"stopped";case"error":return"error";case"auth_required":return"auth_required";default:return null}}function xt(n,e){if(!xe(n))return null;const t=Se(n.name)??Se(e);if(!t)return null;const r=n.type??n.transport,s=sc.includes(r)?r:Se(n.command)?"stdio":"http",o={name:t,type:s},i=Se(n.id);i&&(o.id=i);const a=Se(n.command),c=Se(n.url),l=ic(n.args),d=Bn(n.env),m=Bn(n.headers),I=ac(n.authType);return a&&(o.command=a),c&&(o.url=c),l&&(o.args=l),d&&(o.env=d),m&&(o.headers=m),I&&(o.authType=I),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),o}function cc(n){if(Array.isArray(n))return n.flatMap(r=>xt(r)??[]);if(!xe(n))return[];const e=n.mcpServers??n.servers;if(Array.isArray(e))return e.flatMap(r=>xt(r)??[]);const t=xe(e)?e:n;return Object.entries(t).flatMap(([r,s])=>xt(s,r)??[])}function Fr(n){const e=new Set,t=new Map;for(const r of n){const s=lr(r);if(e.has(s))throw new Error(`Duplicate MCP server identity: ${s}`);e.add(s);const o=t.get(r.name);if(o&&(!o.id||!r.id))throw new Error(`Duplicate MCP server name requires distinct IDs: ${r.name}`);t.set(r.name,r)}}function il(n){const e=cc(n);return Fr(e),e}function al(n){const e={name:n.name,type:n.type};return n.id!==void 0&&(e.id=n.id),n.command!==void 0&&(e.command=n.command),n.args!==void 0&&(e.args=[...n.args]),n.url!==void 0&&(e.url=n.url),n.authType!==void 0&&(e.authType=n.authType),n.disabled!==void 0&&(e.disabled=n.disabled),n.workspaceDisabled!==void 0&&(e.workspaceDisabled=n.workspaceDisabled),n.plugin!==void 0&&(e.plugin=n.plugin),e}const Ln="global",be=new Map,We=new Map,he=new Map;let Me=0,$r=0;function Wr(n,e){return JSON.stringify([$r,e??null,n])}let jn=!1;function uc(n){if(n.method!=="events.event"||!n.params)return;const e=n.params,t=e.event&&typeof e.event=="object"?e.event:e;return typeof t.type=="string"?t.type:void 0}function Gr(){jn||(jn=!0,typeof ae=="function"&&ae(n=>{uc(n)==="settings:changed"&&Ve()}),typeof ce=="function"&&ce(()=>{$r+=1,Ve()}))}function Ve(n){if(Me+=1,!n)be.clear();else for(const e of be.keys())n.includes(JSON.parse(e)[2])&&be.delete(e)}function lc(n){return n?.definition?{...n.definition,value:n.value,...n.origin?{origin:n.origin}:{},...typeof n.revision=="number"?{revision:n.revision}:{}}:null}function Hr(n,e){Gr();const t=Wr(n,e);if(be.has(t))return Promise.resolve(be.get(t)??null);const r=We.get(t);if(r?.generation===Me)return r.promise;if(r){const i=he.get(t);if(i)return i;const a=r.promise.catch(()=>null).then(()=>he.get(t)!==a?null:(he.delete(t),Hr(n,e))).finally(()=>{he.get(t)===a&&he.delete(t)});return he.set(t,a),a}const s=Me,o=u("settings.get",{path:n,...e?{workspaceId:e}:{}}).then(lc).then(i=>(s===Me&&be.set(t,i),i)).finally(()=>{We.get(t)?.promise===o&&We.delete(t)});return We.set(t,{generation:s,promise:o}),o}async function dc(n){if(n.length===0)return{applied:[],revision:0};const e=await u("settings.update",{changes:n});return Ve(n.map(({path:t})=>t)),{applied:Array.isArray(e?.applied)?e.applied:[],revision:typeof e?.revision=="number"?e.revision:0}}function cl(){Ve(),We.clear(),he.clear()}function Dn(n){const e=[];for(const[t,r]of Object.entries(n))r!==void 0&&e.push({path:t,value:r});return e}class fc{async list(e){return(await this.listSnapshot(e)).settings}async listSnapshot(e){Gr();const t=Me;try{const r=await u("settings.list",...e?[{workspaceId:e}]:[]),s={settings:Array.isArray(r?.settings)?r.settings:[],revision:typeof r?.revision=="number"?r.revision:0};if(t===Me)for(const o of s.settings)be.set(Wr(o.path,e),o);return s}catch{return{settings:[],revision:0}}}async get(e,t){try{return await Hr(e,t)}catch{return null}}async update(e){return(await this.updateSnapshot(e)).applied}async updateSnapshot(e){return dc(e)}async reset(e){try{const t=await u("settings.reset",{path:e});return typeof t?.path!="string"?null:(Ve([t.path]),{path:t.path,value:t.value})}catch{return null}}async getUserRule(e,t){try{const r=await u("rules.get",{workspaceId:t??Ln,ruleType:e});return!r||typeof r.content!="string"?null:{enabled:r.enabled===!0,content:r.content,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:0}}catch{return null}}async updateUserRule(e,t,r){return b("rules.update",{workspaceId:Ln,ruleType:e,content:t,...r!==void 0?{enabled:r}:{}})}async getUserPreferences(){return null}async setUserPreferences(e){return{success:!0}}async getProviderSettings(e){const t=await this.list(e),r=Nt(t,"model.defaultProvider"),s=et(t,"providers.enabled");return r===null&&s===null?null:{activeProviderId:r??"",enabledProviders:s??{}}}async setProviderSettings(e){return b("settings.update",{changes:Dn({"model.defaultProvider":e.activeProviderId,"providers.enabled":e.enabledProviders})})}async getMcpServers(e){return(await qn(e)).flatMap(r=>Vr(r)??[])}async getMcpServerStatuses(e,t){return(await Promise.all(e.map(async s=>{try{const o=await u("mcp.servers.getStatus",{serverId:s,...t?{workspaceId:t}:{}});return Un(s,o?.status)}catch{return null}}))).filter(s=>s!==null)}async restartMcpServer(e){const t=await u("mcp.servers.restart",{serverId:e}),r=Un(e,t?.status);if(!r)throw new Error("The daemon returned an invalid MCP server status.");return r}async getWorkspaceDisabledMcpServerKeys(e){try{const t=await u("mcp.servers.list",{workspaceId:e});return Array.isArray(t?.servers)?t.servers.flatMap(r=>r.workspaceDisabled===!0&&typeof r.name=="string"&&r.name?[lr({id:r.id,name:r.name})]:[]):null}catch{return null}}async toggleWorkspaceMcpServer(e,t,r){try{const s=await u("mcp.servers.toggle",{serverId:t,enabled:r,workspaceId:e});return typeof s?.workspaceDisabled=="boolean"?{success:!0,workspaceDisabled:s.workspaceDisabled}:{success:!0}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async setMcpServers(e){try{Fr(e);const t=await qn(),r=new Map(t.map(i=>[i.id,i])),s=e.map(i=>{if(i.id!==void 0)return{config:i,current:r.get(i.id)};const a=t.filter(c=>c.name===i.name);if(a.length>1)throw new Error(`Ambiguous MCP server name: ${i.name}`);return{config:i,current:a[0]}}),o=new Set;for(const{config:i,current:a}of s){const c=a?.id??i.id;if(c){if(o.has(c))throw new Error(`Duplicate MCP server identity: ${c}`);o.add(c)}}for(const i of t)i.id&&!i.plugin&&!o.has(i.id)&&await u("mcp.servers.delete",{serverId:i.id});for(const{config:i,current:a}of s){if(i.plugin&&!a?.plugin)continue;if(!a?.id){await u("mcp.servers.create",{config:Fn(i,i.id)});continue}const c={...i,env:i.env??a.env,headers:i.headers??a.headers};!a.plugin&&!pc(a,c)&&await u("mcp.servers.update",{serverId:a.id,config:Fn(c,a.id)});const l=i.disabled!==!0;a.enabled!==!1!==l&&await u("mcp.servers.toggle",{serverId:a.id,enabled:l})}return{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async getWorkspaceSettings(e){try{const t=await u("workspace.getAutoCommit",{workspaceId:e});return typeof t?.autoCommit?.enabled!="boolean"?null:{autoCommitEnabled:t.autoCommit.enabled}}catch{return null}}async setWorkspaceSettings(e,t){return t.autoCommitEnabled===void 0?{success:!0}:b("workspace.setAutoCommit",{workspaceId:e,enabled:t.autoCommitEnabled})}async getBackgroundAgentSettings(e){const t=await this.list(e),r=Nt(t,"quickActions.defaultReasoningEffort"),s=et(t,"quickActions.typeReasoningEffortOverrides"),o=Nt(t,"quickActions.defaultModel"),i=et(t,"quickActions.typeOverrides"),a=et(t,"quickActions.providerSettings");return o===null&&i===null&&a===null&&r===null&&s===null?null:{defaultReasoningEffort:r??"",typeReasoningEffortOverrides:s??{},defaultModel:o??"",typeOverrides:i??{commit:"",pr:"",review:"",fast:""},providerSettings:a??{}}}async setBackgroundAgentSettings(e){return b("settings.update",{changes:Dn({"quickActions.defaultReasoningEffort":e.defaultReasoningEffort,"quickActions.typeReasoningEffortOverrides":e.typeReasoningEffortOverrides,"quickActions.defaultModel":e.defaultModel,"quickActions.typeOverrides":e.typeOverrides,"quickActions.providerSettings":e.providerSettings})})}subscribe(e){return e(null),()=>{}}}function Un(n,e){if(typeof e?.serverId=="string"&&e.serverId&&e.serverId!==n||e?.state!=="stopped"&&e?.state!=="starting"&&e?.state!=="running"&&e?.state!=="error"&&e?.state!=="auth_required")return null;const t={serverId:n,state:e.state};return typeof e.lastError=="string"&&e.lastError&&(t.lastError=e.lastError),t}async function qn(n){try{const e=await u("mcp.servers.list",...n?[{workspaceId:n}]:[]);return Array.isArray(e?.servers)?e.servers:[]}catch{return[]}}function Vr(n){if(typeof n?.name!="string"||!n.name)return null;const e=n.transport==="http"||n.transport==="sse"?n.transport:"stdio",t={name:n.name,type:e};return typeof n.id=="string"&&n.id&&(t.id=n.id),typeof n.command=="string"&&n.command&&(t.command=n.command),Array.isArray(n.args)&&(t.args=n.args),n.env&&typeof n.env=="object"&&(t.env=n.env),typeof n.url=="string"&&n.url&&(t.url=n.url),n.headers&&typeof n.headers=="object"&&(t.headers=n.headers),n.enabled===!1&&(t.disabled=!0),typeof n.workspaceDisabled=="boolean"&&(t.workspaceDisabled=n.workspaceDisabled),typeof n.plugin=="string"&&n.plugin&&(t.plugin=n.plugin),t}function Fn(n,e){const t={name:n.name,transport:n.type,enabled:n.disabled!==!0};return e&&(t.id=e),n.command&&(t.command=n.command),n.args&&(t.args=n.args),n.env&&(t.env=n.env),n.url&&(t.url=n.url),n.headers&&(t.headers=n.headers),t}function pc(n,e){const t=Vr(n);if(!t)return!1;const r=o=>o?Object.entries(o).sort(([i],[a])=>i.localeCompare(a)):null,s=o=>JSON.stringify([o.name,o.type,o.command??null,o.args??null,r(o.env),o.url??null,r(o.headers)]);return s(t)===s(e)}function zr(n,e){for(const t of n)if(t.path===e)return t;return null}function Nt(n,e){const t=zr(n,e);return t&&typeof t.value=="string"?t.value:null}function et(n,e){const t=zr(n,e);return!t||t.value===null||typeof t.value!="object"?null:t.value}function Bt(n){if(!n||typeof n!="object")return null;const e=n.setupScript;return!e||typeof e!="object"?null:e}class gc{async get(e){try{const t=await u("workspace.getSetupScript",{workspaceId:e});return Bt(t)}catch{return null}}async save(e,t){try{const r=await u("workspace.saveSetupScript",{workspaceId:e,script:t});return Bt(r)}catch{return null}}async detectProjectType(e){try{const t=await u("workspace.detectProjectType",{workspaceId:e});return typeof t?.projectType=="string"?t.projectType:null}catch{return null}}async generate(e){try{const t=await u("workspace.generateSetupScript",{workspaceId:e});return Bt(t)}catch{return null}}}const Lt=Ne("LiveSkillsClient"),yc=["machine-offline","machine-update-required"],$n=500,Wn=100;function jt(n){return{name:n.name,description:n.description,location:n.location,...n.resourceDirectory?{resourceDirectory:n.resourceDirectory}:{},scope:n.scope}}class mc{async fetchList(e){const t=[],r=new Set;let s;for(let o=0;o<Wn;o++){const i=await u("skill.list",{workspaceId:e,limit:$n,...s?{nextToken:s}:{}});if(Array.isArray(i))return i.map(jt);for(const a of Array.isArray(i?.skills)?i.skills:[])r.has(a.name)||(r.add(a.name),t.push(jt(a)));if(s=typeof i?.nextToken=="string"?i.nextToken:void 0,!s)return t}return Lt.warn("skill.list paging stopped at the page limit"),t}async list(e){return this.fetchList(e)}async listForAgent(e,t){const r=[],s=new Set;let o=!1,i=null,a;for(let c=0;c<Wn;c++){const l=await u("skill.list",{workspaceId:e,agentId:t,limit:$n,...a?{nextToken:a}:{}});for(const m of Array.isArray(l?.skills)?l.skills:[])s.has(m.name)||(s.add(m.name),r.push(jt(m)));if(o=l?.stale===!0,i=yc.find(m=>m===l?.unavailable)??null,a=typeof l?.nextToken=="string"?l.nextToken:void 0,!a)return{skills:r,stale:o,unavailable:i}}return Lt.warn("skill.list paging stopped at the page limit"),{skills:r,stale:o,unavailable:i}}subscribe(e){let t=!1,r,s;e([]);const o=l=>{this.fetchList(l).then(d=>{t||e(d)}).catch(d=>{Lt.error("Failed to refetch skill list; keeping last known-good view",d)})},i=()=>Jt({eventTypes:["skills:changed"]}).then(l=>{r=l?.subscriptionId,t&&r&&Oe(r)}).catch(()=>{});i();const a=ae(l=>{if(l.method==="skills:changed"&&!t){const m=l.params?.workspaceId;m&&(s=m,o(m))}}),c=ce(()=>{t||(r=void 0,i(),s&&o(s))});return()=>{t=!0,a(),c(),r&&Oe(r)}}}const Dt=Ne("LiveSpecialistsClient"),hc=100,vc=500,bc=100;class kc{async listCatalog(e,t,r){const s={...e?{provider:e}:{},...t?{workspaceId:t}:{},...r?.includeProject?{includeProject:!0}:{}},o=[],i=new Set;let a,c;for(let d=0;d<bc;d++){const m=await u("specialist.list",{...s,limit:vc,...c?{nextToken:c}:{}});for(const I of Array.isArray(m?.specialists)?m.specialists:[])i.has(I.id)||(i.add(I.id),o.push(I));if(d===0&&(a=m?.importDiagnostics),c=typeof m?.nextToken=="string"?m.nextToken:void 0,!c)break}return c&&Dt.warn("specialist.list paging stopped at the page limit"),{specialists:await Promise.all(o.map(d=>d.behaviorPromptOmitted?this.hydrateOmittedPrompt(d,e,t):d)),importDiagnostics:a}}async hydrateOmittedPrompt(e,t,r){try{const o=(await u("specialist.get",{id:e.id,...t?{provider:t}:{},...r?{workspaceId:r}:{}}))?.specialist;if(o&&o.id===e.id&&o.source===e.source&&!o.behaviorPromptOmitted&&typeof o.behaviorPrompt=="string")return{...e,...o,behaviorPromptOmitted:void 0,behaviorPromptBytes:void 0}}catch(s){Dt.warn(`specialist.get for omitted prompt of ${e.id} failed`,s)}return e}async list(e,t){try{return(await this.listCatalog(e,t)).specialists}catch{return[]}}subscribe(e){return this.subscribeCatalogSnapshot(t=>e(t.specialists),()=>e([]))}subscribeCatalog(e){return this.subscribeCatalogSnapshot(e)}subscribeCatalogSnapshot(e,t){let r=!1,s,o;this.listCatalog().then(d=>{r||e(d)}).catch(()=>{r||t?.()});const i=()=>{this.listCatalog().then(d=>{r||e(d)}).catch(d=>{Dt.error("Failed to refetch specialist list; keeping last known-good view",d)})},a=()=>Jt({eventTypes:["specialists:changed","skills:changed"]}).then(d=>{s=d?.subscriptionId,r&&s&&Oe(s)}).catch(()=>{});a();const c=ae(d=>{(d.method==="specialists:changed"||d.method==="skills:changed")&&!r&&(o!==void 0&&clearTimeout(o),o=setTimeout(()=>{o=void 0,i()},hc))}),l=ce(()=>{r||(s=void 0,a(),o!==void 0&&(clearTimeout(o),o=void 0),i())});return()=>{r=!0,o!==void 0&&(clearTimeout(o),o=void 0),c(),l(),s&&Oe(s)}}async create(e,t,r,s,o){const i={id:e,spec:t};return r&&(i.scope=r),s&&(i.workspacePath=s),r==="project"&&o&&(i.workspaceId=o),(await u("specialist.create",i)).specialist}async edit(e,t,r,s,o){const i={id:e,spec:t,scope:r};return s&&(i.workspacePath=s),r==="project"&&o&&(i.workspaceId=o),(await u("specialist.edit",i)).specialist}async delete(e,t,r,s){const o={id:e,scope:t};return r&&(o.workspacePath=r),t==="project"&&s&&(o.workspaceId=s),await u("specialist.delete",o)}}class Ic{async getUsage(e,t,r){const s={period:e,tzOffsetMinutes:r};t!==void 0&&(s.key=t);const o=await u("stats.getUsage",s);for(const i of["byModel","byProvider"])if(!Array.isArray(o[i]))throw new Error(`stats.getUsage result is missing the required \`${i}\` array (PROTOCOL §5.36) — the daemon is likely outdated and predates this field`);return o}}const Sc=12e4;function wc(n){return typeof n.arrayBuffer=="function"?n.arrayBuffer():new Promise((e,t)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>t(r.error??new Error("Blob read failed")),r.readAsArrayBuffer(n)})}async function Ac(n){const e=new Uint8Array(await wc(n)),t=32768;let r="";for(let s=0;s<e.length;s+=t)r+=String.fromCharCode(...e.subarray(s,s+t));return btoa(r)}class Tc{async transcribe(e,t,r,s){const o={audio:await Ac(e),mimeType:t};return r&&(r.prompt!==void 0||r.keyterms!==void 0)&&(o.context=r),typeof s=="string"&&s.trim().length>0&&(o.workspaceId=s),u("voice.transcribe",o,{timeoutMs:Sc})}async getWorkspaceVocabulary(e){return u("voice.getWorkspaceVocabulary",{workspaceId:e})}}const Ec=["stable","beta","alpha","disabled"];function ul(n){return Ec.includes(n)}const M={CHECK_MANUAL:"auto-update:check-manual",DOWNLOAD:"auto-update:download",INSTALL:"auto-update:install",DISMISS_DOWNLOADED_TOAST:"auto-update:dismiss-downloaded-toast",GET_STATE:"auto-update:get-state",SET_CHANNEL:"auto-update:set-channel",SET_SHARE_STATISTICS:"auto-update:set-share-statistics",STATUS_CHANGED:"auto-update:status-changed",PROGRESS:"auto-update:progress",ERROR:"auto-update:error",UP_TO_DATE:"auto-update:up-to-date",SHOW_TOAST:"auto-update:show-toast"},Cc={async checkForUpdatesManual(){const n=await ee(M.CHECK_MANUAL);if(!n.success||n.data===void 0)throw new Error(n.error?.message||T.autoUpdate_client_checkFailed_error());return n.data},async downloadUpdate(){const n=await ee(M.DOWNLOAD);if(!n.success)throw new Error(n.error?.message||T.autoUpdate_client_downloadFailed_error())},async installUpdate(){const n=await ee(M.INSTALL);if(!n.success)throw new Error(n.error?.message||T.autoUpdate_client_installFailed_error())},async dismissDownloadedToast(){const n=await ee(M.DISMISS_DOWNLOADED_TOAST);if(!n.success)throw new Error(n.error?.message||"Could not dismiss the update notice")},async getState(){const n=await ee(M.GET_STATE);if(!n.success||n.data===void 0)throw new Error(n.error?.message||T.autoUpdate_client_getStateFailed_error());return n.data},async setChannel(n){const e=await ee(M.SET_CHANNEL,{channel:n});if(!e.success)throw new Error(e.error?.message||T.autoUpdate_client_setChannelFailed_error())},async setShareStatistics(n){const e=await ee(M.SET_SHARE_STATISTICS,{enabled:n});if(!e.success)throw new Error(e.error?.message||T.autoUpdate_client_setShareStatisticsFailed_error())},onStatusChanged(n){const e=window.electronAPI.on(M.STATUS_CHANGED,n);return()=>{e&&window.electronAPI.offById(M.STATUS_CHANGED,e)}},onProgress(n){const e=window.electronAPI.on(M.PROGRESS,n);return()=>{e&&window.electronAPI.offById(M.PROGRESS,e)}},onError(n){const e=window.electronAPI.on(M.ERROR,n);return()=>{e&&window.electronAPI.offById(M.ERROR,e)}},onShowToast(n){const e=window.electronAPI.on(M.SHOW_TOAST,n);return()=>{e&&window.electronAPI.offById(M.SHOW_TOAST,e)}},onUpToDate(n){const e=window.electronAPI.on(M.UP_TO_DATE,n);return()=>{e&&window.electronAPI.offById(M.UP_TO_DATE,e)}}};class Rc{async status(){try{const e=await u("system.status");return!e||typeof e!="object"?{nodeVersionOk:null,nodeVersion:void 0,auggieInstalled:!1,binaryInstallAvailable:!1}:{nodeVersionOk:typeof e.nodeVersionOk=="boolean"?e.nodeVersionOk:null,nodeVersion:typeof e.nodeVersion=="string"?e.nodeVersion:void 0,auggieInstalled:typeof e.auggieInstalled=="boolean"?e.auggieInstalled:!1,binaryInstallAvailable:typeof e.binaryInstallAvailable=="boolean"?e.binaryInstallAvailable:!1}}catch{return{nodeVersionOk:null,nodeVersion:void 0,auggieInstalled:!1,binaryInstallAvailable:!1}}}async releaseNotes(){return null}async autoUpdate(){try{return{...await Cc.getState(),toastVisible:!1,downloadedToastDismissedAt:null}}catch{return null}}subscribe(e){return this.status().then(t=>e(t)),()=>{}}}class Kr{constructor(e=!1){this.localMachine=e}async pairingInfo(){const e=await u("server.pairingInfo",void 0,this.localMachine?{localMachine:!0}:void 0);if(typeof e?.token!="string"||typeof e?.certFingerprint!="string"||typeof e?.path!="string"||!Array.isArray(e?.localIps)||typeof e?.hostname!="string")throw new Error("Invalid server.pairingInfo response shape");return{token:e.token,certFingerprint:e.certFingerprint,port:e.port??null,path:e.path,localIps:e.localIps,hostname:e.hostname,...typeof e.tcAddress=="string"&&e.tcAddress.length>0?{tcAddress:e.tcAddress}:{},...Array.isArray(e.availableIps)?{availableIps:e.availableIps}:{}}}async rotateToken(){const e=await u("server.rotateToken",void 0,this.localMachine?{localMachine:!0}:void 0);if(typeof e?.token!="string")throw new Error("Invalid server.rotateToken response shape");return{token:e.token}}}function _c(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.enabled=="boolean"&&typeof e.relayUrl=="string"&&(e.daemonId===null||typeof e.daemonId=="string")&&typeof e.linked=="boolean"&&(e.linkedDevices===null||typeof e.linkedDevices=="number")&&typeof e.publishing=="boolean"}class Mc{async status(){let e;try{e=await u("push.status")}catch(c){if(c instanceof Yt&&(c.rpcCode===-32601||c.code==="METHOD_NOT_FOUND"))return null;throw c}if(!_c(e))throw new Error("Invalid push.status response shape");const{enabled:t,relayUrl:r,daemonId:s,linked:o,linkedDevices:i,publishing:a}=e;return{enabled:t,relayUrl:r,daemonId:s,linked:o,linkedDevices:i,publishing:a}}}const Pc=Ne("LiveTasksClient");function Ut(n,e){if(!(!Array.isArray(e)||e.length===0)){if(!e.every(t=>typeof t=="string")){Pc.warn(`discarding malformed ${n}: expected string[], got non-string member`,{value:e});return}return e}}function Jr(n){const e=Ut("dependsOn",n.dependsOn),t=Ut("conflictsWith",n.conflictsWith),r=Ut("unmetDependsOn",n.unmetDependsOn);return{...e?{dependsOn:e}:{},...t?{conflictsWith:t}:{},...r?{unmetDependsOn:r}:{}}}function Yr(n){return typeof n.specLinked=="boolean"?{specLinked:n.specLinked}:{}}function nn(n){const t=n.metadata?.task;return t?{id:String(n.id??""),title:String(n.title??""),status:typeof t.status=="string"?t.status:"not_started",updatedAt:typeof n.updatedAt=="string"?n.updatedAt:typeof n.updated_at=="string"?n.updated_at:void 0,...typeof n.rev=="number"?{rev:n.rev}:{},...Jr(t),...Yr(t)}:null}function Gn(n){const e=nn(n);return e||(typeof n.status!="string"?null:{id:String(n.id??""),title:String(n.title??""),status:n.status,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:typeof n.updated_at=="string"?n.updated_at:void 0,...typeof n.rev=="number"?{rev:n.rev}:{},...Jr(n),...Yr(n)})}function Oc(n){const e=nn(n);return e||(typeof n.status=="string"?{id:String(n.id??""),title:String(n.title??""),status:n.status,...typeof n.updatedAt=="string"?{updatedAt:n.updatedAt}:{},...typeof n.rev=="number"?{rev:n.rev}:{}}:null)}const xc={total:0,completed:0,inProgress:0};function Hn(n){if(!n||typeof n!="object")return null;const e=n,t=e.noteId,r=e.taskKey,s=e.taskText,o=e.agentId,i=e.createdAt;return typeof t!="string"||typeof r!="string"||typeof s!="string"||typeof o!="string"||typeof i!="number"?null:{noteId:t,taskKey:r,taskText:s,agentId:o,createdAt:i}}function Nc(n){if(!n||typeof n!="object")return{...xc};const e=n;return{total:typeof e.total=="number"?e.total:0,completed:typeof e.completed=="number"?e.completed:0,inProgress:typeof e.inProgress=="number"?e.inProgress:0}}class Bc{async list(e){const t=await u("task.list",{workspaceId:e}),r=Array.isArray(t?.tasks)?t.tasks:[],s=[];for(const o of r){const i=Gn(o);i&&(i.id&&He(i.id,e),s.push(i))}return{tasks:s,stats:Nc(t?.stats)}}async get(e){const t=await ie(e);if(!t)return null;try{const r=await Sr(o=>u("note.get",o),{workspaceId:t,noteId:e}),s=r&&typeof r=="object"&&"note"in r?r.note:r;return!s||typeof s!="object"?null:nn(s)}catch{return null}}async updateStatus(e,t,r,s){return this.runTaskMutation(e,"task.updateStatus",{taskText:t,status:r},s)}async update(e,t,r,s){return this.runTaskMutation(e,"task.update",{line:t,...r.text!==void 0?{text:r.text}:{},...r.status!==void 0?{status:r.status}:{},...r.expected!==void 0?{expected:r.expected}:{}},s)}async updateNoteStatus(e,t,r){return this.runTaskMutation(e,"task.updateNoteStatus",{status:t},r)}async markAsTask(e,t,r,s){return this.runTaskMutation(e,"task.markAsTask",{status:t,...r?.acceptanceCriteria!==void 0?{acceptanceCriteria:r.acceptanceCriteria}:{},...r?.effort!==void 0?{effort:r.effort}:{},...r?.dependsOn!==void 0?{dependsOn:r.dependsOn}:{},...r?.conflictsWith!==void 0?{conflictsWith:r.conflictsWith}:{}},s)}async setRelations(e,t){return this.runTaskMutation(e,"task.setRelations",{...t.dependsOn!==void 0?{dependsOn:t.dependsOn}:{},...t.conflictsWith!==void 0?{conflictsWith:t.conflictsWith}:{}})}async assignAgent(e,t,r){return this.runTaskMutation(e,"task.assignAgent",{agentId:t},r)}async createPrerequisite(e,t,r){const s=await ie(e);return s?Wt("task.createPrerequisite",{workspaceId:s,dependentNoteId:e,title:t,...r?.content!==void 0?{content:r.content}:{},...r?.status!==void 0?{status:r.status}:{},idempotencyKey:Q()}):{success:!1,error:`Cannot resolve workspace for note ${e}`}}async listAgentLinks(e){const r=(await u("task.listAgentLinks",{workspaceId:e}))?.linksByNoteId;if(!r||typeof r!="object")return{};const s={};for(const[o,i]of Object.entries(r)){if(!i||typeof i!="object")continue;const a={};for(const[c,l]of Object.entries(i)){const d=Hn(l);d&&(a[c]=d)}Object.keys(a).length>0&&(s[o]=a)}return s}async linkAgent(e,t,r){const s=await u("task.linkAgent",{workspaceId:e,noteId:t,taskText:r.taskText,agentId:r.agentId,...r.taskKey!==void 0?{taskKey:r.taskKey}:{}}),o=Hn(s?.link);return o||{...r,noteId:t}}async unlinkAgent(e,t,r){return(await u("task.unlinkAgent",{workspaceId:e,noteId:t,taskKey:r}))?.removed===!0}async runTaskMutation(e,t,r,s){const o=await ie(e);if(!o)return{success:!1,error:`Cannot resolve workspace for note ${e}`};const i=await Wt(t,{workspaceId:o,noteId:e,...r,...s!==void 0?{expectedVersion:s}:{}}),a=i.conflict?.current;if(a&&typeof a=="object"){const c=Oc(a);if(c)return{...i,conflict:{current:c}}}return i}subscribe(e){return Je({channel:{subscribeMethod:"task.subscribe",unsubscribeMethod:"task.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t})},continuation:{method:"task.list",key:"tasks",params:t=>({workspaceId:t.workspaceId})}},getId:t=>String(t.id??""),normalize:t=>{const r=Gn(t);return r?.id&&typeof t.workspaceId=="string"&&t.workspaceId&&He(r.id,t.workspaceId),r},handler:e})}}function Lc(n){const e=new TextEncoder().encode(n);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Vn(n){if(typeof n!="string"||n.length===0)return"";try{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}catch{return""}}function jc(n,e){if(!n||typeof n!="object")return null;const t=n,r=String(t.terminalId??t.id??"");if(!r)return null;const s=typeof t.workspaceId=="string"?t.workspaceId:e;return{id:r,name:typeof t.name=="string"?t.name:"",workspaceId:s,createdAt:typeof t.createdAt=="string"?t.createdAt:void 0,isConnected:!0,...typeof t.isExecutingCommand=="boolean"?{isExecuting:t.isExecutingCommand}:{}}}function Dc(n){if(!n||typeof n!="object")return null;const e=n;return e.event&&typeof e.event=="object"?e.event:typeof e.type=="string"?e:null}function Uc(n){if(!n||typeof n!="object")return;const e=n.subscriptionId;return typeof e=="string"?e:void 0}class qc{async list(e){const t=await u("terminal.list",{workspaceId:e}),r=Array.isArray(t),s=r?t:Array.isArray(t?.terminals)?t.terminals:[],o=!r&&typeof t?.daemonBootId=="string"?t.daemonBootId:void 0,i=[];for(const a of s){const c=jc(a,e);c&&i.push(c)}return{terminals:i,...o!==void 0?{daemonBootId:o}:{}}}async create(e){try{const t=await u("terminal.create",{workspaceId:e.workspaceId,cols:e.cols,rows:e.rows,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.command!==void 0?{command:e.command}:{},...e.env!==void 0?{env:e.env}:{}}),r=typeof t?.terminalId=="string"?t.terminalId:void 0;return r?{success:!0,id:r}:{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async write(e,t,r){return b("terminal.write",{terminalId:e,data:Lc(t),...r!==void 0?{workspaceId:r}:{}})}async resize(e,t,r,s){return b("terminal.resize",{terminalId:e,cols:t,rows:r,...s!==void 0?{workspaceId:s}:{}})}async kill(e,t){return b("terminal.kill",{terminalId:e,...t!==void 0?{workspaceId:t}:{}})}async getBuffer(e,t,r){try{const s=await u("terminal.getBuffer",{terminalId:e,...r!==void 0?{workspaceId:r}:{},...t!==void 0?{maxBytes:t}:{}});return Vn(s?.data)}catch{return""}}async output(e,t){try{const r=await u("terminal.readOutput",{workspaceId:e,terminalId:t});if(typeof r=="string")return r;const s=r?.output;return typeof s=="string"?s:""}catch{return""}}subscribeEvents(e,t,r){let s=!1,o=0,i;const a=ae(d=>{if(d.method!=="events.event")return;const m=Uc(d.params);if(i===void 0||m!==i)return;const I=Dc(d.params);if(!I||typeof I.type!="string"||!I.type.startsWith("terminal:"))return;const S=I.data??{};if(S.terminalId===e)switch(I.type){case"terminal:data":t.onData?.({terminalId:e,chunk:Vn(S.chunk)});break;case"terminal:exit":t.onExit?.({terminalId:e,exitCode:typeof S.exitCode=="number"?S.exitCode:0});break;case"terminal:cwd":typeof S.cwd=="string"&&t.onCwd?.({terminalId:e,cwd:S.cwd});break;case"terminal:title":typeof S.title=="string"&&t.onTitle?.({terminalId:e,title:S.title});break}}),c=()=>{const d=++o;return Jt({eventTypes:["terminal:data","terminal:exit","terminal:cwd","terminal:title"],...r!==void 0?{workspaceId:r}:{}}).then(m=>{const I=m?.subscriptionId;if(s||d!==o){I&&Oe(I,r);return}i=I}).catch(()=>{})};c();const l=ce(()=>{i=void 0,c()});return()=>{s=!0,a(),l(),i&&Oe(i,r)}}subscribe(e){return e([]),()=>{}}}function Fc(n=qs){return{async begin(e,t,r){const s=Fs.parse(e),o=$s.parse(t);if(te(s.root)!==te(o.review.root))throw new Error("NATIVE_REVIEW_UNAVAILABLE");const i=await n(o);if(te(i.preview.root)!==te(s.root))throw await i.release(),new Error("NATIVE_REVIEW_UNAVAILABLE");let a;try{a=i.onRetired(r)}catch(d){throw await i.release(),d}let c=!1,l;return{...o.review.companion&&i.prepareCompanion?{prepareCompanion(){return l||(l=Promise.resolve().then(async()=>{if(c)throw new Error("NATIVE_REVIEW_UNAVAILABLE");const d=await i.prepareCompanion();if(c||te(d.preview.root)!==te(s.root))throw await d.release(),new Error("NATIVE_REVIEW_UNAVAILABLE");return d}),l)}}:{},preview:i.preview,onRetired:i.onRetired,confirm:i.confirm,reconcile:i.reconcile,async release(){c||(c=!0,a(),l?.then(d=>d.release(),()=>{}),await i.release())}}}}}const $c=Be({root:Ws,editId:P().min(1),admission:P().nullable()}).strict();function Wc(n=Gs){return{async begin(e,t){const r=$c.parse(e),s=await n(r.root);if(te(s.preview.root)!==te(r.root))throw await s.release(),new Error("REPOSITORY_SELECTION_UNAVAILABLE");const o=s.onRetired(t);let i=!1;return{preview:s.preview,onRetired:s.onRetired,confirm:s.confirm,reconcile:s.reconcile,async release(){i||(i=!0,o(),await s.release())}}}}}function Gc(n=Hs){return{async observe(e,t){const r=Object.freeze({...e});let s=!0,o,i;const a=()=>{s&&(s=!1,i?.(),o?.release())},c=()=>{if(s)try{t({type:"unavailable",request:r})}finally{a()}};return(async()=>{if(o=await n(r.gitRootId===void 0?{workspaceId:r.workspaceId,kind:"primary"}:{workspaceId:r.workspaceId,kind:"registered",gitRootId:r.gitRootId}),!s){await o.release();return}if(i=o.onRetired(()=>{if(s)try{t({type:"retired",request:r})}finally{a()}}),!s){i();return}const l=await o.request("workspace.repositoryContext",{workspaceId:r.workspaceId,...r.gitRootId===void 0?{}:{gitRootId:r.gitRootId}});if(!s)return;if(!l.current){try{t({type:"retired",request:r})}finally{a()}return}if(l.settlement.status!=="fulfilled"){c();return}const d=no.parse(l.settlement.value);if(!ro(d,r)){c();return}t({type:"received",response:{request:r,context:d}})})().catch(c),a}}}const Hc="base-refresh-failed",Vc=["auth-required","ssh-host-key","network","timeout","repo-not-found","access-denied","other"];function tt(n){return typeof n=="string"?n:""}function zc(n){if(!n||typeof n!="object")return;const e=n;return e.code!==Hc?void 0:{category:Vc.includes(tt(e.category))?e.category:"other",detail:tt(e.detail),baseRef:tt(e.baseRef),remote:tt(e.remote)}}const Kc=Be({homeId:P().min(1),nodeId:P().min(1).optional(),cloudMachineId:P().min(1).optional(),name:P(),state:P().min(1),since:P(),lastBackupAt:P().optional(),backupWarning:so().optional(),setup:Xs.optional().catch(void 0)});function Zr(n){const e=Kc.safeParse(n);return e.success?e.data:void 0}const Jc=Be({amount:ne().finite(),currency:P().min(1)}).passthrough(),ct=Be({inputTokens:ne().int().nonnegative(),outputTokens:ne().int().nonnegative(),cacheReadTokens:ne().int().nonnegative(),cacheCreationTokens:ne().int().nonnegative(),thoughtTokens:ne().int().nonnegative().optional(),cost:Jc.optional()}).passthrough(),Yc=Be({agentId:P().min(1),model:P().min(1),totals:ct,humanMessages:ne().int().nonnegative(),agentMessages:ne().int().nonnegative()}).passthrough(),zn=new TextEncoder;function Kn(n,e){const t=zn.encode(n),r=zn.encode(e);for(let s=0;s<Math.min(t.length,r.length);s++)if(t[s]!==r[s])return t[s]-r[s];return t.length-r.length}const Zc=oo(Yc).superRefine((n,e)=>{for(const[t,r]of n.entries()){const s=n[t-1];s!==void 0&&(Kn(r.agentId,s.agentId)||Kn(r.model,s.model))<=0&&e.addIssue({code:io.custom,message:"byAgentModel rows must be unique and sorted by agentId, then model",path:[t]})}}),Qr=Be({byAgentId:Tt(P(),ct),totals:ct,byModel:Tt(P(),ct),byAgentModel:Zc.optional(),agentNames:Tt(P(),P()).optional(),lastScanAt:eo({offset:!0}).nullable()}).passthrough();function Qc(n){return Qr.parse(n)}function ll(n){const e=Qr.safeParse(n);return e.success?e.data:null}const Xc=Ne("LiveWorkspacesClient"),eu=12e4,tu=3e5;function nu(n){switch(String(n).toLowerCase()){case"inactive":return De.Inactive;case"archived":return De.Archived;case"retired":return De.Retired;case"deleted":return De.Deleted;default:return De.Active}}function we(n){const e=new Date().toISOString(),t=String(n.id??n.workspaceId??""),{defaultAgentPlacement:r,home:s,...o}=n,i=Zr(s);return s!==void 0&&!i&&Xc.warn("workspace row carried a home outside the contract",{workspaceId:t}),{...o,...r===void 0?{}:{defaultAgentPlacement:to.parse(r)},...i?{home:i}:{},id:dr(t),title:String(n.title??n.name??t),branch:String(n.branch??""),status:nu(n.status),changesets:Array.isArray(n.changesets)?n.changesets:[],timeline:Array.isArray(n.timeline)?n.timeline:[],conversationInfo:Array.isArray(n.conversationInfo)?n.conversationInfo:[],createdAt:String(n.createdAt??e),updatedAt:String(n.updatedAt??e)}}function Jn(n){if(!n||typeof n!="object")return;const e=n.data;if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function ru(n){if(!n||typeof n!="object")return;const e=n.data;if(!e||typeof e!="object")return;const t=e;if(t.code!=="launch-failed"||typeof t.workspaceId!="string"||t.workspaceId.length===0)return;const r=t.launch?.agentId,s=t.cause?.message;return{workspaceId:t.workspaceId,...typeof r=="string"&&r.length>0?{agentId:r}:{},...typeof s=="string"&&s.length>0?{cause:s}:{}}}function Yn(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.type=="string"&&e.type.length>0}function Zn(n,e){if(!Oi(n))throw new Error(`Invalid ${e} response shape`);return n}function su(n){if(n===null||typeof n!="object")return!1;const e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.title=="string"&&typeof e.archived=="boolean"&&typeof e.linkedAt=="string"}const ou=["applied","dismissed","notResolved"];function iu(n){if(!n||typeof n!="object")return;const{proposalId:e,outcome:t}=n;if(!(typeof e!="string"||typeof t!="string")&&ou.includes(t))return{proposalId:e,outcome:t}}class au{constructor(){y(this,"listRequests",new Map);y(this,"getRequests",new Map)}beginNativeReview(e,t,r){return Fc().begin(e,t,r)}beginRepositorySelectionEdit(e,t){return Wc().begin(e,t)}observeRepositoryContext(e,t){return Gc().observe(e,t)}list(e){const t=e?.includeArchived===!0,r=e?.includeRetired===!0,s=`${t}:${r}`,o=r?void 0:this.listRequests.get(s);if(o)return o;const i={...t?{includeArchived:!0}:{},...r?{includeRetired:!0}:{}},a=ut(l=>u("workspace.list",l),i,"workspaces").then(l=>(Array.isArray(l?.workspaces)?l.workspaces:[]).map(m=>we(m)));if(r)return a;this.listRequests.set(s,a);const c=()=>{this.listRequests.get(s)===a&&this.listRequests.delete(s)};return a.then(c,c),a}get(e){const t=this.getRequests.get(e);if(t)return t;const r=u("workspace.get",{workspaceId:e}).then(o=>{const i=o&&typeof o=="object"&&"workspace"in o?o.workspace:o;return!i||typeof i!="object"?null:we(i)});this.getRequests.set(e,r);const s=()=>{this.getRequests.get(e)===r&&this.getRequests.delete(e)};return r.then(s,s),r}async open(e){return this.get(e)}async create(e){try{const t=await u("workspace.create",{...e,idempotencyKey:e.idempotencyKey??Q()},{timeoutMs:tu}),r=t?.workspace,s=t?.initialAgent,o=iu(t?.proposalOrigin);let i;if(s!=null){if(typeof s!="object"||typeof s.id!="string"||s.id.length===0)return{success:!1,error:"workspace.create returned an initialAgent without a valid daemon-assigned id"};i=s}return r&&typeof r=="object"?{success:!0,workspace:we(r),...i?{initialAgent:i}:{},...o?{proposalOrigin:o}:{}}:{success:!0}}catch(t){const r=_(t),s=lt(t);if(s)return{success:!1,error:r,conflict:s};const o=Jn(t),i=ru(t),a=zc(t?.data);return o?{success:!1,error:r,errorCode:o,...i?{launchFailure:i}:{},...a?{baseRefreshFailure:a}:{}}:{success:!1,error:r}}}async update(e){const{id:t,...r}=e;try{const o=(await u("workspace.update",{workspaceId:t,...r}))?.workspace;return o&&typeof o=="object"?{success:!0,workspace:we(o)}:{success:!0}}catch(s){const o=s instanceof Error?s.message:String(s),i=lt(s);return i?{success:!1,error:o,conflict:i}:{success:!1,error:o}}}async delete(e,t){const r=t?.undoDelayMs;try{const s=await u("workspace.delete",r&&r>0?{workspaceId:e,undoDelayMs:r}:{workspaceId:e},{timeoutMs:eu}),o=s?.scheduled===!0,i=typeof s?.deleteAt=="string"?s.deleteAt:void 0;return o&&i?{success:!0,scheduled:!0,deleteAt:i}:{success:!0}}catch(s){return{success:!1,error:_(s)}}}async findByPullRequest(e){const r=(await u("workspace.findByPullRequest",{url:e}))?.workspaces;if(!Array.isArray(r)||!r.every(su))throw new Error("Invalid workspace.findByPullRequest response shape");return r}async cancelDelete(e){try{return{success:!0,cancelled:(await u("workspace.cancelDelete",{workspaceId:e}))?.cancelled===!0}}catch(t){return{success:!1,error:_(t)}}}async archive(e){return b("workspace.archive",{workspaceId:e})}async unarchive(e){return b("workspace.unarchive",{workspaceId:e})}async retire(e){try{const r=(await u("workspace.retire",{workspaceId:e}))?.workspace;return{success:!0,...r&&typeof r=="object"?{workspace:we(r)}:{}}}catch(t){const r=Jn(t);return{success:!1,error:_(t),...r?{errorCode:r}:{}}}}async markSeen(e){return b("workspace.markSeen",{workspaceId:e})}async setActive(e){return b("workspace.setActive",{workspaceId:e})}async recentViews(){return{}}async getTokenUsage(e){const r=(await u("workspace.getTokenUsage",{workspaceId:e}))?.tokenUsage;return r&&typeof r=="object"?Qc(r):null}async diskUsage(e){try{const t=await u("workspace.diskUsage",{workspaceId:e}),r=t?.diskUsage,s={refreshing:t?.refreshing===!0};return r&&typeof r=="object"&&(s.diskUsage=r),s}catch(t){if(t instanceof Yt&&(t.rpcCode===-32601||t.code==="METHOD_NOT_FOUND"))return null;throw t}}async getContext(e){const t=await u("workspace.getContext",{workspaceId:e});return(Array.isArray(t?.items)?t.items:[]).filter(Yn)}async updateContext(e,t){const r=await u("workspace.updateContext",{workspaceId:e,items:t});return(Array.isArray(r?.items)?r.items:[]).filter(Yn)}async getBrowserClient(e){const t=await u("workspace.getBrowserClient",{workspaceId:e});return Zn(t?.browserClient,"workspace.getBrowserClient")}async setBrowserClient(e,t){const r=await u("workspace.setBrowserClient",{workspaceId:e,clientId:t});return Zn(r?.browserClient,"workspace.setBrowserClient")}async setHome(e,t){const r=await u("workspace.setHome",{workspaceId:e,to:t}),s=Zr(r?.home);if(!s)throw new Error("Invalid workspace.setHome response shape");return s}subscribe(e){return Je({channel:{subscribeMethod:"workspace.subscribe",unsubscribeMethod:"workspace.unsubscribe",continuation:{method:"workspace.list",key:"workspaces",params:t=>({includeArchived:!0,...t.includeRetired===!0?{includeRetired:!0}:{}})}},getId:t=>String(t.id??t.workspaceId??""),normalize:t=>we(t),handler:e})}}class Xr{constructor(){y(this,"workspaces",new au);y(this,"agents",new Ci);y(this,"notes",new Za);y(this,"tasks",new Bc);y(this,"comments",new ca);y(this,"git",new ja);y(this,"files",new wa);y(this,"terminals",new qc);y(this,"settings",new fc);y(this,"specialists",new kc);y(this,"integrations",new qa);y(this,"scripts",new ec);y(this,"setupScripts",new gc);y(this,"events",new da);y(this,"models",new Ha);y(this,"providers",new Qa);y(this,"stats",new Ic);y(this,"voice",new Tc);y(this,"chat",new ta);y(this,"skills",new mc);y(this,"browser",new Bi);y(this,"system",new Rc);y(this,"server",new Kr);y(this,"push",new Mc);y(this,"drafts",new ua);y(this,"clients",new na)}}const nt={FileChanged:"file:changed",AgentIdle:"agent:idle",NoteUpdated:"note:updated",TaskStatusChanged:"task:status-changed"},pt="2026-01-01T00:00:00.000Z",O=dr("ws-mock-1"),cu=Ns("00000000-0000-4000-8000-000000000010"),es=`terminal-${O}-default`,ts=`terminal-${O}-2`,Qn=[{id:es,name:"Terminal",type:"terminal",workspaceId:String(O),createdAt:pt},{id:ts,name:"Terminal 2",type:"terminal",workspaceId:String(O),createdAt:pt}],Xn={[es]:`$ pnpm run dev\r
1
+ var rs=Object.defineProperty;var sn=n=>{throw TypeError(n)};var ss=(n,e,t)=>e in n?rs(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>ss(n,typeof e!="symbol"?e+"":e,t),bt=(n,e,t)=>e.has(n)||sn("Cannot "+t);var A=(n,e,t)=>(bt(n,e,"read from private field"),t?t.call(n):e.get(n)),V=(n,e,t)=>e.has(n)?sn("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Ie=(n,e,t,r)=>(bt(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),kt=(n,e,t)=>(bt(n,e,"access private method"),t);import{d as ar,b as os,C as is}from"./B5aYN90J.js";import{bm as T}from"./C0QTy0Sy.js";import{fU as as,as as ve,r_ as cr,i as cs,h as It,bq as ur,Cp as us,ag as ls,q as it,m5 as ds,ns as fs,Jv as ps,$ as St,ac as wt,tU as gs,av as ys,E as ms,au as hs,j as vs,aL as bs,aM as ks,aS as Is,aF as Ss,aO as ws,aK as As,aR as Ts,aJ as Es,aN as Cs,aP as Rs,aI as _s,aQ as Ms,aD as Ps,aH as Os,aG as xs,n_ as lr,iC as dr,br as De,it as Ns,ib as Bs,b0 as Ls}from"./_LtUY0jS.js";import{M as ae,O as ce,h as u,p as js,q as Ds,L as Us,i as Jt,k as Oe,U as qs,a as Fs,N as $s,e as Ws,s as Gs,r as Hs}from"./C2jYl_tm.js";import{b as on,B as Yt}from"./C7LIHk5_.js";import{c as Ne}from"./ChTqQfQN.js";import{bV as Vs,br as zs,aD as ye,bH as At}from"./3SdAC2_C.js";import{a as Ks}from"./BdWqymET.js";import{i as ee}from"./BBWuirRW.js";import{L as Js}from"./DONrLvvt.js";import{i as Ys,C as fr,g as Zs}from"./DypB-Dwi.js";import{g as Qs}from"./_WGu_9si.js";import{R as Xs,G as eo,b as to}from"./Bqd7fdCF.js";import{r as te,b as no,i as ro}from"./uXuxG9cN.js";import{o as Be,s as P,c as so,n as ne,b as oo,r as Tt}from"./CIyUrgF0.js";import{Z as io}from"./CrD0jtXE.js";const ao=["high","medium","low"],co=["pending","in_progress","completed"],uo=256;function Z(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function lo(n){return Z(n)?typeof n.content=="string"&&ao.includes(n.priority)&&co.includes(n.status):!1}function pr(n){return Z(n)&&n.type==="plan"&&Array.isArray(n.entries)&&n.entries.length<=uo&&n.entries.every(lo)}function an(n){return n?.type==="plan"?pr(n):typeof n=="object"&&n!==null&&(typeof n.type=="string"&&["text","code","tool_use","tool_result","thinking","image","audio","video","file","nav-link","proposal","plan"].includes(n.type)||n.kind==="nav-link"&&typeof n.target=="string"||ar(n.kind)&&!!n.preview)}const fo=/\.(?:mp4|webm|mov|m4v)$/i,po=/^video\/[a-z0-9][a-z0-9.+-]*$/i,go=new Set(["video/mp4","video/webm","video/quicktime","video/x-m4v","video/m4v"]);function Ft(n){if(typeof n!="string")return;const e=n.split(";",1)[0].trim().toLowerCase();return po.test(e)?e:void 0}function yo(n,e){if(typeof n!="string"||n.length===0||n!==n.trim())return null;let t;try{t=new URL(n)}catch{return null}if(t.protocol!=="https:"||t.username||t.password)return null;const r=Ft(e),s=r&&go.has(r)?r:void 0;return!s&&!fo.test(t.pathname)?null:{kind:"remote",url:n,...s?{mimeType:s}:{}}}function mo(n,e){if(typeof n!="string"||!n.startsWith("intent://local/")||!e||!/^[A-Za-z0-9._-]+$/.test(e)||n.includes("?")||n.includes("#"))return null;const r=n.slice(9).split("/").slice(1);let s,o;if(r[0]==="file")s=e,o=r.slice(1);else if(r.length>=3&&r[1]==="file"){try{s=decodeURIComponent(r[0])}catch{return null}if(s!==e)return null;o=r.slice(2)}else return null;const i=[];for(const l of o){let d;try{d=decodeURIComponent(l)}catch{return null}if(!d||d==="."||d===".."||d.includes("/")||d.includes("\\")||d.includes("\0"))return null;i.push(d)}if(i.length===0||/^[A-Za-z]:/.test(i[0]))return null;const a=i[i.length-1].toLowerCase(),c=a.endsWith(".mp4")?"video/mp4":a.endsWith(".webm")?"video/webm":null;return c?{kind:"workspace",url:`workspace-file://${s}/${i.map(encodeURIComponent).join("/")}`,mimeType:c}:null}function Et(n,e,t){return yo(n,e)??mo(n,t)}function Ue(n,e,t){return{type:"video",source:e,...typeof n.id=="string"?{id:n.id}:{},...Z(n.metadata)?{metadata:n.metadata}:{},...typeof t=="string"&&t.length>0?{fileName:t}:{}}}function ho(n,e){if(!Z(n))return null;const t=n.type;if((t==="file"||t==="blob")&&typeof n.data=="string"&&n.data){const r=Ft(n.mimeType);if(r)return Ue(n,{kind:"inline",data:n.data,mimeType:r},n.fileName)}if(t==="resource"&&Z(n.resource)){const r=n.resource,s=Ft(r.mimeType);if(s&&typeof r.blob=="string"&&r.blob)return Ue(n,{kind:"inline",data:r.blob,mimeType:s},r.name);const o=Et(r.uri,r.mimeType,e);return o?Ue(n,o,r.name):null}if(t==="resource_link"){const r=Et(n.uri,n.mimeType,e);return r?Ue(n,r,n.name):null}if(t==="file"){const r=Et(n.url??n.uri,n.mimeType,e);return r?Ue(n,r,n.fileName):null}return null}function cn(n,e){if(!Array.isArray(n))return n;let t=!1;const r=n.map(s=>{const o=gr(s,e);return o!==s&&(t=!0),o});return t?r:n}function gr(n,e){const t=ho(n,e);if(t)return t;if(!Z(n)||n.type!=="tool_result")return n;const r=cn(n.output,e),s=cn(n.content,e);return r===n.output&&s===n.content?n:{...n,output:r,content:s}}function Uu(n,e,t){if(e!=="assistant")return n;let r=!1;const s=n.map(o=>{const i=gr(o,t);return i!==o&&(r=!0),i});return r?s:n}function vo(n){return n.kind==="inline"?`inline:${n.mimeType}:${n.data}`:`${n.kind}:${n.url}`}function qu(n){const e=new Set;function t(r){let s=!1;const o=[];for(const i of r){if(Z(i)&&i.type==="video"&&Z(i.source)){const a=i.source,c=vo(a);if(e.has(c)){s=!0;continue}e.add(c)}if(Z(i)&&i.type==="tool_result"){const a=Array.isArray(i.output)?t(i.output):i.output,c=Array.isArray(i.content)?t(i.content):i.content;if(a!==i.output||c!==i.content){o.push({...i,output:a,content:c}),s=!0;continue}}o.push(i)}return s?o:r}return t(n)}const bo=new Set(["text","code","tool_use","tool_result","thinking","image","audio","file","nav-link","proposal","plan"]);function ko(n){return{content:n.content,priority:n.priority,status:n.status}}function Io(n){if(!pr(n))throw new Error(`Invalid plan block: required bounded 'entries' snapshot missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);return{type:"plan",...typeof n.id=="string"?{id:n.id}:{},entries:n.entries.map(ko)}}const un=/^image\/[a-z0-9][a-z0-9.+-]*$/i;function So(n){const e=Object.prototype.hasOwnProperty.call(n,"data"),t=typeof n.data=="string",r=n.dataTruncated!==void 0,s=n.dataIsThumbnail!==void 0,o=n.dataBytes!==void 0;if(Object.prototype.hasOwnProperty.call(n,"attachmentId")){if(typeof n.attachmentId!="string"||n.attachmentId.trim().length===0||e||r||s||o||n.mimeType!==void 0&&(typeof n.mimeType!="string"||!un.test(n.mimeType)))throw new Error("Invalid image attachment reference (PROTOCOL §5.5)");return}if(typeof n.mimeType!="string"||!un.test(n.mimeType))throw new Error(`Invalid image block: required image 'mimeType'. Received: ${JSON.stringify(n)}`);if(e&&!t)throw new Error(`Invalid image block: present 'data' must be a string. Received: ${JSON.stringify(n)}`);if(!r){if(!t||s||o)throw new Error(`Invalid image block: full images require 'data' without slim flags. Received: ${JSON.stringify(n)}`);return}if(n.dataTruncated!==!0||!Number.isSafeInteger(n.dataBytes)||n.dataBytes<0||(t?n.dataIsThumbnail!==!0:s))throw new Error(`Invalid image block: malformed slim projection metadata. Received: ${JSON.stringify(n)}`)}function wo(n){if(!n||typeof n!="object")throw new Error("Invalid block: must be an object");const e=os(n);if(e)return{type:"proposal",kind:e.kind,payload:e.payload,preview:e.preview,applyToolCallId:e.applyToolCallId,proposal:e,id:n.id,metadata:n.metadata};if(n.kind==="nav-link"&&typeof n.target=="string")return{type:"nav-link",kind:"nav-link",target:n.target,label:n.label,id:n.id,metadata:n.metadata};if((n.type==="proposal"||ar(n.kind))&&n.preview){const t=n.proposal??{kind:n.kind,payload:n.payload??{},preview:n.preview,applyToolCallId:n.applyToolCallId};return{type:"proposal",kind:t.kind,payload:t.payload,preview:t.preview,applyToolCallId:t.applyToolCallId,proposal:t,id:n.id,metadata:n.metadata}}if(typeof n.type!="string")throw new Error(`Invalid ContentBlock: missing canonical 'type' field (PROTOCOL §7). Received: ${JSON.stringify(n)}`);if(!bo.has(n.type))throw new Error(`Invalid ContentBlock: unknown 'type' "${n.type}" (PROTOCOL §7). Received: ${JSON.stringify(n)}`);return Ao(n),To(n)}function Ao(n){if(n.text===void 0&&typeof n.content=="string")throw new Error(`Invalid ContentBlock: legacy 'content' field is not part of PROTOCOL §7 (use 'text'). Received: ${JSON.stringify(n)}`);if(n.name===void 0&&typeof n.toolName=="string")throw new Error(`Invalid ContentBlock: legacy 'toolName' field is not part of PROTOCOL §7 (use 'name'). Received: ${JSON.stringify(n)}`);if(n.type==="tool_result"&&n.tool_use_id===void 0&&typeof n.toolCallId=="string")throw new Error(`Invalid ContentBlock: tool_result must use 'tool_use_id' (PROTOCOL §7). Received: ${JSON.stringify(n)}`);if(n.is_error===void 0&&n.isError!==void 0)throw new Error(`Invalid ContentBlock: legacy 'isError' field is not part of PROTOCOL §7 (use 'is_error'). Received: ${JSON.stringify(n)}`)}function To(n){switch(n.type){case"text":case"thinking":if(typeof n.text!="string")throw new Error(`Invalid ${n.type} block: required 'text' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"tool_use":if(typeof n.name!="string")throw new Error(`Invalid tool_use block: required 'name' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"tool_result":if(typeof n.tool_use_id!="string")throw new Error(`Invalid tool_result block: required 'tool_use_id' field missing (PROTOCOL §7). Received: ${JSON.stringify(n)}`);break;case"image":So(n);break;case"audio":if(typeof n.data!="string"||typeof n.mimeType!="string")throw new Error(`Invalid ${n.type} block: required 'data'/'mimeType' fields missing. Received: ${JSON.stringify(n)}`);break;case"file":if(typeof n.attachmentId!="string"||n.attachmentId.length===0||typeof n.fileName!="string"||n.fileName.length===0)throw new Error(`Invalid file block: required 'attachmentId'/'fileName' fields missing (PROTOCOL §5.5). Received: ${JSON.stringify(n)}`);break;case"code":case"nav-link":case"proposal":break;case"plan":return Io(n)}return{...n}}const Eo=["user","assistant","tool","system","error"];function yr(n){return typeof n=="number"&&Number.isInteger(n)&&n>0}function mr(n){if(!n||typeof n!="object")return null;const e=n;return yr(e.position)?e:null}function Co(n){const{position:e,queueSize:t}=n;return yr(t)&&t>=e?T.shared_mergeQueue_positionOfTotal_label({position:e,total:t}):T.shared_mergeQueue_position_label({position:e})}function Ro(n){if(typeof n!="number"||!Number.isFinite(n)||n<0)return null;const e=Math.max(1,Math.ceil(n/60));return e<60?T.shared_mergeQueue_etaMinutes_label({minutes:e}):T.shared_mergeQueue_etaHours_label({hours:Math.floor(e/60),minutes:e%60})}function Fu(n){const e=mr(n);if(!e)return null;const t=Ro(e.estimatedTimeToMerge),r=Co(e);return t?`${r} · ${t}`:r}const hr=-32602,$t="not-found";function $u(n){if(!n||typeof n!="object"||n.rpcCode!==hr)return!1;const e=n.data;return!e||typeof e!="object"?!1:e.code===$t}function _o(n){if(!n||typeof n!="object")return!1;const{message:e,rpcCode:t,code:r,data:s}=n,o=s&&typeof s=="object"?s.code:void 0;return r===$t||o===$t?!0:t===hr&&typeof e=="string"&&/not found/i.test(e)}function Mo(n){if(n.notificationsMuted===!0||as(n)!=="topLevel"||n.lastMessageRole!=="assistant")return!1;const e=ln(n.lastMessageId);return e===void 0?!1:e!==ln(n.metadata?.lastSeenMessageId)}function ln(n){return typeof n=="string"&&n.length>0?n:void 0}const Po=1e3;async function ut(n,e,t){const r=e??{},s=await n(Object.keys(r).length>0?r:void 0);if(!s||typeof s!="object")return s;const o=s[t];let i=s.nextToken;if(typeof i!="string"||i.length===0)return s;const a=Array.isArray(o)?[...o]:[];for(let c=1;typeof i=="string"&&i.length>0&&!(c>=Po);c+=1){const l=await n({...r,nextToken:i}),d=l&&typeof l=="object"?l[t]:void 0;Array.isArray(d)&&a.push(...d),i=l&&typeof l=="object"?l.nextToken:void 0}return{...s,[t]:a,nextToken:null}}const Wu=1e3,Oo="goal",xo=/^\p{White_Space}*\/goal(?:\p{White_Space}|$)/u;function Gu(n){return xo.test(n)}const No=new Set(["set","updated","unchanged","shown"]),Bo=new Set(["set","updated","unchanged","cleared"]),Lo=new Set(["set","updated","unchanged","shown","cleared"]);function Ge(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}function Zt(n){return n===null?null:typeof n=="string"?n:void 0}function Qt(n){if(!Ge(n))return;const{principalId:e,displayName:t,login:r}=n;if(!(typeof e!="string"||e.trim().length===0))return{principalId:e,displayName:typeof t=="string"?t:null,login:typeof r=="string"?r:null}}function vr(n,e){const t=n?Qt(e):void 0;return t?{goalSetBy:t}:{}}function jo(n){if(!Ge(n)||!Ge(n.command))return null;const{name:e,action:t,goal:r,goalSetBy:s,noticeMessageId:o}=n.command,i=Zt(r);return e!==Oo||typeof t!="string"||!No.has(t)||i===void 0?null:{action:t,goal:i,...vr(i,s),...typeof o=="string"?{noticeMessageId:o}:{}}}function Do(n){if(!Ge(n))return null;const{action:e,goal:t,goalSetBy:r,noticeMessageId:s}=n,o=Zt(t);return typeof e!="string"||!Bo.has(e)||o===void 0?null:{action:e,goal:o,...vr(o,r),...typeof s=="string"?{noticeMessageId:s}:{}}}function Hu(n){const e=n?.metadata;if(!e||e.type!=="goal_command")return null;const t=e.action;if(typeof t!="string"||!Lo.has(t))return null;const r=Zt(e.goal)??null,s=e.fromPrincipalId;return{action:t,goal:r&&r.length>0?r:null,...typeof s=="string"&&s.length>0?{fromPrincipalId:s}:{}}}function Vu(n){if(!Object.prototype.hasOwnProperty.call(n,"goal"))return{present:!1};const e=n.goal;if(e===null)return{present:!0,goal:void 0,goalSetBy:void 0};if(typeof e=="string"){const t=e.length>0?e:void 0;return{present:!0,goal:t,goalSetBy:t?Qt(n.goalSetBy):void 0}}return{present:!1}}function dn(n){const e=n&&typeof n=="object"&&typeof n.message=="string"?n.message:void 0;if((n&&typeof n=="object"?n.rpcCode:void 0)!==-32602)return{kind:"failed",...e?{message:e}:{}};const r=n.data,s=Ge(r)?r.code:void 0;return s==="goal-too-long"?{kind:"tooLong"}:s==="goal-attachments-not-allowed"?{kind:"attachments"}:s==="agent-retired"?{kind:"retired"}:s==="workspace-retired"?{kind:"workspaceRetired"}:{kind:"invalid",message:e??""}}const Uo="application/vnd.intent.secret-request+json";function qo(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.requestId=="string"&&e.requestId.length>0&&typeof e.agentId=="string"&&typeof e.name=="string"&&e.name.length>0&&typeof e.reason=="string"}function Fo(n){if(!n||typeof n!="object")return!1;const e=n;if(e.type!=="resource")return!1;const t=e.resource;return typeof t=="object"&&t!==null&&t.mimeType===Uo}function zu(n){if(!Fo(n))return null;const e=n.resource.text;if(typeof e!="string")return null;try{const t=JSON.parse(e);return qo(t)?t:null}catch{return null}}function br(n){return!!n&&typeof n=="object"&&typeof n.name=="string"}function kr(n){return br(n)&&typeof n.requestId=="string"}function $o(n){const e=n?.outcome;return kr(n)&&(e==="provided"||e==="declined")}function Wo(n){if(!n||typeof n!="object")return null;const e=n,t=r=>Array.isArray(e[r])?e[r]:[];return{secrets:t("secrets").filter(br).map(({name:r})=>({name:r})),pendingRequests:t("pendingRequests").filter(kr).map(({requestId:r,name:s})=>({requestId:r,name:s})),answeredRequests:t("answeredRequests").filter($o).map(({requestId:r,name:s,outcome:o})=>({requestId:r,name:s,outcome:o}))}}const Go=Ne("DeltaSubscription");function Ho(n,e){if(n!=="subscription.push"||!e||typeof e!="object")return null;const t=e,r=typeof t.subscriptionId=="string"?t.subscriptionId:void 0,s=typeof t.seq=="number"?t.seq:void 0;if(!r||s===void 0)return null;if(t.kind==="snapshot")return{subscriptionId:r,kind:"snapshot",seq:s,snapshot:Array.isArray(t.snapshot)?t.snapshot:[],...typeof t.nextToken=="string"&&t.nextToken.length>0?{nextToken:t.nextToken}:{}};if(t.kind==="delta"){const o=t.delta&&typeof t.delta=="object"?t.delta:{};return{subscriptionId:r,kind:"delta",seq:s,delta:{added:Array.isArray(o.added)?o.added:[],updated:Array.isArray(o.updated)?o.updated:[],removedIds:Array.isArray(o.removedIds)?o.removedIds.map(i=>String(i)):[]}}}return null}class fn{constructor(e,t){y(this,"items",new Map);y(this,"removedSinceSnapshot",new Set);y(this,"changedSinceSnapshot",new Set);y(this,"expectedSeq",0);y(this,"seeded",!1);y(this,"epochValue",0);this.getId=e,this.normalize=t}reset(){this.items.clear(),this.removedSinceSnapshot.clear(),this.changedSinceSnapshot.clear(),this.expectedSeq=0,this.seeded=!1,this.epochValue+=1}get epoch(){return this.epochValue}applySnapshot(e,t){this.items.clear(),this.removedSinceSnapshot.clear(),this.changedSinceSnapshot.clear(),this.epochValue+=1;for(const r of t)this.upsert(r);this.expectedSeq=e+1,this.seeded=!0}applyDelta(e,t){if(!this.seeded||e!==this.expectedSeq)return!1;for(const r of[...t.added??[],...t.updated??[]])if(this.upsert(r),r&&typeof r=="object"){const s=this.getId(r);s&&this.changedSinceSnapshot.add(s)}for(const r of t.removedIds??[])this.items.delete(String(r)),this.removedSinceSnapshot.add(String(r));return this.expectedSeq=e+1,!0}fillFromPage(e){for(const t of e){if(!t||typeof t!="object")continue;const r=this.getId(t);!r||this.items.has(r)||this.removedSinceSnapshot.has(r)||this.upsert(t)}}completeRow(e){const t=this.getId(e);return!t||!this.items.has(t)||this.changedSinceSnapshot.has(t)?!1:(this.upsert(e),!0)}values(){return[...this.items.values()]}upsert(e){if(!e||typeof e!="object")return;const t=e,r=this.getId(t);if(!r)return;const s=this.normalize(t);s!==null&&this.items.set(r,s)}}const Vo=32,zo=1e3,pn=3,Ko=250,Jo=1e3,Yo=3e4;function qe(n){return Math.min(Jo*2**n,Yo)}function Je(n){const{channel:e,getId:t,normalize:r,handler:s}=n,o=e.dynamic,i={...e.params},a=(g,p)=>({subscriptionId:g,...typeof p.workspaceId=="string"?{workspaceId:p.workspaceId}:{}}),c=new fn(t,r);let l=!1,d,m=0,I=0,S=0,h;const w=new Map,R=[],H=g=>{R.push(g),R.length>Vo&&R.shift()},N=g=>{const p=R.filter(f=>f.subscriptionId===g);for(const f of p)R.splice(R.indexOf(f),1);for(const f of p)le(f)},F=()=>{if(!o)return c.values();const g=[];for(const p of w.values())g.push(...p.reconciler.values());return g},B=()=>{l||s(F())},ue=()=>{if(o){for(const g of w.values())if(g.subscriptionId===void 0)return!0;return!1}return d===void 0},$=()=>{R.length>0&&!ue()&&(R.length=0)},U=()=>{if(o)return;h!==void 0&&(clearTimeout(h),h=void 0),m+=1;const g=m;u(e.subscribeMethod,i).then(p=>{const f=p?.subscriptionId;if(g!==m||l){f&&u(e.unsubscribeMethod,a(f,i)).catch(()=>{});return}if(!f){const v=qe(I);I+=1,h=setTimeout(()=>{h=void 0,l||U()},v);return}d=f,I=0,N(f),$()}).catch(()=>{if(g!==m||l)return;const p=qe(I);I+=1,h=setTimeout(()=>{h=void 0,l||U()},p)})},X=()=>{if(o||(m+=1,h!==void 0&&(clearTimeout(h),h=void 0),!d))return;const g=d;d=void 0,u(e.unsubscribeMethod,a(g,i)).catch(()=>{})},D=(g,p)=>{if(!o)return;p.retryTimer!==void 0&&(clearTimeout(p.retryTimer),p.retryTimer=void 0),p.generation+=1;const f=p.generation;u(e.subscribeMethod,p.params).then(v=>{const k=v?.subscriptionId;if(l||w.get(g)!==p||f!==p.generation){k&&u(e.unsubscribeMethod,a(k,p.params)).catch(()=>{});return}if(!k){const E=qe(p.retryAttempt);p.retryAttempt+=1,p.retryTimer=setTimeout(()=>{p.retryTimer=void 0,!l&&w.get(g)===p&&D(g,p)},E);return}p.subscriptionId=k,p.retryAttempt=0,N(k),$()}).catch(()=>{if(l||w.get(g)!==p||f!==p.generation)return;const v=qe(p.retryAttempt);p.retryAttempt+=1,p.retryTimer=setTimeout(()=>{p.retryTimer=void 0,!l&&w.get(g)===p&&D(g,p)},v)})},J=g=>{g.generation+=1,g.retryTimer!==void 0&&(clearTimeout(g.retryTimer),g.retryTimer=void 0);const p=g.subscriptionId;g.subscriptionId=void 0,p&&u(e.unsubscribeMethod,a(p,g.params)).catch(()=>{})},Y=(g,p)=>{p.awaitingResnapshot||(p.awaitingResnapshot=!0,p.seeded=!1,p.reconciler.reset(),J(p),D(g,p),B())},ht=g=>{if(l||!o)return;const p=new Set(g);let f=!1;for(const[v,k]of[...w])p.has(v)||(w.delete(v),J(k),f=!0);for(const v of p){if(w.has(v))continue;const k={generation:0,params:{...o.paramsForId(v)},reconciler:new fn(t,r),seeded:!1,awaitingResnapshot:!1,retryAttempt:0,continuationFailures:0};w.set(v,k),D(v,k),f=!0}f&&B()},Ye=()=>{c.reset(),X(),U()},Le=(g,p,f,v)=>{const k=e.continuation;if(!k)return;const E=g.epoch,C=()=>l||g.epoch!==E;(async()=>{let fe=f;for(let rn=0;fe&&rn<zo;rn+=1){let pe;for(let ge=0;ge<pn;ge+=1){if(ge>0&&(await new Promise(ns=>setTimeout(ns,Ko*2**(ge-1))),C())||(pe=await u(k.method,{...k.params(p),nextToken:fe}).catch(()=>{}),C()))return;if(pe)break}if(!pe){const ge=v.failures();Go.warn(`${k.method} continuation page failed ${pn} times; resubscribing ${e.subscribeMethod} for a fresh snapshot`),v.setFailures(ge+1),setTimeout(()=>{C()||v.resubscribe()},qe(ge));return}const Ze=pe[k.key];g.fillFromPage(Array.isArray(Ze)?Ze:[]),B(),ke(g,Array.isArray(Ze)?Ze:[]),fe=typeof pe.nextToken=="string"&&pe.nextToken?pe.nextToken:null}v.setFailures(0)})()},ke=(g,p)=>{const f=n.complete;if(!f)return;const v=g.epoch;for(const k of p){if(!k||typeof k!="object")continue;const E=f(k);E&&E.then(C=>{l||g.epoch!==v||g.completeRow(C)&&B()}).catch(()=>{})}},le=g=>{if(!l){if(o){for(const[p,f]of w)if(f.subscriptionId===g.subscriptionId){g.kind==="snapshot"?(f.awaitingResnapshot=!1,f.seeded=!0,f.reconciler.applySnapshot(g.seq,g.snapshot??[]),B(),ke(f.reconciler,g.snapshot??[]),g.nextToken&&Le(f.reconciler,f.params,g.nextToken,{failures:()=>f.continuationFailures,setFailures:v=>{f.continuationFailures=v},resubscribe:()=>{w.get(p)===f&&Y(p,f)}})):f.awaitingResnapshot||(f.reconciler.applyDelta(g.seq,g.delta??{})?B():Y(p,f));return}ue()&&H(g);return}if(g.subscriptionId!==d){ue()&&H(g);return}g.kind==="snapshot"?(c.applySnapshot(g.seq,g.snapshot??[]),B(),ke(c,g.snapshot??[]),g.nextToken&&Le(c,i,g.nextToken,{failures:()=>S,setFailures:p=>{S=p},resubscribe:Ye})):c.applyDelta(g.seq,g.delta??{})?B():Ye()}},je=ae(g=>{const p=Ho(g.method,g.params);p&&le(p)}),vt=ce(()=>{if(!l){m+=1,d=void 0,I=0,h!==void 0&&(clearTimeout(h),h=void 0),c.reset(),R.length=0;for(const[g,p]of w)p.generation+=1,p.subscriptionId=void 0,p.seeded=!1,p.awaitingResnapshot=!1,p.retryAttempt=0,p.retryTimer!==void 0&&(clearTimeout(p.retryTimer),p.retryTimer=void 0),p.reconciler.reset(),D(g,p);o||U()}}),de=o?o.subscribeIds(ht):void 0;return o||U(),()=>{l=!0,h!==void 0&&(clearTimeout(h),h=void 0),je(),vt(),de?.(),X();for(const g of w.values())J(g);w.clear()}}const Zo=1e3;function Qo(n){if(!n||typeof n!="object")return;const e=n.nextToken;return typeof e=="string"&&e.length>0?e:void 0}async function Ce(n,e,t){const r=[],s=new Set;let o;for(let i=0;i<Zo;i++){const a=await n(o?{...e,nextToken:o}:e),c=a&&typeof a=="object"?a[t]:void 0;if(Array.isArray(c)&&r.push(...c),o=Qo(a),!o||s.has(o))break;s.add(o)}return r}function Xo(n){const e=new Map,t=[];for(const r of n){const s=r&&typeof r=="object"?r.threadId:void 0;if(typeof s!="string"||!s){t.push(r);continue}e.delete(s),e.set(s,r)}return[...e.values(),...t]}function Ir(n,e){if(!n||typeof n!="object")return null;const t=n;return t.commentsTruncated!==!0||typeof t.threadId!="string"?null:e(t.threadId).then(r=>{if(!r||typeof r!="object")return t;const{rootComment:s,replies:o}=r;if(!s||typeof s!="object"||!Array.isArray(o))return t;const{commentsTruncated:i,...a}=t;return{...a,comments:[s,...o]}},()=>t)}async function ei(n,e,t){const r=Xo(await Ce(n,e,"threads"));return Promise.all(r.map(s=>Ir(s,t)??s))}const ti=1e3;function gn(n){if(!n||typeof n!="object")return;const e="note"in n?n.note:n;return e&&typeof e=="object"?e:void 0}function yn(n){const e=n.nextContentOffset;return n.contentTruncated===!0&&typeof e=="number"&&e>0?e:void 0}async function ni(n,e,t){const r=gn(t);if(!r)return{result:t,retry:!1};let s=yn(r);if(s===void 0)return{result:t,retry:!1};let o=typeof r.content=="string"?r.content:"";for(let S=1;S<ti&&s!==void 0;S++){const h=gn(await n({...e,contentOffset:s}));if(h&&h.rev!==r.rev)return{result:t,retry:!0};if(!h||typeof h.content!="string"||h.contentOffset!==s)return{result:t,retry:!1};o+=h.content,s=yn(h)}if(s!==void 0||new TextEncoder().encode(o).length!==r.contentBytes)return{result:t,retry:!1};const{contentTruncated:i,contentBytes:a,contentOffset:c,nextContentOffset:l,...d}=r,m={...d,content:o};return{result:t&&typeof t=="object"&&"note"in t?{...t,note:m}:m,retry:!1}}async function Sr(n,e){let t;for(let r=0;r<3;r++){t=await n(e);const{result:s,retry:o}=await ni(n,e,t);if(!o)return s}return t}function Q(){const n=globalThis.crypto;return typeof n?.randomUUID=="function"?n.randomUUID():`idk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function _(n){const e=n instanceof Error?n.message:String(n);if(e==="Internal error"&&n&&typeof n=="object"){const t=n.data;if(typeof t=="string"&&t.length>0)return`${e}: ${t}`;if(t&&typeof t=="object"){const r=t.detail;if(typeof r=="string"&&r.length>0)return`${e}: ${r}`}}return e}const ri=-32005;function lt(n){if(!n||typeof n!="object"||n.rpcCode!==ri)return;const e=n.data;if(!(!e||typeof e!="object")&&e.code==="conflict")return{current:e.current}}function si(n){if(!n||typeof n!="object")return;const e=n.noteRev;return typeof e=="number"&&Number.isFinite(e)?e:void 0}function oi(n){if(!n||typeof n!="object")return;const{newContent:e,rev:t}=n;if(typeof e=="string")return typeof t=="number"&&Number.isFinite(t)?{newContent:e,rev:t}:{newContent:e}}async function b(n,e,t){try{const r=await(t!==void 0?u(n,e,t):u(n,e)),s=oi(r),o=si(r)??s?.rev;return{success:!0,...o!==void 0?{noteRev:o}:{},...s!==void 0?{newContent:s.newContent}:{}}}catch(r){const s=lt(r);return s?{success:!1,error:_(r),conflict:s}:ii(r)?{success:!1,error:_(r),contentBaseMismatch:!0}:{success:!1,error:_(r)}}}function ii(n){if(!n||typeof n!="object"||n.rpcCode!==-32602)return!1;const e=n.data;return!!e&&typeof e=="object"&&e.code==="content-base-mismatch"}function ai(n){if(!n||typeof n!="object")return;const e=n,t=e.id;if(typeof t=="string"&&t.length>0)return t;for(const r of["task","note","entity"]){const s=e[r];if(s&&typeof s=="object"){const o=s.id;if(typeof o=="string"&&o.length>0)return o}}}async function Wt(n,e,t){try{const r=await(t!==void 0?u(n,e,t):u(n,e)),s=ai(r);return s!==void 0?{success:!0,id:s}:{success:!0}}catch(r){const s=lt(r);return s?{success:!1,error:_(r),conflict:s}:{success:!1,error:_(r)}}}const ci=2e3;let Re=null,Ae=null;function ui(n,e){console.debug(`[live-support] workspace.list RPC (${n})${e?`: ${e}`:""}`)}function wr(n,e){if(Ae)return Ae;ui(n,e);const t=ut(r=>u("workspace.list",r),void 0,"workspaces").then(r=>{const o=(Array.isArray(r?.workspaces)?r.workspaces:[]).map(i=>String(i.id??i.workspaceId??"")).filter(i=>i.length>0);return Re={ids:o,fetchedAt:Date.now()},o});return Ae=t,t.catch(()=>{}).finally(()=>{Ae===t&&(Ae=null)}),t}async function li(n){return x!==null?[...x]:Re!==null&&Date.now()-Re.fetchedAt<ci?[...Re.ids]:wr(n)}const di=["workspace:created","workspace:updated","workspace:deleted"],fi=250;let x=null,Te=0;const dt=new Map;let pi=0,Ct=null,Rt=null,oe=0,Gt=!1,Ee=!1,_e;function Xt(){const n=x?[...x]:[];for(const e of dt.values())e(n)}function Ar(n,e){Gt=!0;const t=oe;Ae!==null&&(Ee=!0),wr(n,e).then(r=>{oe!==t&&(Te===0||(Ee=!0,x!==null))||(x=new Set(r),oe+=1,Xt())}).catch(()=>{if(x===null)for(const r of dt.values())r([])}).finally(()=>{Gt=!1,Ee&&(Ee=!1,_e=setTimeout(()=>{_e=void 0,Te>0&&Ar("follow-up")},fi))})}function se(n,e){if(_e===void 0){if(Gt){Ee=!0;return}Ar(n,e)}}function mn(n){if(!x){oe+=1,se("defensive-resync","workspace event before seed settled");return}x.has(n)||(x.add(n),oe+=1,Re=null,Xt())}function hn(n){if(!x){oe+=1,se("defensive-resync","workspace event before seed settled");return}x.has(n)&&(x.delete(n),oe+=1,Re=null,Xt())}function gi(n){if(!n||typeof n!="object")return;const e=n.event;return e&&typeof e=="object"?e.data:n.data}function vn(n){if(!n||typeof n!="object")return;const e=n;if(typeof e.workspaceId=="string"&&e.workspaceId.length>0)return e.workspaceId;const t=e.workspace;if(t&&typeof t=="object"){const r=t.id;if(typeof r=="string"&&r.length>0)return r}}function yi(n){if(!n||typeof n!="object")return!1;const e=n.workspace;return!e||typeof e!="object"?!1:e.archived===!0}function mi(n,e){if(!bi(n,e,di))return;const t=Er(e);if(t===void 0){se("defensive-resync","typeless event payload");return}const r=gi(e);if(t==="workspace:created"){const s=vn(r);if(!s){se("defensive-resync",`${t} without workspace id`);return}if(yi(r))return;mn(s);return}if(t==="workspace:deleted"){const s=vn(r);if(!s){se("defensive-resync",`${t} without workspace id`);return}hn(s);return}if(t==="workspace:updated"){const s=r&&typeof r=="object"?r:void 0,o=typeof s?.workspaceId=="string"?s.workspaceId:void 0,i=s?.changes;if(!o||!i||typeof i!="object"){se("defensive-resync",`${t} without workspaceId/changes`);return}const a=i.archived;a===!0?hn(o):a===!1&&mn(o)}}function en(n){let e=!1;Te+=1;const t=pi++;return dt.set(t,n),Te===1?(Ct=ae(r=>mi(r.method,r.params)),Rt=ce(()=>se("reconnect")),se("seed")):x!==null&&n([...x]),()=>{e||(e=!0,dt.delete(t),Te-=1,!(Te>0)&&(Ct?.(),Ct=null,Rt?.(),Rt=null,_e!==void 0&&(clearTimeout(_e),_e=void 0),Ee=!1,x=null,oe+=1))}}const Tr=new Map;function He(n,e){n&&e&&(Tr.set(n,e),ft.delete(n))}const hi=5e3,ft=new Map,_t=new Map;async function vi(n){let e;try{e=await li("resolver")}catch{return null}let t=!0;for(const r of e)try{const s=a=>u("note.list",a);let o;try{o=await Ce(s,{workspaceId:r,projection:"slim",limit:ve},"notes")}catch(a){if(!cr(a))throw a;o=await Ce(s,{workspaceId:r,limit:ve},"notes")}let i=!1;for(const a of o){const c=String(a.id??"");c&&He(c,r),c===n&&(i=!0)}if(i)return r}catch{t=!1}return t&&e.length>0&&ft.set(n,Date.now()),null}async function ie(n){const e=Tr.get(n);if(e)return e;const t=ft.get(n);if(t!==void 0){if(Date.now()-t<hi)return null;ft.delete(n)}const r=_t.get(n);if(r)return r;const s=vi(n).finally(()=>{_t.delete(n)});return _t.set(n,s),s}function Er(n){if(!n||typeof n!="object")return;const e=n.event;if(e&&typeof e=="object"){const r=e.type;if(typeof r=="string")return r}const t=n.type;return typeof t=="string"?t:void 0}function bi(n,e,t){if(n!=="events.event")return!1;const r=Er(e);return r===void 0?!0:t.includes(r)}const Cr=new Map,ki=41943040,Ii=/^response for agent\.getConversation exceeds maximum outbound frame size: ([1-9][0-9]*) bytes > 41943040 bytes$/;function Si(n){if(!n||typeof n!="object")return!1;const e=n;if(e.name!=="BackendError"||typeof e.message!="string")return!1;const t=Ii.exec(e.message);return t!==null&&Number(t[1])>ki}function wi(n,e){n&&e&&Cr.set(n,e)}function Qe(n){const e=new Date().toISOString(),t=String(n.id??""),r=n.acpSessionId?String(n.acpSessionId):null,s=String(n.workspaceId??"");wi(t,s);const o={...n,id:It(t),backendSessionId:r?It(r):null,workspaceId:ur(s),name:String(n.name??t),status:typeof n.status=="string"?n.status:cs.Pending,messages:Array.isArray(n.messages)?n.messages:[],createdAt:String(n.createdAt??e),updatedAt:String(n.updatedAt??e)};return typeof n.retiredAt=="string"&&n.retiredAt.length>0&&(o.retiredAt=n.retiredAt),typeof n.parentAgentId=="string"&&n.parentAgentId.length>0&&(o.parentAgentId=It(n.parentAgentId)),o.usingEarlierProfileSettings=n.usingEarlierProfileSettings===!0?!0:void 0,o.goal=typeof n.goal=="string"&&n.goal.length>0?n.goal:void 0,o.goalSetBy=o.goal?Qt(n.goalSetBy):void 0,o.providerReplacementRequired=Ai(n.providerReplacementRequired),o.permissionPolicy=typeof n.permissionPolicy=="string"||n.permissionPolicy===null?n.permissionPolicy:void 0,o.effectivePermissionPolicy=typeof n.effectivePermissionPolicy=="string"?n.effectivePermissionPolicy:void 0,typeof n.isBackground=="boolean"&&(o.metadata={...o.metadata,isBackground:n.isBackground},o.agentMetadata&&(o.agentMetadata={...o.agentMetadata,isBackground:n.isBackground})),o.hasUnread=Mo(o),o}function Ai(n){if(!n||typeof n!="object")return;const{providerRef:e,reason:t}=n;if(!(typeof e!="string"||e.length===0)&&!(t!=="profile-missing"&&t!=="provider-disabled"))return{providerRef:e,reason:t}}function Ti(n){if(!n||typeof n!="object")return;const{topLevel:e,delegated:t,background:r}=n;if(!(typeof e!="number"||typeof t!="number"||typeof r!="number"))return{topLevel:e,delegated:t,background:r}}function Ei(n){if(!n||typeof n!="object")return;const{running:e,byParent:t,orphaned:r}=n;if(typeof e!="number"||!t||typeof t!="object"||Array.isArray(t))return;const s={};for(const[i,a]of Object.entries(t)){const c=bn(a);if(!c)return;s[i]=c}if(r===void 0)return{running:e,byParent:s};const o=bn(r);if(o)return{running:e,byParent:s,orphaned:o}}function bn(n){if(!n||typeof n!="object")return;const{total:e,running:t}=n;if(!(typeof e!="number"||typeof t!="number"))return{total:e,running:t}}async function kn(n,e){try{return await u(n,e),{ok:!0}}catch(t){const r=t?.data,s=!!r&&typeof r=="object"&&r.code==="secret-request-unknown",o=t instanceof Error?t.message:String(t);return{ok:!1,expired:s,error:o}}}class Ci{constructor(){y(this,"retirementCapabilityRequest",null)}supportsRetirement(e=0){if(this.retirementCapabilityRequest?.generation!==e){const t=u("client.hello",{}).then(r=>r?.server?.capabilities?.agentRetire===1).catch(()=>!1).finally(()=>{this.retirementCapabilityRequest?.promise===t&&(this.retirementCapabilityRequest=null)});this.retirementCapabilityRequest={generation:e,promise:t}}return this.retirementCapabilityRequest.promise}async list(e,t){const{agents:r}=await this.listWithMeta(e,t);return r}async listWithMeta(e,t){const r={workspaceId:e};t?.retiredOnly&&(r.retiredOnly=!0),t?.scope&&t.scope!=="all"&&(r.scope=t.scope),t?.parentAgentId&&(r.parentAgentId=t.parentAgentId),t?.orphanedOnly&&(r.orphanedOnly=!0);const s=await ut(c=>u("agent.list",c),r,"agents"),o=Array.isArray(s?.agents)?s.agents:[],i=Ti(s?.scopeCounts),a=Ei(s?.delegatedCounts);return{agents:o.map(c=>Qe(c)),retiredCount:typeof s?.retiredCount=="number"?s.retiredCount:0,...i?{scopeCounts:i}:{},...a?{delegatedCounts:a}:{}}}async get(e,t){const r=await u("agent.get",{agentId:e,...t!==void 0?{workspaceId:t}:{}}),s=r&&typeof r=="object"&&"agent"in r?r.agent:r;return!s||typeof s!="object"?null:Qe(s)}async getConversation(e,t=is,r,s,o,i){let a=t,c;for(;;){const d={agentId:e,...i!==void 0?{workspaceId:i}:{},limit:a,projection:"slim"};r!==void 0&&(d.nextToken=r),s!==void 0&&(d.aroundMessageId=s),o!==void 0&&(d.aroundIndex=o);try{c=await u("agent.getConversation",d);break}catch(m){if(!Si(m)||!Number.isFinite(a)||a<=1)throw m;a=Math.max(1,Math.floor(a/2))}}return!c||typeof c!="object"?{messages:[],truncated:!1,totalMessages:0,nextToken:null,prevToken:null}:{messages:Array.isArray(c.messages)?c.messages:[],truncated:!!c.truncated,totalMessages:typeof c.totalMessages=="number"?c.totalMessages:0,nextToken:typeof c.nextToken=="string"?c.nextToken:null,prevToken:typeof c.prevToken=="string"?c.prevToken:null}}async getMessageBlock(e,t,r,s){const i=(await u("agent.getMessageBlock",{agentId:e,messageId:t,blockId:r,...s!==void 0?{workspaceId:s}:{}}))?.block;if(!an(i))throw new Error(`agent.getMessageBlock returned no block for message ${t} block ${r}`);return i}async getMessageBlockPage(e,t,r,s,o){const i=await u("agent.getMessageBlock",{agentId:e,messageId:t,blockId:r,...s!==void 0?{workspaceId:s}:{},...o!==void 0?{offset:o}:{}}),a=i?.block;if(!an(a))throw new Error(`agent.getMessageBlock returned no block for message ${t} block ${r}`);const c=l=>typeof l=="number"&&Number.isSafeInteger(l)&&l>=0?l:null;return{block:a,truncated:i.truncated===!0,field:typeof i.field=="string"?i.field:null,encoding:i.encoding==="text"||i.encoding==="json"?i.encoding:null,totalBytes:c(i.totalBytes),nextOffset:c(i.nextOffset)}}async listUserMessages(e,t,r,s){const o={agentId:e,...r!==void 0?{workspaceId:r}:{}};t!==void 0&&(o.previewChars=t),s?.limit!==void 0&&(o.limit=s.limit),s?.nextToken!==void 0&&(o.nextToken=s.nextToken);try{const i=await u("agent.listUserMessages",o),c=(Array.isArray(i?.items)?i.items:[]).filter(m=>!!m&&typeof m=="object").map(m=>{const I={id:String(m.id??""),preview:String(m.preview??""),createdAt:String(m.createdAt??"")};return m.metadata&&typeof m.metadata=="object"&&(I.metadata=m.metadata),I}),l=typeof i?.total=="number"?i.total:c.length,d=i?.nextToken;return typeof d=="string"||d===null?{ok:!0,items:c,total:l,nextToken:d}:{ok:!0,items:c,total:l}}catch(i){return{ok:!1,unsupported:!!i&&typeof i=="object"&&"rpcCode"in i&&i.rpcCode===-32601,error:i instanceof Error?i.message:String(i)}}}async create(e){const t={workspaceId:e.workspaceId,idempotencyKey:Q()};e.placement!==void 0&&(t.placement=e.placement),e.model!==void 0&&(t.model=e.model),e.reasoningEffort!==void 0&&(t.reasoningEffort=e.reasoningEffort),e.rememberSpecialist!==void 0&&(t.rememberSpecialist=e.rememberSpecialist),e.specialist!==void 0&&(e.specialist!==null||e.rememberSpecialist)&&(t.specialistId=e.specialist),e.prompt!==void 0&&(t.behaviorPrompt=e.prompt),e.name!==void 0&&(t.name=e.name),e.nameExplicitlySet!==void 0&&(t.nameExplicitlySet=e.nameExplicitlySet),e.provider!==void 0&&(t.provider=e.provider),e.agentType!==void 0&&(t.agentType=e.agentType),e.metadata!==void 0&&(t.metadata=e.metadata),e.workspacePath!==void 0&&(t.workspacePath=e.workspacePath),e.workspaceContext!==void 0&&(t.workspaceContext=e.workspaceContext);const r=await u("agent.create",t),s=r&&typeof r=="object"&&"agent"in r?r.agent:r;if(!s||typeof s!="object")throw new Error("agent.create returned no agent object");const o=s.id;if(typeof o!="string"||o.length===0)throw new Error("agent.create response missing daemon-assigned agent.id");return Qe(s)}async send(e,t,r){if(r??=await this.resolveAgentWorkspaceId(e)??void 0,!r)return{success:!1,error:`Unknown workspace for agent ${e}`};const s=Q();return b("agent.sendMessage",{agentId:e,content:t,workspaceId:r,messageId:s})}async editAndRegenerate(e){const t={agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId,content:e.content};return e.model!==void 0&&(t.model=e.model),e.imageBlocks!==void 0&&(t.imageBlocks=e.imageBlocks),e.fileBlocks!==void 0&&(t.fileBlocks=e.fileBlocks),b("agent.editAndRegenerate",t)}async queue(e,t,r){try{const s={agentId:e,content:t,...r?.workspaceId!==void 0?{workspaceId:r.workspaceId}:{}};r?.messageId!==void 0&&(s.messageId=r.messageId),r?.imageBlocks!==void 0&&(s.imageBlocks=r.imageBlocks),r?.fileBlocks!==void 0&&(s.fileBlocks=r.fileBlocks),r?.messageMetadata!==void 0&&(s.messageMetadata=r.messageMetadata);const o=await u("agent.queueMessage",s);if(o?.success===!1)return{success:!1,error:o.error};const i=o?.queuedMessage,a=typeof o?.turnId=="string"?o.turnId:typeof i?.turnId=="string"?i.turnId:void 0,c={success:!0};return i&&(c.queuedMessage=i),a!==void 0&&(c.turnId=a),c}catch(s){const o=s&&typeof s=="object"?s.rpcCode:void 0,i=o===-32600||o===-32601||o===-32602||on(s);if(r?.messageId!==void 0&&!i)throw s;return{success:!1,error:s instanceof Error?s.message:String(s)}}}async editQueued(e,t,r,s,o){try{const i={agentId:e,messageId:t,content:r,...o!==void 0?{workspaceId:o}:{}};s!==void 0&&(i.editing=s);const c=(await u("agent.editQueuedMessage",i))?.queuedMessage;return c?{success:!0,queuedMessage:c}:{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:String(i)}}}async sendQueuedNow(e){try{const t=await u("agent.sendQueuedMessageNow",{agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId});return{success:t.success,queued:t.queued,...t.quarantined!==void 0?{quarantined:t.quarantined}:{},...t.queuedMessage?{queuedMessage:t.queuedMessage}:{},...!t.queued&&t.turnId?{turnId:t.turnId}:{}}}catch(t){return{success:!1,error:_(t)}}}async sendQueuedMessagesNow(e){try{const r=(await u("client.hello",{}))?.server?.protocolVersion,s=typeof r=="string"?/^(\d+)\.(\d+)(?:\.\d+)?$/.exec(r):null;if(!s||Number(s[1])<13||Number(s[1])===13&&Number(s[2])<1)return{success:!1,error:T.chat_queuedMessages_sendAllUnsupported_error()};const o=await u("agent.sendQueuedMessagesNow",{agentId:e.agentId,workspaceId:e.workspaceId,messageIds:e.messageIds});return{success:o.success,queued:o.queued,messageIds:o.messageIds,...o.quarantined!==void 0?{quarantined:o.quarantined}:{},...!o.queued&&!o.quarantined&&o.turnId?{turnId:o.turnId}:{}}}catch(t){return{success:!1,error:_(t)}}}async getQueue(e,t){const r=await ut(s=>u("agent.getQueue",s),{agentId:e,...t!==void 0?{workspaceId:t}:{}},"queue");return Array.isArray(r?.queue)?r.queue:[]}async removeQueued(e,t,r){return b("agent.removeQueuedMessage",{agentId:e,messageId:t,...r!==void 0?{workspaceId:r}:{}})}async stop(e,t){return b("agent.stop",{agentId:e,...t!==void 0?{workspaceId:t}:{}})}async cancelSubscriptions(e){const t={agentId:e.agentId,workspaceId:e.workspaceId};return e.subscriptionId!==void 0&&(t.subscriptionId=e.subscriptionId),e.groupId!==void 0&&(t.groupId=e.groupId),b("agent.cancelSubscriptions",t)}async dismissQuestions(e){return b("agent.dismissQuestions",{agentId:e.agentId,workspaceId:e.workspaceId,messageId:e.messageId})}async secretList(e){try{return Wo(await u("secret.list",{workspaceId:e.workspaceId,agentId:e.agentId}))}catch{return null}}async secretProvide(e){return kn("secret.provide",{workspaceId:e.workspaceId,requestId:e.requestId,value:e.value})}async secretDismiss(e){return kn("secret.dismiss",{workspaceId:e.workspaceId,requestId:e.requestId})}async resolveProposal(e){const t={workspaceId:e.workspaceId,agentId:e.agentId,proposalId:e.proposalId,outcome:e.outcome};return e.detail!==void 0&&(t.detail=e.detail),b("agent.resolveProposal",t)}async resolveRpcProposal(e){try{const t=await u("agent.resolveRpcProposal",{workspaceId:e.workspaceId,agentId:e.agentId,proposalId:e.proposalId,decision:e.decision},{timeoutMs:66e4});return{success:!0,outcome:t?.outcome==="applied"?"applied":"dismissed",items:Array.isArray(t?.items)?t.items:[],...t?.expired?{expired:!0}:{}}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async markSeen(e){return b("agent.markSeen",{workspaceId:e.workspaceId,agentId:e.agentId,messageId:e.messageId})}async setReasoningEffort(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{reasoningEffort:e.reasoningEffort}})}async setNotificationsMuted(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{notificationsMuted:e.notificationsMuted}})}async setPinned(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{pinned:e.pinned}})}async sendGoalCommand(e){try{const t=await u("agent.sendMessage",{agentId:e.agentId,workspaceId:e.workspaceId,content:e.content,interpretCommands:!0});if(t&&typeof t=="object"&&t.success===!1){const r=t.error;return{ok:!1,error:{kind:"failed",...typeof r=="string"?{message:r}:{}}}}return{ok:!0,command:jo(t)}}catch(t){return{ok:!1,error:dn(t)}}}async setGoal(e){try{const t=Do(await u("agent.setGoal",{agentId:e.agentId,workspaceId:e.workspaceId,goal:e.goal}));return t?{ok:!0,result:t}:{ok:!1,error:{kind:"failed"}}}catch(t){return{ok:!1,error:dn(t)}}}async setPermissionPolicy(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{permissionPolicy:e.permissionPolicy}})}async setBackground(e){return b("agent.update",{agentId:e.agentId,workspaceId:e.workspaceId,changes:{isBackground:e.isBackground}})}async updateSpecialist(e){const t={specialist:e.specialist};e.rememberSpecialist!==void 0&&(t.rememberSpecialist=e.rememberSpecialist),e.model!==void 0&&(t.model=e.model),e.systemPrompt!==void 0&&(t.systemPrompt=e.systemPrompt);const r={agentId:e.agentId,workspaceId:e.workspaceId,changes:t};try{return await u("agent.update",r),{success:!0}}catch(s){if(e.rememberSpecialist!==void 0&&s?.rpcCode===-32602&&_(s).includes("agent.update: unknown field `rememberSpecialist` in `changes`")){const o={...t};return delete o.rememberSpecialist,b("agent.update",{...r,changes:o})}return{success:!1,error:_(s)}}}async rename(e,t,r,s){const o={agentId:e,name:t,...r!==void 0?{workspaceId:r}:{}};return s?.skipIfExplicitlySet===!0&&(o.skipIfExplicitlySet=!0),b("agent.rename",o)}async delete(e,t,r){const s=r?.undoDelayMs;try{const o=await u("agent.delete",{agentId:e,...t!==void 0?{workspaceId:t}:{},...s&&s>0?{undoDelayMs:s}:{}}),i=o?.scheduled===!0,a=typeof o?.deleteAt=="string"?o.deleteAt:void 0;return i&&a?{success:!0,scheduled:!0,deleteAt:a}:{success:!0}}catch(o){return on(o)?{success:!1,forbidden:!0,error:_(o)}:{success:!1,error:_(o)}}}async cancelDelete(e,t){try{return{success:!0,cancelled:(await u("agent.cancelDelete",{agentId:e,...t!==void 0?{workspaceId:t}:{}}))?.cancelled===!0}}catch(r){return{success:!1,error:_(r)}}}async retire(e,t){const r={agentId:e};t!==void 0&&(r.workspaceId=t);try{return await u("agent.retire",r)}catch(s){return{success:!1,error:_(s)}}}async restore(e,t){const r={agentId:e,...t!==void 0?{workspaceId:t}:{}};return b("agent.restore",r)}async retry(e,t){try{const r=await u("agent.retry",{agentId:e,workspaceId:t});if(r?.ok!==!0)return{ok:!1,error:"Agent not in error status"};const s=typeof r.redriven=="boolean"?r.redriven:void 0,o=typeof r.turnId=="string"?r.turnId:void 0;return o!==void 0?{ok:!0,redriven:s,turnId:o}:{ok:!0,redriven:s}}catch(r){const s=r instanceof Error?r.message:"Failed to retry agent spawn";return _o(r)?{ok:!1,notFound:!0,error:s}:{ok:!1,error:s}}}async respondPermission(e,t,r){try{const s=await u("agent.respondPermission",{requestId:e,outcome:t,...r!==void 0?{workspaceId:r}:{}}),o=typeof s?.resolved=="boolean"?s.resolved:void 0;return o!==void 0?{success:!0,resolved:o}:{success:!0}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async listInterrupted(){try{const e=await u("agent.listInterrupted",{});return(Array.isArray(e?.agents)?e.agents:[]).map(r=>{const s=r;return{agentId:String(s.agentId??""),workspaceId:String(s.workspaceId??""),workspaceName:String(s.workspaceName??""),agentName:String(s.agentName??""),prevStatus:String(s.prevStatus??""),interruptedAt:String(s.interruptedAt??"")}})}catch(e){if(e&&typeof e=="object"&&"rpcCode"in e&&e.rpcCode===-32601)return[];throw e}}async resolveInterrupted(e){try{const t=await u("agent.resolveInterrupted",e);return{resumed:Array.isArray(t?.resumed)?t.resumed:[],abandoned:Array.isArray(t?.abandoned)?t.abandoned:[],failed:Array.isArray(t?.failed)?t.failed.map(r=>{const s=r;return{agentId:String(s.agentId??""),error:String(s.error??"")}}):[]}}catch(t){throw t}}async resolveAgentWorkspaceId(e){const t=Cr.get(e);if(t)return t;const r=await this.get(e);if(!r)return null;const s=String(r.workspaceId??"");return s.length>0?s:null}subscribe(e){return Je({channel:{subscribeMethod:"agent.subscribe",unsubscribeMethod:"events.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t})},continuation:{method:"agent.list",key:"agents",params:t=>({workspaceId:t.workspaceId})}},getId:t=>String(t.id??""),normalize:t=>Qe(t),handler:e})}}function Ri(n){return`browser-recent-${n}`}function _i(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.url=="string"&&typeof e.lastVisited=="string"&&(e.title===void 0||typeof e.title=="string")&&(e.favicon===void 0||typeof e.favicon=="string")}function Ku(n){const e=n?.target;return K(e)&&typeof e.clientId=="string"&&e.clientId.length>0&&typeof e.via=="string"?{clientId:e.clientId,via:e.via}:void 0}function K(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function In(n){return K(n)&&n.ok===!0}function Mi(n){return K(n)&&typeof n.action=="string"&&typeof n.success=="boolean"&&(n.error===void 0||typeof n.error=="string")}function Pi(n){return K(n)&&typeof n.clientId=="string"&&K(n.capabilities)&&typeof n.connections=="number"&&Array.isArray(n.transports)&&typeof n.connectedAt=="string"}function Ju(n){return K(n)&&typeof n.clientId=="string"&&K(n.capabilities)}function Oi(n){if(!K(n))return!1;if(n.source==="workspace"){if(typeof n.clientId!="string")return!1}else if(n.source==="default"){if(n.clientId!==void 0)return!1}else return!1;const e=n.resolved;return e===null||K(e)&&typeof e.clientId=="string"}function Rr(n){return K(n)&&typeof n.tabId=="string"&&typeof n.workspaceId=="string"&&typeof n.hostClientId=="string"&&typeof n.url=="string"&&(n.visibility==="visible"||n.visibility==="hidden")&&typeof n.createdAt=="string"&&typeof n.updatedAt=="string"}function xi(n){return Rr(n)&&typeof n.hostConnected=="boolean"}function Ni(n){const e=us.getJSON(Ri(n));return Array.isArray(e)?e.filter(t=>_i(t)).slice(0,ls):[]}class Bi{async recentUrls(e){return Ni(e)}subscribe(e){return e([]),()=>{}}async listTabs(e){const t=await u("browser.listTabs",{workspaceId:e});if(!Array.isArray(t?.tabs)||!t.tabs.every(xi))throw new Error("Invalid browser.listTabs response shape");return t.tabs}async upsertTab(e,t){const r=await u("browser.upsertTab",{workspaceId:e,tab:t});if(!Rr(r?.tab))throw new Error("Invalid browser.upsertTab response shape");return r.tab}async removeTab(e){const t=await u("browser.removeTab",{tabId:e});if(!In(t))throw new Error("Invalid browser.removeTab response shape");return t}async syncTabs(e){const t=await u("browser.syncTabs",{tabs:e});if(!Array.isArray(t?.drop)||!t.drop.every(r=>typeof r=="string"))throw new Error("Invalid browser.syncTabs response shape");return{drop:t.drop}}async navigateTab(e,t){const r=await u("browser.navigateTab",{tabId:e,url:t});if(!Mi(r))throw new Error("Invalid browser.navigateTab response shape");return r}async closeTab(e,t){const r=await u("browser.closeTab",{tabId:e,...t?.force===void 0?{}:{force:t.force}});if(!In(r))throw new Error("Invalid browser.closeTab response shape");return r}}var _r=(n=>(n.AGENT="agent",n))(_r||{}),re,q,ze,z,gt,yt,mt,Pe,Ke,Ht;class Li{constructor(){V(this,Ke);V(this,re);V(this,q,Vs(zs([])));V(this,ze,1e3);V(this,z,[]);V(this,gt,100);V(this,yt,5e3);V(this,mt,null);V(this,Pe,!1);Ie(this,re,new Ks("Renderer",{enableConsole:!0})),typeof window<"u"&&window.electronAPI&&Ie(this,Pe,!0),A(this,Pe)&&Ie(this,mt,setInterval(()=>{kt(this,Ke,Ht).call(this)},A(this,yt)))}get logs(){return ye(A(this,q))}addToStore(e){At(A(this,q),[...ye(A(this,q)),e],!0),ye(A(this,q)).length>A(this,ze)&&At(A(this,q),ye(A(this,q)).slice(-A(this,ze)),!0)}addToPendingLogs(e){A(this,z).push(e),A(this,z).length>=A(this,gt)&&kt(this,Ke,Ht).call(this)}error(e,t,r,s){const o={timestamp:new Date().toISOString(),level:"ERROR",category:e,message:t,context:s,error:r instanceof Error?{name:r.name,message:r.message,stack:r.stack}:void 0};A(this,re).error(t,r instanceof Error?r:void 0,s),this.addToStore(o),this.addToPendingLogs(o)}warn(e,t,r){const s={timestamp:new Date().toISOString(),level:"WARN",category:e,message:t,context:r};A(this,re).warn(t,r),this.addToStore(s),this.addToPendingLogs(s)}info(e,t,r){const s={timestamp:new Date().toISOString(),level:"INFO",category:e,message:t,context:r};A(this,re).info(t,r),this.addToStore(s),this.addToPendingLogs(s)}debug(e,t,r){const s={timestamp:new Date().toISOString(),level:"DEBUG",category:e,message:t,context:r};A(this,re).debug(t,r),this.addToStore(s),this.addToPendingLogs(s)}verbose(e,t,r){this.debug(e,t,r)}getLogs(){return[...ye(A(this,q))]}getLogsByCategory(e){return ye(A(this,q)).filter(t=>t.category===e)}getLogsByLevel(e){return ye(A(this,q)).filter(t=>t.level===e.toUpperCase())}clearLogs(){At(A(this,q),[],!0)}}re=new WeakMap,q=new WeakMap,ze=new WeakMap,z=new WeakMap,gt=new WeakMap,yt=new WeakMap,mt=new WeakMap,Pe=new WeakMap,Ke=new WeakSet,Ht=async function(){if(A(this,z).length===0||!A(this,Pe))return;const e=[...A(this,z)];Ie(this,z,[]);try{await ee(Js.PERSIST_RENDERER_LOGS,e)}catch(t){console.error("[RendererLogger] Failed to persist logs via IPC:",t),Ie(this,z,[...e,...A(this,z)])}};const ji=new Li,Di=2048,Ui=256;let Sn=0,wn=0,An=0;const qi=192,Fi=64;function $i(n){if(n.stage==="render"&&(n.event.includes("not-committed")||n.terminalErrorVisible===!0||n.callbackResult==="ignored"||n.callbackResult==="threw"))return"render";if(n.callbackResult==="threw"||n.storeStreamState==="error"||n.event.includes("failed")||n.event.includes("error")||n.pushKind==="snapshot"&&(n.callbackResult==="ignored"||n.callbackResult==="buffered")&&n.event.startsWith("snapshot-"))return"failure"}function Tn(n){if(!n)return;let e=0xcbf29ce484222325n;for(const t of new TextEncoder().encode(n))e^=BigInt(t),e=BigInt.asUintN(64,e*0x100000001b3n);return e.toString(16).padStart(16,"0")}function L(n){const e=Di-Ui;if(Sn<e)Sn+=1;else{const t=$i(n);if(t==="failure"&&wn<qi)wn+=1;else if(t==="render"&&An<Fi)An+=1;else return}ji.info(_r.AGENT,"stream-lifecycle",n)}const Wi={messages:[],truncated:!1,totalMessages:0},En=5e3,Cn=1e3,Gi=3e4,Hi=256,Vi=new Set(Eo),zi=new Set(["text","code","tool_use","tool_result","thinking","image","audio","file","nav-link","proposal","plan"]);function G(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Rn(n){if(!G(n))return null;const{target:e,received:t,complete:r}=n;return typeof e!="number"||!Number.isSafeInteger(e)||e<1||e>200||typeof t!="number"||!Number.isSafeInteger(t)||t<0||t>e||typeof r!="boolean"?null:{target:e,received:t,complete:r}}function Mr(n){if(!G(n))return null;try{return wo(n)}catch{return typeof n.type!="string"||n.type.length===0||zi.has(n.type)?null:{...n}}}function Pr(n,e){if(!G(n)||typeof n.id!="string"||n.id.length===0||typeof n.role!="string"||!Vi.has(n.role)||typeof n.timestamp!="string"||n.timestamp.length===0)return null;const t=n.agentId===void 0?e:n.agentId;if(t!==void 0&&(typeof t!="string"||t.length===0)||e!==void 0&&t!==void 0&&t!==e||n.seq!==void 0&&(typeof n.seq!="number"||!Number.isSafeInteger(n.seq)||n.seq<0))return null;const r=Array.isArray(n.contentBlocks)?n.contentBlocks.map(Mr).filter(s=>s!==null):[];return{...n,...t===void 0?{}:{agentId:t},contentBlocks:r}}function Or(n,e){if(!G(n))return Wi;const t=n.agentId===void 0?e:n.agentId,r=t===void 0||typeof t=="string"&&t.length>0&&(e===void 0||t===e);return{messages:Array.isArray(n.messages)?r?n.messages.map(o=>Pr(o,t)).filter(o=>o!==null):[]:[],...n.nextToken===null||typeof n.nextToken=="string"?{nextToken:n.nextToken}:{},truncated:!!n.truncated,totalMessages:typeof n.totalMessages=="number"?n.totalMessages:0}}function Ki(n){if(!n||typeof n!="object")return;const e=n.resumed;return typeof e=="boolean"?e:void 0}function Ji(n,e){if(n!=="subscription.push"||!e||typeof e!="object")return null;const t=e,r=typeof t.subscriptionId=="string"?t.subscriptionId:null,s=typeof t.seq=="number"?t.seq:null;if(!r||s===null||!Number.isSafeInteger(s)||s<0)return null;if(t.kind==="snapshot")return{subscriptionId:r,kind:"snapshot",seq:s,snapshot:t.snapshot};if(t.kind==="history")return{subscriptionId:r,kind:"history",seq:s,history:t.history};if(t.kind==="delta"){const o=t.delta&&typeof t.delta=="object"?t.delta:{};return{subscriptionId:r,kind:"delta",seq:s,delta:{added:Array.isArray(o.added)?o.added:[],updated:Array.isArray(o.updated)?o.updated:[],removedIds:Array.isArray(o.removedIds)?o.removedIds.map(i=>String(i)):[]}}}return null}function Yi(n){if(n.kind==="snapshot"){const t=Or(n.snapshot).messages;for(let r=t.length-1;r>=0;r-=1){const s=t[r];if(s.role==="assistant")return Tn(s.id)}return}const e=[...n.delta?.updated??[],...n.delta?.added??[]];for(let t=e.length-1;t>=0;t-=1){const r=xr(e[t],!0);if(r&&(r.role===void 0||r.role==="assistant"))return Tn(r.messageId)}}function xr(n,e){if(!G(n))return null;const t=n,r=typeof t.messageId=="string"?t.messageId:null;if(!r||!G(t.block)||typeof t.block.id!="string")return null;const s=e&&(t.block.type==="text"||t.block.type==="thinking")&&typeof t.block.textDelta=="string",o=Mr(s?{text:t.block.textDelta,...t.block}:t.block);return o?(s&&!("text"in t.block)&&delete o.text,{messageId:r,...typeof t.role=="string"?{role:t.role}:{},block:o,...typeof t.messageSeq=="number"?{messageSeq:t.messageSeq}:{},...typeof t.timestamp=="string"?{timestamp:t.timestamp}:{},...t.streamingComplete===!0?{streamingComplete:!0}:{},...t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?{metadata:t.metadata}:{},...typeof t.appMessageId=="string"&&t.appMessageId.length>0?{appMessageId:t.appMessageId}:{},...t.author===null||t.author&&typeof t.author=="object"&&!Array.isArray(t.author)?{author:t.author}:{}}):null}function Zi(n,e){const t=e.name??e.toolName??"";if(e.type!=="tool_use"||n.type!=="tool_use"||!e.toolCallId||e.toolCallId!==n.toolCallId||t.length>0)return e;const r=n.metadata?.toolKind;return{...e,name:n.name??n.toolName??"",input:n.input,metadata:{...e.metadata??{},...r!==void 0?{toolKind:r}:{}}}}function Qi(n,e){return n.type!=="text"||!e?.media?n:{...n,media:{...e.media,...n.media??{}}}}function Xi(n){const e=JSON.stringify(n)??"";let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}class ea{constructor(e){y(this,"messages",[]);y(this,"truncated",!1);y(this,"nextToken");y(this,"totalMessages",0);y(this,"streaming",!1);y(this,"expectedSeq",0);y(this,"seeded",!1);y(this,"snapshotFingerprint",0);y(this,"incremental",!1);y(this,"initialHistory");y(this,"initialMessageIds",new Set);this.expectedAgentId=e}reset(){this.messages=[],this.truncated=!1,this.nextToken=void 0,this.totalMessages=0,this.streaming=!1,this.expectedSeq=0,this.seeded=!1,this.snapshotFingerprint=0,this.incremental=!1,this.initialHistory=void 0,this.initialMessageIds.clear()}applySnapshot(e,t){const r=G(t)?t:{},s=r.historyDelivery==="progressive"?Rn(r.initialHistory):void 0,o=Or(t,this.expectedAgentId),i=new Set(o.messages.map(l=>l.id));if(s===null||s&&(s.received!==i.size||!s.complete&&o.messages.length>1))return"invalid";const a=Xi(t);if(this.seeded&&a===this.snapshotFingerprint&&(e+1===this.expectedSeq||e===0&&s!==void 0&&e<this.expectedSeq))return!1;this.snapshotFingerprint=a,this.messages=o.messages,this.truncated=o.truncated,this.nextToken=o.nextToken,this.totalMessages=o.totalMessages;const c=t&&typeof t=="object"?t:{};return this.streaming=this.messages.some(l=>l.isStreaming===!0)||c.isResponding===!0||c.turnInFlight===!0,this.incremental=c.deltaEncoding==="incremental",this.initialHistory=s,this.initialMessageIds=i,this.initialHistory?.complete===!1&&(this.nextToken=void 0),this.expectedSeq=e+1,this.seeded=!0,!0}applyDelta(e,t){if(!this.seeded||e>this.expectedSeq)return"gap";if(e<this.expectedSeq)return"stale";let r=!1,s=!1;for(const o of[...t.added,...t.updated]){const i=xr(o,this.incremental);i&&(this.upsertBlock(i),(i.role===void 0||i.role==="assistant")&&(s=!0,i.streamingComplete&&(r=!0)))}if(t.removedIds.length>0){const o=new Set(t.removedIds);this.messages=this.messages.map(i=>{const a=i.contentBlocks;return!a||!a.some(c=>c.id!==void 0&&o.has(c.id))?i:{...i,contentBlocks:a.filter(c=>c.id===void 0||!o.has(c.id))}})}return r?this.streaming=this.messages.some(o=>o.role==="assistant"&&o.isStreaming===!0):s&&(this.streaming=!0),this.expectedSeq=e+1,"applied"}applyHistory(e,t){if(!this.seeded||e>this.expectedSeq)return"gap";if(e<this.expectedSeq)return"stale";if(!this.initialHistory||this.initialHistory.complete||!G(t))return"gap";const r=Rn(t);if(!r||r.target!==this.initialHistory.target)return"gap";const{received:s,complete:o}=r,i=t.message===void 0?void 0:Pr(t.message,this.expectedAgentId);if(!o&&!i||o&&t.message!==void 0)return"gap";const a=i&&!this.initialMessageIds.has(i.id);return s!==this.initialHistory.received+(a?1:0)||o&&(t.nextToken!==null&&(typeof t.nextToken!="string"||t.nextToken.length===0)||typeof t.truncated!="boolean"||typeof t.totalMessages!="number"||!Number.isSafeInteger(t.totalMessages)||t.totalMessages<s||s<r.target&&t.nextToken!==null)?"gap":(i&&(this.initialMessageIds.add(i.id),this.messages.some(c=>c.id===i.id)||(this.messages=[i,...this.messages].sort((c,l)=>(c.seq??Number.MAX_SAFE_INTEGER)-(l.seq??Number.MAX_SAFE_INTEGER)))),this.initialHistory=r,o&&(this.nextToken=t.nextToken,this.truncated=t.truncated,this.totalMessages=t.totalMessages),this.expectedSeq=e+1,"applied")}transcript(){return{...this.initialHistory?{initialHistory:this.initialHistory}:{},messages:this.messages,truncated:this.truncated,...this.nextToken!==void 0?{nextToken:this.nextToken}:{},totalMessages:this.totalMessages,isStreaming:this.streaming}}materializeBlock(e,t){const{textDelta:r,...s}=e.block,i=this.incremental&&typeof r=="string"&&(s.type==="text"||s.type==="thinking")?{...s,text:(t?.text??"")+r}:e.block;return Qi(i,t)}upsertBlock(e){const t=e.streamingComplete===!0;let r=this.messages.findIndex(l=>l.id===e.messageId);r<0&&(this.messages=[...this.messages,{id:e.messageId,role:e.role??"assistant",contentBlocks:[],timestamp:e.timestamp??new Date().toISOString(),isStreaming:!t}],r=this.messages.length-1,this.totalMessages+=1);const s=this.messages[r],o=[...s.contentBlocks??[]],i=o.findIndex(l=>l.id===e.block.id),a=this.materializeBlock(e,i>=0?o[i]:void 0);i>=0?o[i]=Zi(o[i],a):o.push(a);const c={...s,contentBlocks:o,isStreaming:!t,...t?{streamingComplete:!0}:{}};e.timestamp&&(c.timestamp=e.timestamp),e.messageSeq!==void 0&&(c.seq=e.messageSeq),e.metadata&&(c.metadata=e.metadata),e.appMessageId&&(c.appMessageId=e.appMessageId),"author"in e&&(c.author=e.author),this.messages=[...this.messages.slice(0,r),c,...this.messages.slice(r+1)]}}class ta{subscribe(e,t,r,s){const o=s?.workspaceId,i=o!==void 0?{workspaceId:o}:{},a=new ea(e);let c=!1,l,d=s?.sinceMessageId,m=!1,I,S;const h=f=>{c||f===I||(I=f,r?.(f))},w=()=>{S!==void 0&&(clearTimeout(S),S=void 0)};let R,H=Cn,N=!1;const F=()=>{R!==void 0&&(clearTimeout(R),R=void 0)},B=()=>{F(),N=!1,H=Cn},ue=()=>{c||(h("delayed"),N=!0,F(),R=setTimeout(()=>{R=void 0,!c&&(a.reset(),je(),le())},H),H=Math.min(H*2,Gi))};let $=0,U=0,X=!1,D=!1,J=!1,Y=[];const ht=(f,v=!1)=>{if(!c)try{t({...a.transcript(),...v?{fromHistory:!0}:{}}),L({...f,callbackResult:"delivered"})}catch(k){throw L({...f,callbackResult:"threw"}),k}},Ye=(f,v,k=!1)=>{if(c)return;const E=a.transcript();try{t({...E,fromSnapshot:!0,...f===void 0?{}:{resumed:f},...k?{resetCachedTranscript:!0}:{}}),L({...v,callbackResult:"delivered"})}catch(C){throw L({...v,callbackResult:"threw"}),C}},Le=()=>{w(),a.transcript().initialHistory?.complete===!1&&(S=setTimeout(()=>{S=void 0,m=!0,ue()},En))},ke=f=>{if(c)return;const v={stage:"subscription",event:"push",turnCorrelation:Yi(f),subscriptionGeneration:$,transportGeneration:U,pushKind:f.kind,pushSeq:f.seq};if(l===void 0){Y.push(f),Y.length>Hi&&Y.shift(),L({...v,callbackResult:"buffered"});return}if(f.subscriptionId!==l){L({...v,callbackResult:"ignored"});return}if(f.kind==="snapshot"){D=!1,w(),B(),h("live");const k=Ki(f.snapshot);d=void 0;const E=a.applySnapshot(f.seq,f.snapshot);if(E==="invalid"){m=X,de();return}if(E){const C=m&&k===void 0;m=!1;const fe=X?"reset":"applied";X=!0,Ye(k,{...v,reconcilerResult:fe},C)}else L({...v,reconcilerResult:"duplicate",callbackResult:"not-invoked"});Le(),J&&a.transcript().initialHistory?.complete!==!1&&(J=!1,de())}else if(D)L({...v,callbackResult:"ignored"});else{const k=f.kind==="history"?a.applyHistory(f.seq,f.history):a.applyDelta(f.seq,f.delta??{added:[],updated:[],removedIds:[]});k==="applied"?(f.kind==="history"&&(B(),h("live"),Le()),ht({...v,reconcilerResult:"applied"},f.kind==="history"),f.kind==="history"&&a.transcript().initialHistory?.complete&&J&&(J=!1,de())):k==="gap"?(L({...v,reconcilerResult:"gap",callbackResult:"not-invoked"}),de()):L({...v,reconcilerResult:"stale",callbackResult:"not-invoked"})}},le=()=>{F(),$+=1;const f=$;L({stage:"subscription",event:"registration-start",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),N||h(D?"resyncing":"connecting"),u("chat.subscribe",{agentId:e,...i,deltaEncoding:"incremental",projection:"slim",historyDelivery:"progressive",...d===void 0?{}:{sinceMessageId:d}}).then(v=>{const k=v?.subscriptionId;if($!==f||c){L({stage:"subscription",event:"registration-stale",subscriptionGeneration:f,transportGeneration:U,callbackResult:"ignored"}),k&&u("chat.unsubscribe",{subscriptionId:k,...i}).catch(()=>{});return}l=k,L({stage:"subscription",event:"registration-ack",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),!D&&!N&&h("awaiting-snapshot"),w(),S=setTimeout(()=>{S=void 0,ue()},En);const E=Y.filter(C=>C.subscriptionId===k);Y=[];for(const C of E)ke(C)}).catch(()=>{$===f&&(L({stage:"subscription",event:"registration-failed",subscriptionGeneration:f,transportGeneration:U,callbackResult:"not-invoked"}),ue())})},je=()=>{if($+=1,!l)return;const f=l;l=void 0,u("chat.unsubscribe",{subscriptionId:f,...i}).catch(()=>{})},vt=()=>{D=!0,F(),w(),a.reset(),je(),le()},de=()=>{c||D||vt()},g=ae(f=>{const v=Ji(f.method,f.params);if(v){ke(v);return}if(c||f.method!=="events.event"||!G(f.params))return;const k=G(f.params.event)?f.params.event:f.params;if(k.type!=="agent:stream:end"||!G(k.data))return;const E=k.data;if(E.agentId!==e||typeof E.messageId!="string"||E.messageId.length===0||E.stopReason!=="interrupted"&&typeof E.finishReason!="string")return;const C=a.transcript().messages.find(fe=>fe.id===E.messageId);C&&((C.contentBlocks?.length??0)>0||C.seq!==void 0&&C.isStreaming!==!0&&C.streamingComplete!==!1)||(!X||D||l===void 0||S!==void 0||N?J=!0:de())}),p=ce(()=>{c||(m||=X,U+=1,$+=1,L({stage:"subscription",event:"transport-reconnected",subscriptionGeneration:$,transportGeneration:U,callbackResult:"not-invoked"}),l=void 0,D=!1,Y=[],w(),B(),a.reset(),le())});return le(),()=>{c=!0,w(),F(),g(),p(),je()}}}let me=null;class na{async list(e){const t=await u("client.list",...e?[{workspaceId:e}]:[]);if(!Array.isArray(t?.clients)||!t.clients.every(Pi))throw new Error("Invalid client.list response shape");return t.clients}ownClientId(){if(!me){me=u("client.hello",{}).then(t=>{const r=t?.clientId;if(typeof r!="string"||r.length===0)throw new Error("Invalid client.hello response shape: clientId missing");return r});const e=me;e.catch(()=>{me===e&&(me=null)})}return me}}function Yu(){me=null}function tn(n){if(n.authorType!=="user")return{};const e={};if(typeof n.authorPrincipalId=="string"&&n.authorPrincipalId.trim()&&(e.authorPrincipalId=n.authorPrincipalId),Ys(n.authorIdentity)&&n.authorIdentity.externalUserId.trim()){const{provider:t,host:r,externalUserId:s}=n.authorIdentity;e.authorIdentity={provider:t,host:r,externalUserId:s}}return e}function ra(n){const e=n.latestCommentAuthorType==="user"||n.latestCommentAuthorType==="agent"?n.latestCommentAuthorType:void 0,t=tn({authorType:e,authorPrincipalId:n.latestCommentAuthorPrincipalId,authorIdentity:n.latestCommentAuthorIdentity});return{author:typeof n.latestCommentAuthor=="string"?n.latestCommentAuthor:void 0,authorType:e,authorPrincipalId:t.authorPrincipalId,authorIdentity:t.authorIdentity}}function Zu(n){const e=n.author||T.tiptap_comment_unknownAuthor_label(),{authorIdentity:t}=tn(n);if(!t)return e;const{provider:r,host:s,externalUserId:o}=t,i=`${r}@${s} · ${o}`;return T.presence_person_forge_label({name:e,handle:i})}function sa(n){if(!(!n||typeof n!="object"))return Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Array.isArray(t)?t.map(r=>String(r)):[String(t)]]))}function oa(n){if(!n||typeof n!="object")return;const e=n;return{before:String(e.before??""),after:String(e.after??"")}}function ia(n){const e=n&&typeof n=="object"?n:{};return{original:String(e.original??""),proposed:String(e.proposed??"")}}function Vt(n,e,t){const r=new Date().toISOString(),s=String(n.id??""),o=typeof n.parentId=="string"&&n.parentId.length>0,i=n.anchor&&typeof n.anchor=="object"?n.anchor:o?void 0:{type:"point"},a=oa(n.anchorContext),c=sa(n.reactions),l={...tn(n),id:s,threadId:String(n.threadId??s),noteId:String(n.noteId??e),...t?{workspaceId:t}:{},content:String(n.content??""),author:String(n.author??""),authorType:n.authorType==="agent"?"agent":"user",status:typeof n.status=="string"?n.status:"open",...i?{anchor:i}:{},createdAt:String(n.createdAt??r),updatedAt:String(n.updatedAt??r),...typeof n.parentId=="string"?{parentId:n.parentId}:{},...n.anchorText!==void 0||n.section!==void 0?{anchorText:String(n.anchorText??n.section??"")}:{},...a?{anchorContext:a}:{},...typeof n.isOrphaned=="boolean"?{isOrphaned:n.isOrphaned}:{},...c?{reactions:c}:{}},d=typeof n.type=="string"?n.type:"comment";switch(d){case"suggestion":return{...l,type:d,suggestionDiff:ia(n.suggestionDiff)};case"session":return{...l,type:d,agentId:String(n.agentId??"")};case"change-request":case"question":return{...l,type:d};case"comment":default:return{...l,type:"comment"}}}async function aa(n,e){const t=e??await ie(n);if(!t)return[];try{const r=await ei(o=>u("comment.list",o),{workspaceId:t,noteId:n,includeComments:!0,limit:it},o=>u("comment.getThread",{workspaceId:t,noteId:n,threadId:o})),s=[];for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(Array.isArray(i.comments))for(const a of i.comments)s.push(Vt(a,n,t));else s.push(Vt({...i,...ra(i)},n,t))}return s}catch{return[]}}class ca{async list(e,t){return aa(e,t)}async add(e,t){return this.runCommentMutation(e,"comment.add",{searchContext:t.searchContext,commentTarget:t.commentTarget,comment:t.comment,...t.type!==void 0?{type:t.type}:{},...t.author!==void 0?{author:t.author}:{},...t.authorType!==void 0?{authorType:t.authorType}:{},...t.commentId!==void 0?{commentId:t.commentId}:{},idempotencyKey:Q()},t.workspaceId)}async respond(e,t){return this.runCommentMutation(e,"comment.respond",{...t.threadId!==void 0?{threadId:t.threadId}:{},...t.commentId!==void 0?{commentId:t.commentId}:{},comment:t.comment,...t.type!==void 0?{type:t.type}:{},...t.authorType!==void 0?{authorType:t.authorType}:{},...t.suggestionOriginal!==void 0?{suggestionOriginal:t.suggestionOriginal}:{},...t.suggestionProposed!==void 0?{suggestionProposed:t.suggestionProposed}:{}},t.workspaceId)}async delete(e,t,r){return this.runCommentMutation(e,"comment.delete",{commentId:t},r)}async runCommentMutation(e,t,r,s){const o=s??await ie(e);return o?b(t,{workspaceId:o,noteId:e,...r}):{success:!1,error:`Cannot resolve workspace for note ${e}`}}subscribe(e,t,r){let s=r;const o={subscribeMethod:"comment.subscribe",unsubscribeMethod:"comment.unsubscribe",continuation:{method:"comment.list",key:"threads",params:i=>({workspaceId:i.workspaceId,noteId:e,includeComments:!0,limit:it})},...r?{params:{workspaceId:r,noteId:e,limit:it}}:{dynamic:{subscribeIds:i=>{let a=!1;return ie(e).then(c=>{a||!c||(s=c,i([c]))}).catch(()=>{}),()=>{a=!0}},paramsForId:i=>({workspaceId:i,noteId:e,limit:it})}}};return Je({channel:o,getId:i=>typeof i.threadId=="string"?i.threadId:"",complete:i=>Ir(i,a=>u("comment.getThread",{workspaceId:s,noteId:e,threadId:a})),normalize:i=>i.noteId!==e||!Array.isArray(i.comments)?null:i.comments.flatMap(a=>{if(!a||typeof a!="object"||Array.isArray(a))return[];const c=a;return typeof c.id!="string"||!c.id||c.threadId!==i.threadId||c.noteId!==void 0&&c.noteId!==e?[]:[Vt(c,e,s)]}),handler:i=>t(i.flat())})}}class ua{async get(e,t){return await u("drafts.get",{workspaceId:e,agentId:t})??null}async set(e,t,r,s){const o={workspaceId:e,agentId:t,text:r};return s&&s.length>0&&(o.attachments=s),await u("drafts.set",o)}async clear(e,t){return await u("drafts.clear",{workspaceId:e,agentId:t})}}const la=300;class da{async list(e){return[...await this.query(e,{limit:la})].reverse()}async query(e,t={}){const r=await u("event.query",{workspaceId:e,...t});return Array.isArray(r)?r:[]}async queryPage(e,t={}){return u("event.query",{workspaceId:e,...t,paginate:!0})}subscribe(e,t){return this.list(e).then(r=>t(r)).catch(()=>t([])),()=>{}}}const fa=new Set([".onnx",".onnx_data",".pt",".pth",".bin",".safetensors",".h5",".hdf5",".pkl",".pickle",".npy",".npz",".model",".weights",".tflite",".mlmodel",".pb",".ckpt",".mat",".parquet",".feather",".arrow",".wasm",".png",".jpg",".jpeg",".gif",".bmp",".ico",".icns",".webp",".tiff",".tif",".svg",".psd",".raw",".heic",".heif",".avif",".mp3",".wav",".ogg",".flac",".aac",".m4a",".wma",".mp4",".mov",".avi",".mkv",".webm",".wmv",".flv",".zip",".tar",".gz",".bz2",".7z",".rar",".xz",".tgz",".exe",".dll",".so",".dylib",".a",".o",".obj",".ttf",".otf",".woff",".woff2",".eot",".pdf",".doc",".docx",".xls",".xlsx",".ppt",".pptx",".db",".sqlite",".sqlite3",".pyc",".pyo",".class",".jar",".war",".ear",".node"]),pa=[/package-lock\.json$/,/yarn\.lock$/,/pnpm-lock\.yaml$/,/composer\.lock$/,/Gemfile\.lock$/,/Cargo\.lock$/,/poetry\.lock$/,/\.min\.(js|css)$/,/\.bundle\.(js|css)$/,/[\\/](dist|build|node_modules)[\\/]/];function ga(n){const e=n.lastIndexOf("."),t=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\"));return e>t&&e!==-1?n.slice(e).toLowerCase():""}function ya(n){const e=ga(n);return fa.has(e)}function ma(n){return pa.some(e=>e.test(n))}function Qu(n){return ya(n)?{skip:!0,reason:"binary/media file"}:ma(n)?{skip:!0,reason:"lock/minified/build file"}:{skip:!1}}function ha(n,e=8192){const t=n.subarray(0,Math.min(e,n.length));if(t.includes(0))return!0;let r=0;for(let s=0;s<t.length;s++){const o=t[s];o!==9&&o!==10&&o!==13&&!(o>=32&&o<=126)&&!(o>=194&&o<=244)&&!(o>=128&&o<=191)&&r++}return r/t.length>.3}const Nr=48e4,va=8*1024*1024,_n=40*1024*1024;class Br extends Error{constructor(e){super(`file.read: ${e}: stream did not contain valid UTF-8`),this.name="InvalidUtf8Error"}}function Lr(n){if(typeof n=="string")return{text:n,truncated:!1};if(n&&typeof n=="object"){const{content:e,truncated:t}=n;if(typeof e=="string")return{text:e,truncated:t===!0}}return null}function ba(n){const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}async function jr(n,e,t=u,r=va){const s=[];let o=0,i;for(;;){const l=await t(n,{...e,offset:o,length:r});if(!l||typeof l.content!="string"||!Number.isSafeInteger(l.size)||!Number.isSafeInteger(l.bytesRead))throw new Error(`${n}: invalid chunk response`);if(l.size>_n)throw new Error(`${n}: object is ${l.size} bytes, over the ${_n}-byte limit`);if(i===void 0)i=l.size;else if(l.size!==i)throw new Error(`${n}: object changed while it was read`);const d=ba(l.content);if(d.length!==l.bytesRead)throw new Error(`${n}: content/bytesRead mismatch (${d.length} vs ${l.bytesRead})`);if(s.push(d),o+=d.length,d.length<r||o>=i)break}const a=new Uint8Array(o);let c=0;for(const l of s)a.set(l,c),c+=l.length;return a}async function ka(n,e=u){const t=await e("file.read",{...n,maxBytes:Nr}),r=Lr(t);if(!r)return null;if(!r.truncated)return r.text;const s=await jr("file.readChunk",n,e);try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(s)}catch{throw new Br(n.path)}}async function Xu(n,e=u){const t=await e("git.showFile",{...n,maxBytes:Nr}),r=Lr(t);if(!r)return"";if(!r.truncated)return r.text;const s=await jr("git.showFileChunk",n,e);return new TextDecoder("utf-8",{ignoreBOM:!0}).decode(s)}function Ia(n){for(let e=0;e<n.length;e++){const t=n.charCodeAt(e);if(t<=8||t>=14&&t<=26||t>=28&&t<=31||t===127)return!0}return!1}function Mt(n,e){return{path:n,absolutePath:null,...fs(e),lastUpdated:Date.now(),loading:!1,saving:!1,error:null,truncated:!1}}function Mn(n){const e=n,t=Array.isArray(e)?e:Array.isArray(e?.entries)?e.entries:Array.isArray(e?.files)?e.files:[],r=[];for(const s of t){if(!s||typeof s!="object")continue;const o=s,i=typeof o.name=="string"?o.name:void 0,c=(typeof o.path=="string"?o.path:void 0)??i;if(!c)continue;const l=o.type==="directory"||o.type==="dir"||o.isDirectory===!0,d={name:i??c.split("/").pop()??c,path:c,type:l?"directory":"file"};typeof o.size=="number"&&(d.size=o.size),typeof o.modified=="string"&&(d.modified=o.modified),typeof o.isGitignored=="boolean"&&(d.isGitignored=o.isGitignored),r.push(d)}return r}function Sa(n,e){const t=n.trim();return t==="?"?"??":e?`${t} `:` ${t}`}class wa{async list(e){return[]}async read(e,t,r){try{const s=await ka({workspaceId:e,path:t,...r?.gitRootId?{gitRootId:r.gitRootId}:{}});if(s===null)return null;const o=Ia(s)||ha(new TextEncoder().encode(s.slice(0,8192)));return Mt(t,o?{kind:"restorable-snapshot",content:s,isBinary:!0}:ds(s))}catch(s){if(s instanceof Br)return Mt(t,{kind:"preview-only",isBinary:!0});if(s instanceof Yt&&s.rpcCode===-32603){const o=_(s);if(o.endsWith("stream did not contain valid UTF-8"))return Mt(t,{kind:"preview-only",isBinary:!0});if(!r?.gitRootId&&/\(os error [23]\)$/.test(o))return null}throw s}}async explorerTree(e){const t=await u("file.tree",{workspaceId:e,path:"."});if(!Array.isArray(t))throw new Error("Invalid file.tree response: expected an array");return{name:"",path:"",type:"directory",children:Mn(t)}}async listDirectory(e,t){try{const r=await u("file.list",{workspaceId:e,path:t});return Mn(r)}catch{return[]}}async gitStatusMap(e){try{const t=await u("git.status",{workspaceId:e}),r=Array.isArray(t?.files)?t.files:[],s={};for(const o of r){const i=o,a=String(i.path??"");a&&(s[a]={status:Sa(String(i.status??""),!!i.staged)})}return s}catch{return{}}}async write(e,t,r){return b("file.write",{workspaceId:e,path:t,content:r.content,idempotencyKey:Q()})}async delete(e,t){return b("file.delete",{workspaceId:e,path:t})}async mkdir(e,t){return b("file.mkdir",{workspaceId:e,path:t,idempotencyKey:Q()})}async rename(e,t,r){return b("file.rename",{workspaceId:e,oldPath:t,newPath:r,idempotencyKey:Q()})}}const Aa=48e4;function zt(n){if(!n||typeof n!="object")return;const e=n;if(e.truncated===!0)return e.truncatedReason==="pageBudget"?"pageBudget":"fileTooLarge"}function at(n,e){if(!n||typeof n!="object")return;const t=n[e];return typeof t=="string"&&t?t:void 0}function Ta(n,e){if(!n||typeof n!="object"||at(n,e)!==void 0)return;const t=n.nextToken;return typeof t=="string"&&t?t:void 0}async function Pn(n,e,t,r){const s=[],o=new Set;let i;do{const a=await n(e,i?{...t,nextToken:i}:t);if(!Array.isArray(a))return i?s:void 0;i=void 0;for(const c of a){const l=Ta(c,r);l!==void 0?i=l:s.push(c)}if(i!==void 0){if(o.has(i))break;o.add(i)}}while(i!==void 0);return s}async function Ea(n,e,t,r){const s={...t,maxBytes:t.maxBytes??Aa},o=await Pn(n,e,s,r);if(!o)return[];const i=[...o],a=new Map;i.forEach((S,h)=>{const w=at(S,r);w!==void 0&&a.set(w,h)});let c=i.filter(S=>zt(S)==="pageBudget").map(S=>at(S,r)).filter(S=>S!==void 0);const{path:l,paths:d,...m}=s;let I=!1;for(;c.length>0;){const S=I?c.slice(0,1):c,h=await Pn(n,e,{...m,paths:S},r);if(!h)break;const w=new Set(S),R=new Set;for(const N of h){const F=at(N,r);if(F===void 0||!w.has(F))continue;if(zt(N)==="pageBudget"){R.add(F);continue}const B=a.get(F);B!==void 0&&(i[B]=N)}const H=c.filter(N=>!w.has(N)||R.has(N));if(H.length===c.length){if(I)break;I=!0}else I=!1;c=H}return i}const Ca=15e4;function Dr(n){const t=(Array.isArray(n.files)?n.files:[]).map(r=>{const s=r,o={path:String(s.path??""),status:typeof s.status=="string"?s.status.trim()||St.Modified:St.Modified,staged:!!s.staged};return typeof s.mode=="string"&&(o.mode=s.mode),typeof s.oldSha=="string"&&(o.oldSha=s.oldSha),typeof s.newSha=="string"&&(o.newSha=s.newSha),o});return{branch:String(n.branch??""),ahead:Number(n.ahead??0),behind:Number(n.behind??0),diverged:n.diverged===void 0?Number(n.ahead)>0&&Number(n.behind)>0:!!n.diverged,files:t,hasUncommittedChanges:n.hasUncommittedChanges===void 0?t.length>0:!!n.hasUncommittedChanges,hasUntrackedFiles:n.hasUntrackedFiles===void 0?t.some(r=>r.status===St.Untracked):!!n.hasUntrackedFiles}}function el(n){if(!n||typeof n!="object")return null;const e=n;return typeof e.branch!="string"||typeof e.ahead!="number"||typeof e.behind!="number"||!Array.isArray(e.files)||e.files.some(t=>!t||typeof t!="object"||typeof t.path!="string"||typeof t.status!="string"||typeof t.staged!="boolean")?null:Dr(e)}const Xe=new Map;function On(n,e){const t=ps.state,r=JSON.stringify([Qs(t),Zs(t),t.daemonHealth?.connectionGeneration,n]);if(!e?.forceRefresh){const o=Xe.get(r);if(o)return o}const s=u("git.status",{workspaceId:n,...e?.forceRefresh?{forceRefresh:!0}:{}}).then(o=>!o||typeof o!="object"?null:Dr(o)).catch(()=>null);return Xe.set(r,s),s.then(()=>{Xe.get(r)===s&&Xe.delete(r)}),s}function Ra(n){const e=n&&typeof n=="object"?n:{},t=typeof e.type=="string"?e.type:"Context",s={type:t==="Addition"?wt.Addition:t==="Deletion"?wt.Deletion:wt.Context,content:typeof e.content=="string"?e.content:""};return typeof e.oldNumber=="number"&&(s.oldNumber=e.oldNumber),typeof e.newNumber=="number"&&(s.newNumber=e.newNumber),s}function _a(n){const e=Array.isArray(n)?n:[],t=[];for(const r of e){if(!r||typeof r!="object")continue;const s=r,o=typeof s.path=="string"?s.path:"";if(!o)continue;const a=(Array.isArray(s.hunks)?s.hunks:[]).map(l=>{const d=l&&typeof l=="object"?l:{};return{oldStart:Number(d.oldStart??0),oldLines:Number(d.oldLines??0),newStart:Number(d.newStart??0),newLines:Number(d.newLines??0),lines:Array.isArray(d.lines)?d.lines.map(Ra):[]}}),c=zt(r);t.push(c?{file:o,chunks:a,truncatedReason:c}:{file:o,chunks:a})}return t}function Ma(n){if(typeof n!="string"||!n)return 0;const e=Date.parse(n);return Number.isFinite(e)?e:0}function Pa(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.path=="string"?e.path:"";if(!t)return null;const r={path:t};return typeof e.additions=="number"&&(r.additions=e.additions),typeof e.deletions=="number"&&(r.deletions=e.deletions),typeof e.status=="string"&&(r.status=e.status),r}function Oa(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.hash=="string"?e.hash:"";if(!t)return null;const r=!!e.isPushed,s={hash:t,message:typeof e.message=="string"?e.message:"",author:typeof e.author=="string"?e.author:"",timestamp:Ma(e.date),stage:r?"pushed":"local",isPushed:r};return Array.isArray(e.files)&&(s.files=e.files.map(Pa).filter(o=>o!==null)),typeof e.filesChanged=="number"&&(s.filesChanged=e.filesChanged),typeof e.date=="string"&&(s.date=e.date),typeof e.agentId=="string"&&(s.agentId=e.agentId),typeof e.linkedNoteId=="string"&&(s.linkedNoteId=e.linkedNoteId),s}function xa(n,e){const r=(Array.isArray(n.files)?n.files:[]).map(i=>typeof i=="string"?i:null).filter(i=>i!==null),o=(Array.isArray(n.fileDetails)?n.fileDetails:[]).map(i=>{if(!i||typeof i!="object")return null;const a=i,c=typeof a.path=="string"?a.path:"";return c?{path:c,additions:typeof a.additions=="number"?a.additions:0,deletions:typeof a.deletions=="number"?a.deletions:0}:null}).filter(i=>i!==null);return{commitHash:typeof n.commitHash=="string"?n.commitHash:e,author:typeof n.author=="string"?n.author:"",authorEmail:typeof n.authorEmail=="string"?n.authorEmail:"",date:typeof n.date=="string"?n.date:"",message:typeof n.message=="string"?n.message:"",files:r,fileDetails:o}}const Na=new Set(Object.values(fr)),Ba=new Set(["added","modified","deleted","renamed"]);function La(n){if(!n||typeof n!="object")return null;const e=n,t=typeof e.file=="string"?e.file:"",r=typeof e.relativePath=="string"?e.relativePath:t;if(!t&&!r)return null;const s=typeof e.stage=="string"&&Na.has(e.stage)?e.stage:fr.Unstaged,o=typeof e.status=="string"&&Ba.has(e.status)?e.status:void 0,i=e.stats&&typeof e.stats=="object"?e.stats:{},a=e.attribution&&typeof e.attribution=="object"?e.attribution:{};return{id:typeof e.id=="string"&&e.id?e.id:r||t,file:t||r,relativePath:r||t,stage:s,stats:{additions:typeof i.additions=="number"?i.additions:0,deletions:typeof i.deletions=="number"?i.deletions:0},...o?{status:o}:{},attribution:{...a.agent&&typeof a.agent=="object"?{agent:a.agent}:{},...typeof a.manual=="boolean"?{manual:a.manual}:{},timestamp:typeof a.timestamp=="number"?a.timestamp:0},...typeof e.commitHash=="string"?{commitHash:e.commitHash}:{}}}function Pt(n,e){const t=n.map(r=>r.trim()).filter(Boolean);return t.length===0?{ok:!1,failure:{success:!1,error:`No file paths provided; ${e.toLowerCase()} requires explicit paths.`}}:t.some(r=>r==="."||r==="*"||r.includes("--all"))?{ok:!1,failure:{success:!1,error:`${e} all files is not allowed; specify explicit file paths.`}}:{ok:!0,paths:t}}class ja{async originUrl(e){try{const t=await u("git.getRemoteUrl",{repoPath:e,remoteName:"origin"});return typeof t?.url=="string"?t.url:null}catch{return null}}async status(e,t){return On(e,t)}async changes(e){return On(e)}async diffs(e,t){const r={workspaceId:e};t?.path&&(r.path=t.path),t?.paths?.length&&(r.paths=t.paths),t?.staged===!0&&(r.staged=!0),t?.commitHash&&(r.commitHash=t.commitHash),t?.gitRootId&&(r.gitRootId=t.gitRootId);try{const s=await Ea(u,"git.diffs",r,"path");return _a(s)}catch{return[]}}async commitDetails(e,t,r){try{const s=await u("git.commitDetails",{workspaceId:e,commitHash:t,...r?.gitRootId?{gitRootId:r.gitRootId}:{}});return!s||typeof s!="object"?null:xa(s,t)}catch{return null}}async trackedChanges(e){try{const t=await u("file-tracking.getChanges",{workspaceId:e});return(Array.isArray(t?.changes)?t.changes:[]).map(La).filter(s=>s!==null)}catch{return null}}async commits(e,t){try{return(await this.commitsWithBoundary(e,t)).commits}catch{return[]}}async commitsWithBoundary(e,t){const r=await u("file-tracking.loadCommits",{workspaceId:e,...t!==void 0?{includeOlder:t}:{}}),s=Array.isArray(r?.commits)?r.commits:[],o=r?.boundarySha===null||typeof r?.boundarySha=="string"?r.boundarySha:null,i=r?.nextToken===null||typeof r?.nextToken=="string"?r.nextToken:null;return{commits:s.map(Oa).filter(a=>a!==null),boundarySha:o,nextToken:i,...typeof r?.historyIdentity=="string"&&r.historyIdentity?{historyIdentity:r.historyIdentity}:{}}}async getBranches(e,t,r){try{const s=await u("git.getBranches",{...r===void 0?{}:{workspaceId:r},repoPath:e,includeRemote:t});if(!s||typeof s!="object")return null;const o=Array.isArray(s.branches)?s.branches.filter(a=>typeof a=="string"):[],i=Array.isArray(s.remoteBranches)?s.remoteBranches.filter(a=>typeof a=="string"):[];return{branches:o,remoteBranches:i,currentBranch:typeof s.currentBranch=="string"?s.currentBranch:"",defaultBranch:typeof s.defaultBranch=="string"?s.defaultBranch:""}}catch{return null}}async branchStatus(e,t,r){try{const s=await u("git.branchStatus",{...r===void 0?{}:{workspaceId:r},repoPath:e,branchName:t});return!s||typeof s!="object"?null:{branch:typeof s.branch=="string"?s.branch:t,currentBranch:typeof s.currentBranch=="string"?s.currentBranch:"",isCurrentBranch:!!s.isCurrentBranch,ahead:typeof s.ahead=="number"?s.ahead:0,behind:typeof s.behind=="number"?s.behind:0,hasUncommittedChanges:!!s.hasUncommittedChanges}}catch{return null}}async prRefresh(e,t){try{const r=await u("pr.refresh",{workspaceId:e,...t});return!r||typeof r!="object"||typeof r.outcome!="string"||!["skipped","unchanged","linked","updated","unlinked"].includes(r.outcome)?null:{outcome:r.outcome,prNumber:typeof r.prNumber=="number"?r.prNumber:void 0,prUrl:typeof r.prUrl=="string"?r.prUrl:void 0,prStatus:typeof r.prStatus=="string"?r.prStatus:void 0,pullRequests:Array.isArray(r.pullRequests)?r.pullRequests:[]}}catch{return null}}async stage(e,t){const r=Pt(t,"Staging");return r.ok?b("git.stage",{workspaceId:e,paths:r.paths}):r.failure}async unstage(e,t){const r=Pt(t,"Unstaging");return r.ok?b("git.unstage",{workspaceId:e,paths:r.paths}):r.failure}async discard(e,t){const r=Pt(t,"Discarding");return r.ok?b("git.discard",{workspaceId:e,paths:r.paths}):r.failure}async commit(e,t){return t.userRequested?b("git.agentCommit",{workspaceId:e,message:t.message,...t.files!==void 0?{files:t.files}:{},userRequested:t.userRequested}):{success:!1,error:"git.agentCommit requires userRequested: true."}}async pull(e,t,r){try{const s=await u("git.pull",{repoPath:e,branchName:t,...r===void 0?{}:{workspaceId:r}},{timeoutMs:Ca});return s&&typeof s=="object"&&s.ok===!0?{success:!0}:{success:!1,error:s&&typeof s=="object"&&typeof s.error=="string"&&s.error?s.error:"Failed to pull changes"}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}}const Da=Ne("LiveIntegrationsClient");function Ua(n){return n.merged===!0?"merged":n.state==="closed"?"closed":n.draft===!0?"draft":n.isInMergeQueue===!0?"queued":"open"}class qa{captureRepositoryCheckout(e){return js(e)}async githubUser(e){try{const r=(await u("github.getUser",...e===void 0?[]:[{workspaceId:e}]))?.user;return!r||typeof r.login!="string"||r.login.length===0?null:{login:r.login,name:null,email:null,avatar_url:typeof r.avatarUrl=="string"?r.avatarUrl:""}}catch{return null}}async githubBranches(e,t,r,s){const[o,i]=await Promise.all([u("github.branches.list",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,...r?{prefix:r}:{}}),r?Promise.resolve(void 0):u("github.repos.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t}).then(c=>{const l=c?.repo?.defaultBranch;return typeof l=="string"&&l.length>0?l:void 0},()=>{})]);return{branches:Array.isArray(o?.branches)?o.branches.filter(c=>typeof c=="string"):[],defaultBranch:i}}async githubBranchesCached(e,t,r){try{const s=await u("github.branches.listCached",{owner:e,repo:t,...r===void 0?{}:{workspaceId:r}}),o=Array.isArray(s?.branches)?s.branches.filter(c=>typeof c=="string"):[],i=typeof s?.defaultBranch=="string"&&s.defaultBranch.length>0?s.defaultBranch:void 0,a=s?.source==="cache"||s?.source==="ls-remote"?s.source:void 0;return{cached:s?.cached===!0,branches:o,defaultBranch:i,source:a}}catch{return{cached:!1,branches:[]}}}async githubRepoConfig(e,t,r,s){const o=await u("github.repoConfig.get",{owner:e,repo:t,...r?{ref:r}:{},...s===void 0?{}:{workspaceId:s}}),i=o?.config&&typeof o.config=="object"&&!Array.isArray(o.config)?o.config:null;return i===null&&o?.config!=null&&Da.warn("github.repoConfig.get returned a non-object config; treating as null",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t}),{config:i,exists:o?.exists===!0}}captureRepositoryResource(e){return Ds(e)}async githubPullRequest(e,t,r,s){const i=(await u("github.pulls.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,number:r}))?.pull;if(!i)throw new Error(`Pull request ${e}/${t}#${r} not found`);const a=Ua(i),c=a==="queued"?mr(i.mergeQueue):null;return{owner:e,repo:t,number:i.number,title:i.title,state:a,author:i.user.login,createdAt:i.createdAt,updatedAt:i.updatedAt,url:i.htmlUrl,headRef:i.headRef,baseRef:i.baseRef,...c?{mergeQueue:c}:{}}}async githubIssue(e,t,r,s){const i=(await u("github.issues.get",{...s===void 0?{}:{workspaceId:s},owner:e,repo:t,number:r}))?.issue;if(!i)throw new Error(`Issue ${e}/${t}#${r} not found`);return{owner:e,repo:t,number:i.number,title:i.title,state:i.state,author:i.user.login,createdAt:i.createdAt,updatedAt:i.updatedAt,url:i.htmlUrl}}async linearIssues(e){try{return(await u("linear.authStatus",...e===void 0?[]:[{workspaceId:e}]))?.authenticated!==!0?[]:(await u("linear.listIssues",...e===void 0?[]:[{workspaceId:e}])).issues}catch{return[]}}async sentryIssues(e){try{return(await u("sentry.authStatus",...e===void 0?[]:[{workspaceId:e}]))?.authenticated!==!0?[]:(await u("sentry.listIssues",...e===void 0?[]:[{workspaceId:e}])).issues}catch{return[]}}subscribe(e){let t=!1;return this.githubUser().then(r=>{t||e({githubUser:r})}),()=>{t=!0}}}const Fa=["cli-missing","prerequisite-missing"];function $a(n){return Fa.some(e=>e===n)}function Wa(n){if(!(typeof n?.warning!="string"||!n.warning))return $a(n.warningKind)?n.warningKind:void 0}function tl(n){const{providerId:e,providerRef:t,forceRefresh:r,workspaceId:s}=n??{};if(typeof e!="string"||!e)return;const o={providerId:gs(e,t)};return typeof s=="string"&&s&&(o.workspaceId=s),r===!0&&(o.forceRefresh=!0),o}function nl(n){const e=n?.providerId;return{success:!1,error:T.providers_modelsClient_unsupportedProvider_error({id:String(e??"")})}}function rl(n){const e={success:!0,data:Ur(n)};typeof n?.warning=="string"&&n.warning&&(e.warning=n.warning),n?.stale===!0&&(e.stale=!0);const t=Wa(n);return t&&(e.warningKind=t),e}function Ga(n){if(typeof n?.id!="string"||!n.id||typeof n?.name!="string"||!n.name)return null;const e={value:n.id,label:n.name};return typeof n.description=="string"&&(e.description=n.description),typeof n.modelGroupPriority=="number"&&(e.modelGroupPriority=n.modelGroupPriority),typeof n.costTier=="number"&&(e.costTier=n.costTier),Array.isArray(n.badges)&&(e.badges=n.badges),Array.isArray(n.effortLevels)&&(e.effortLevels=n.effortLevels),n.isDefault===!0&&(e.isDefault=!0),n.isLegacyModel===!0&&(e.isLegacyModel=!0),typeof n.priority=="number"&&(e.priority=n.priority),e}function Ur(n){return Array.isArray(n?.models)?n.models.flatMap(e=>Ga(e)??[]):[]}class Ha{async list(e,t){try{const r=e||t?await u("models.list",{...e?{providerId:e}:{},...t?{workspaceId:t}:{}}):await u("models.list");return e&&r.providerId!==e?[]:Ur(r)}catch{return[]}}subscribe(e){let t=!1;return this.list().then(r=>{t||e(r)}),()=>{t=!0}}}function Kt(n){if(typeof n=="number"&&Number.isFinite(n)&&n>=0)return Math.trunc(n);if(typeof n=="string"&&n.length>0){const e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.trunc(e)}return null}function Va(n){if(!n||typeof n!="object")return null;const e=n,t=Kt(e.v);if(t===null)return null;const r=e.author&&typeof e.author=="object"?e.author:null,s=r?{id:String(r.id??""),name:String(r.name??""),type:typeof r.type=="string"?r.type:vs.System}:void 0;return{versionId:String(t),versionNumber:t,content:String(e.content??""),title:String(e.title??""),...s?{author:s}:{},createdAt:String(e.date??"")}}class za extends Error{constructor(){super("Truncated note read capability is unknown: no acknowledged hello yet"),this.name="NoteCapabilityUnknownError"}}function Ka(n){return n instanceof Error?n.message===T.agent_placement_unavailable()?!1:n.name!=="UnbridgedMockIpcChannelError":!0}const Ja=30,Ya=100;function Fe(n,e){const t=new Date().toISOString(),r=String(n.id??"");return{...n,id:hs(r),workspaceId:ur(String(n.workspaceId??e)),title:String(n.title??""),content:String(n.content??""),contentType:typeof n.contentType=="string"?n.contentType:ms.Markdown,tags:Array.isArray(n.tags)?n.tags:[],isPinned:!!(n.isPinned??n.is_pinned??!1),isArchived:!!(n.isArchived??n.is_archived??!1),visibility:typeof n.visibility=="string"?n.visibility:ys.Workspace,rev:typeof n.rev=="number"?n.rev:void 0,contentPreview:typeof n.contentPreview=="string"?n.contentPreview:void 0,contentLength:typeof n.contentLength=="number"?n.contentLength:void 0,contentTruncated:n.contentTruncated===!0?!0:void 0,contentBytes:n.contentTruncated===!0&&typeof n.contentBytes=="number"?n.contentBytes:void 0,createdAt:String(n.createdAt??n.created_at??t),updatedAt:String(n.updatedAt??n.updated_at??t)}}class Za{async list(e,t){const r=o=>u("note.list",o);let s;if(t?.projection==="slim")try{s=await Ce(r,{workspaceId:e,projection:"slim",limit:ve},"notes")}catch(o){if(!cr(o))throw o;s=await Ce(r,{workspaceId:e,limit:ve},"notes")}else s=await Ce(r,{workspaceId:e,limit:ve},"notes");return s.map(o=>{const i=Fe(o,e);return He(String(i.id),e),i})}async supportsTruncatedRead(){for(let e=0;e<Ja;e++){try{const r=(await Us())?.server?.capabilities;if(r)return r.noteTruncatedRead===1}catch(t){if(!Ka(t))return!1}await new Promise(t=>setTimeout(t,Ya))}throw new za}async get(e,t,r){const s=t??await ie(e);if(!s)return null;try{const o=r?.maxContentBytes!==void 0?await u("note.get",{workspaceId:s,noteId:e,maxContentBytes:r.maxContentBytes}):await Sr(a=>u("note.get",a),{workspaceId:s,noteId:e}),i=o&&typeof o=="object"&&"note"in o?o.note:o;return!i||typeof i!="object"?null:Fe(i,s)}catch{return null}}async create(e){return Wt("note.create",{...e,idempotencyKey:Q()})}async setContent(e,t,r,s,o){return this.runNoteMutation(e,"note.setContent",{content:t,...o?.baseContentBytes!==void 0?{baseContentBytes:o.baseContentBytes}:{}},r,s)}async add(e,t,r,s,o){return this.runNoteMutation(e,"note.add",{content:t,...r?.heading!==void 0?{heading:r.heading}:{},...r?.position!==void 0?{position:r.position}:{}},s,o)}async edit(e,t,r,s,o){return this.runNoteMutation(e,"note.edit",{old:t,new:r},s,o)}async editLines(e,t,r,s,o,i){return this.runNoteMutation(e,"note.editLines",{start:t,end:r,content:s},o,i)}async delete(e,t,r){return this.runNoteMutation(e,"note.delete",{},t,r)}async updateMetadata(e,t,r,s){return this.runNoteMutation(e,"note.updateMetadata",{...t.title!==void 0?{title:t.title}:{},...t.tags!==void 0?{tags:t.tags}:{}},r,s)}async listVersions(e,t){const r=await u("note.listVersions",{workspaceId:e,noteId:t});return!Array.isArray(r)||r.length===0?[]:(await Promise.all(r.map(o=>{const i=Kt(o.v);return i===null?Promise.resolve(null):u("note.getVersion",{workspaceId:e,noteId:t,v:i}).then(a=>Va(a)).catch(()=>null)}))).filter(o=>o!==null)}async restoreVersion(e,t,r){const s=Kt(r);if(s===null)return{success:!1,error:`Invalid version id: ${r}`};try{const o=await u("note.restoreVersion",{workspaceId:e,noteId:t,v:s});return{success:!0,note:o&&typeof o=="object"&&o.note&&typeof o.note=="object"?Fe(o.note,e):void 0}}catch(o){return{success:!1,error:o instanceof Error?o.message:String(o)}}}async runNoteMutation(e,t,r,s,o){const i=o??await ie(e);if(!i)return{success:!1,error:`Cannot resolve workspace for note ${e}`};const a=await b(t,{workspaceId:i,noteId:e,...r,...s!==void 0?{expectedVersion:s}:{}}),c=a.conflict?.current;return c&&typeof c=="object"?{...a,conflict:{current:Fe(c,i)}}:a}subscribe(e){return Je({channel:{subscribeMethod:"note.subscribe",unsubscribeMethod:"note.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t,limit:ve})},continuation:{method:"note.list",key:"notes",params:t=>({workspaceId:t.workspaceId,limit:ve})}},getId:t=>String(t.id??""),normalize:t=>{const r=String(t.workspaceId??"");if(!r)return null;const s=Fe(t,r);return He(String(s.id),r),s},handler:e})}}class Qa{async catalog(e){const t=bs.parse(e?{workspaceId:e}:{}),r=await u(Ps,t);return ks.parse(r)}async listProfiles(e){const t=await u(Os,e?{baseProviderId:e}:{});return Is.parse(t)}async createProfile(e){const t=await u(Ss,{baseProviderId:e.baseProviderId,name:e.name,...e.env?{env:e.env}:{},...e.backup!==void 0?{backup:e.backup}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return ws.parse(t)}async updateProfile(e){const t=await u(As,{profileId:e.profileId,...e.name!==void 0?{name:e.name}:{},...e.env?{env:e.env}:{},...e.backup!==void 0?{backup:e.backup}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return Ts.parse(t)}async updateDefault(e){const t=await u(Es,{baseProviderId:e.baseProviderId,...e.name!==void 0?{name:e.name}:{},...e.env?{env:e.env}:{},...e.remoteCompatible!==void 0?{remoteCompatible:e.remoteCompatible}:{}});return Cs.parse(t)}async deleteProfile(e){const t=await u(xs,{profileId:e});return Rs.parse(t)}async reorderProfiles(e){const t=await u(_s,{baseProviderId:e.baseProviderId,profileIds:e.profileIds});return Ms.parse(t)}}const Xa=200;function Ot(n){return n?{remoteAgentId:n.remoteAgentId}:{}}class ec{async supportsLifecycle(){return(await u("client.hello",{}))?.server?.capabilities?.scriptLifecycle===1}async requireActiveLists(){const e=await u("client.hello",{});if(e.server?.capabilities?.scriptActiveLists!==1)throw new Error(T.scripts_list_unsupported_error());return{fullPages:e.server?.capabilities?.boundedReads===1}}async list(e,t){const{fullPages:r}=await this.requireActiveLists(),s=[],o=new Set;let i;do{const a=await u("script.list",{workspaceId:e,archive:t?.archive??"active",...r?{limit:Xa,...i?{cursor:i}:{}}:{}});if(!Array.isArray(a?.scripts))throw new Error(T.scripts_list_load_error());for(const l of a.scripts)s.push(tc(l)?await xn(e,l.id):l);const c=r?a.nextCursor:void 0;if(typeof c=="string"&&c&&!o.has(c))o.add(c),i=c;else{if(c!=null)throw new Error(T.scripts_list_load_error());i=void 0}}while(i);return s}async listPage(e,t){await this.requireActiveLists();const r=await u("script.list",{workspaceId:e,archive:"active",view:"summary",limit:100,...t});if(r?.view!=="summary"||!Array.isArray(r.scripts))throw new Error(T.scripts_list_unsupported_error());return r}async get(e,t){return await this.requireActiveLists(),xn(e,t)}async archive(e,t,r){if(!r?.capabilityVerified&&!await this.supportsLifecycle())throw new Error(T.scripts_list_unsupported_error());return u("script.archive",{workspaceId:e,scriptIds:t})}async restore(e,t,r){if(!r?.capabilityVerified&&!await this.supportsLifecycle())throw new Error(T.scripts_list_unsupported_error());return u("script.restore",{workspaceId:e,scriptIds:t})}async create(e,t){try{if(t.scriptId!==void 0)throw new Error("Use scriptsClient.update to edit an existing script.");const r=await u("script.create",{workspaceId:e,name:t.name,command:t.command,mode:t.mode,...t.purpose!==void 0?{purpose:t.purpose}:{},...t.cwd!==void 0?{cwd:t.cwd}:{},...t.env!==void 0?{env:t.env}:{},...t.category!==void 0?{category:t.category}:{},...t.autoStart!==void 0?{autoStart:t.autoStart}:{},...t.healthUrl!==void 0?{healthUrl:t.healthUrl}:{},...t.readyPattern!==void 0?{readyPattern:t.readyPattern}:{}}),s=typeof r?.id=="string"?r.id:void 0;return{success:!0,...s?{id:s}:{},...r?{script:r}:{}}}catch(r){return{success:!1,error:r instanceof Error?r.message:String(r)}}}async start(e,t){return b("script.start",{workspaceId:e,scriptId:t})}async stop(e,t,r){return b("script.stop",{workspaceId:e,scriptId:t,...Ot(r)})}async restart(e,t,r){return b("script.restart",{workspaceId:e,scriptId:t,...Ot(r)})}async output(e,t,r,s){try{const o=await u("script.output",{workspaceId:e,scriptId:t,...r!==void 0?{maxLines:r}:{},...Ot(s)});return typeof o=="string"?o:""}catch{return""}}async status(e,t){try{const r=await u("script.status",{workspaceId:e,scriptId:t});return r&&typeof r=="object"?r:null}catch{return null}}async run(e,t,r){try{const s=await u("script.run",{workspaceId:e,scriptId:t,...r?.maxLines!==void 0?{maxLines:r.maxLines}:{},...r?.timeoutSeconds!==void 0?{timeoutSeconds:r.timeoutSeconds}:{}});return s&&typeof s=="object"?s:null}catch{return null}}subscribe(e){return e([]),()=>{}}}function tc(n){return Object.entries(n).some(([e,t])=>e.endsWith("Omitted")&&t===!0)}const nc=3,rc=4096;async function xn(n,e){for(let t=0;t<nc;t++){const r=await u("script.get",{workspaceId:n,scriptId:e});if(r?.commandTruncated!==!0)return r;const s=r.commandBytes;let o=r.command,i=r.nextCommandOffset,a=!1,c=1;for(;typeof i=="number";){if(++c>rc)throw new Error(T.scripts_list_load_error());const h=await u("script.get",{workspaceId:n,scriptId:e,commandOffset:i});if(h?.commandBytes!==s||h.commandOffset!==i||h.updatedAt!==r.updatedAt){a=!0;break}o+=h.command;const w=h.nextCommandOffset;if(typeof w=="number"&&w<=i)throw new Error(T.scripts_list_load_error());i=w}if(a)continue;if(new TextEncoder().encode(o).length!==s)throw new Error(T.scripts_list_load_error());const{commandTruncated:l,commandBytes:d,commandOffset:m,nextCommandOffset:I,...S}=r;return{...S,command:o}}throw new Error(T.scripts_list_load_error())}const sc=["stdio","http","sse"],oc=["oauth","header","none"];function xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Nn(n){const e=new WeakSet;try{const t=JSON.stringify(n,(r,s)=>!xe(s)&&!Array.isArray(s)?s:e.has(s)?"[Circular]":(e.add(s),Array.isArray(s)?s:Object.keys(s).sort().reduce((o,i)=>(o[i]=s[i],o),{})));return t===void 0?void 0:t}catch{return}}function qr(n,e,t){if(n==null)return e;if(typeof n=="string")return n||e;if(n instanceof Error)return n.message||e;if(xe(n)){if(t.has(n))return Nn(n)??e;t.add(n);for(const r of["message","error","reason","details"])if(r in n)return qr(n[r],e,t)}return Nn(n)??String(n||e)}function sl(n,e){return qr(n,e,new WeakSet)}function Se(n){return typeof n=="string"&&n.trim()?n.trim():void 0}function ic(n){if(Array.isArray(n)){const e=n.filter(t=>typeof t=="string");return e.length>0?e:void 0}if(typeof n=="string"){const e=n.trim().split(/\s+/).filter(Boolean);return e.length>0?e:void 0}}function Bn(n){if(!xe(n))return;const e=Object.entries(n).filter(t=>typeof t[1]=="string");return Object.fromEntries(e)}function ac(n){return oc.includes(n)?n:void 0}function ol(n){switch(n){case"running":return"connected";case"starting":return"configured";case"stopped":return"stopped";case"error":return"error";case"auth_required":return"auth_required";default:return null}}function xt(n,e){if(!xe(n))return null;const t=Se(n.name)??Se(e);if(!t)return null;const r=n.type??n.transport,s=sc.includes(r)?r:Se(n.command)?"stdio":"http",o={name:t,type:s},i=Se(n.id);i&&(o.id=i);const a=Se(n.command),c=Se(n.url),l=ic(n.args),d=Bn(n.env),m=Bn(n.headers),I=ac(n.authType);return a&&(o.command=a),c&&(o.url=c),l&&(o.args=l),d&&(o.env=d),m&&(o.headers=m),I&&(o.authType=I),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),o}function cc(n){if(Array.isArray(n))return n.flatMap(r=>xt(r)??[]);if(!xe(n))return[];const e=n.mcpServers??n.servers;if(Array.isArray(e))return e.flatMap(r=>xt(r)??[]);const t=xe(e)?e:n;return Object.entries(t).flatMap(([r,s])=>xt(s,r)??[])}function Fr(n){const e=new Set,t=new Map;for(const r of n){const s=lr(r);if(e.has(s))throw new Error(`Duplicate MCP server identity: ${s}`);e.add(s);const o=t.get(r.name);if(o&&(!o.id||!r.id))throw new Error(`Duplicate MCP server name requires distinct IDs: ${r.name}`);t.set(r.name,r)}}function il(n){const e=cc(n);return Fr(e),e}function al(n){const e={name:n.name,type:n.type};return n.id!==void 0&&(e.id=n.id),n.command!==void 0&&(e.command=n.command),n.args!==void 0&&(e.args=[...n.args]),n.url!==void 0&&(e.url=n.url),n.authType!==void 0&&(e.authType=n.authType),n.disabled!==void 0&&(e.disabled=n.disabled),n.workspaceDisabled!==void 0&&(e.workspaceDisabled=n.workspaceDisabled),n.plugin!==void 0&&(e.plugin=n.plugin),e}const Ln="global",be=new Map,We=new Map,he=new Map;let Me=0,$r=0;function Wr(n,e){return JSON.stringify([$r,e??null,n])}let jn=!1;function uc(n){if(n.method!=="events.event"||!n.params)return;const e=n.params,t=e.event&&typeof e.event=="object"?e.event:e;return typeof t.type=="string"?t.type:void 0}function Gr(){jn||(jn=!0,typeof ae=="function"&&ae(n=>{uc(n)==="settings:changed"&&Ve()}),typeof ce=="function"&&ce(()=>{$r+=1,Ve()}))}function Ve(n){if(Me+=1,!n)be.clear();else for(const e of be.keys())n.includes(JSON.parse(e)[2])&&be.delete(e)}function lc(n){return n?.definition?{...n.definition,value:n.value,...n.origin?{origin:n.origin}:{},...typeof n.revision=="number"?{revision:n.revision}:{}}:null}function Hr(n,e){Gr();const t=Wr(n,e);if(be.has(t))return Promise.resolve(be.get(t)??null);const r=We.get(t);if(r?.generation===Me)return r.promise;if(r){const i=he.get(t);if(i)return i;const a=r.promise.catch(()=>null).then(()=>he.get(t)!==a?null:(he.delete(t),Hr(n,e))).finally(()=>{he.get(t)===a&&he.delete(t)});return he.set(t,a),a}const s=Me,o=u("settings.get",{path:n,...e?{workspaceId:e}:{}}).then(lc).then(i=>(s===Me&&be.set(t,i),i)).finally(()=>{We.get(t)?.promise===o&&We.delete(t)});return We.set(t,{generation:s,promise:o}),o}async function dc(n){if(n.length===0)return{applied:[],revision:0};const e=await u("settings.update",{changes:n});return Ve(n.map(({path:t})=>t)),{applied:Array.isArray(e?.applied)?e.applied:[],revision:typeof e?.revision=="number"?e.revision:0}}function cl(){Ve(),We.clear(),he.clear()}function Dn(n){const e=[];for(const[t,r]of Object.entries(n))r!==void 0&&e.push({path:t,value:r});return e}class fc{async list(e){return(await this.listSnapshot(e)).settings}async listSnapshot(e){Gr();const t=Me;try{const r=await u("settings.list",...e?[{workspaceId:e}]:[]),s={settings:Array.isArray(r?.settings)?r.settings:[],revision:typeof r?.revision=="number"?r.revision:0};if(t===Me)for(const o of s.settings)be.set(Wr(o.path,e),o);return s}catch{return{settings:[],revision:0}}}async get(e,t){try{return await Hr(e,t)}catch{return null}}async update(e){return(await this.updateSnapshot(e)).applied}async updateSnapshot(e){return dc(e)}async reset(e){try{const t=await u("settings.reset",{path:e});return typeof t?.path!="string"?null:(Ve([t.path]),{path:t.path,value:t.value})}catch{return null}}async getUserRule(e,t){try{const r=await u("rules.get",{workspaceId:t??Ln,ruleType:e});return!r||typeof r.content!="string"?null:{enabled:r.enabled===!0,content:r.content,updatedAt:typeof r.updatedAt=="number"?r.updatedAt:0}}catch{return null}}async updateUserRule(e,t,r){return b("rules.update",{workspaceId:Ln,ruleType:e,content:t,...r!==void 0?{enabled:r}:{}})}async getUserPreferences(){return null}async setUserPreferences(e){return{success:!0}}async getProviderSettings(e){const t=await this.list(e),r=Nt(t,"model.defaultProvider"),s=et(t,"providers.enabled");return r===null&&s===null?null:{activeProviderId:r??"",enabledProviders:s??{}}}async setProviderSettings(e){return b("settings.update",{changes:Dn({"model.defaultProvider":e.activeProviderId,"providers.enabled":e.enabledProviders})})}async getMcpServers(e){return(await qn(e)).flatMap(r=>Vr(r)??[])}async getMcpServerStatuses(e,t){return(await Promise.all(e.map(async s=>{try{const o=await u("mcp.servers.getStatus",{serverId:s,...t?{workspaceId:t}:{}});return Un(s,o?.status)}catch{return null}}))).filter(s=>s!==null)}async restartMcpServer(e){const t=await u("mcp.servers.restart",{serverId:e}),r=Un(e,t?.status);if(!r)throw new Error("The daemon returned an invalid MCP server status.");return r}async getWorkspaceDisabledMcpServerKeys(e){try{const t=await u("mcp.servers.list",{workspaceId:e});return Array.isArray(t?.servers)?t.servers.flatMap(r=>r.workspaceDisabled===!0&&typeof r.name=="string"&&r.name?[lr({id:r.id,name:r.name})]:[]):null}catch{return null}}async toggleWorkspaceMcpServer(e,t,r){try{const s=await u("mcp.servers.toggle",{serverId:t,enabled:r,workspaceId:e});return typeof s?.workspaceDisabled=="boolean"?{success:!0,workspaceDisabled:s.workspaceDisabled}:{success:!0}}catch(s){return{success:!1,error:s instanceof Error?s.message:String(s)}}}async setMcpServers(e){try{Fr(e);const t=await qn(),r=new Map(t.map(i=>[i.id,i])),s=e.map(i=>{if(i.id!==void 0)return{config:i,current:r.get(i.id)};const a=t.filter(c=>c.name===i.name);if(a.length>1)throw new Error(`Ambiguous MCP server name: ${i.name}`);return{config:i,current:a[0]}}),o=new Set;for(const{config:i,current:a}of s){const c=a?.id??i.id;if(c){if(o.has(c))throw new Error(`Duplicate MCP server identity: ${c}`);o.add(c)}}for(const i of t)i.id&&!i.plugin&&!o.has(i.id)&&await u("mcp.servers.delete",{serverId:i.id});for(const{config:i,current:a}of s){if(i.plugin&&!a?.plugin)continue;if(!a?.id){await u("mcp.servers.create",{config:Fn(i,i.id)});continue}const c={...i,env:i.env??a.env,headers:i.headers??a.headers};!a.plugin&&!pc(a,c)&&await u("mcp.servers.update",{serverId:a.id,config:Fn(c,a.id)});const l=i.disabled!==!0;a.enabled!==!1!==l&&await u("mcp.servers.toggle",{serverId:a.id,enabled:l})}return{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async getWorkspaceSettings(e){try{const t=await u("workspace.getAutoCommit",{workspaceId:e});return typeof t?.autoCommit?.enabled!="boolean"?null:{autoCommitEnabled:t.autoCommit.enabled}}catch{return null}}async setWorkspaceSettings(e,t){return t.autoCommitEnabled===void 0?{success:!0}:b("workspace.setAutoCommit",{workspaceId:e,enabled:t.autoCommitEnabled})}async getBackgroundAgentSettings(e){const t=await this.list(e),r=Nt(t,"quickActions.defaultReasoningEffort"),s=et(t,"quickActions.typeReasoningEffortOverrides"),o=Nt(t,"quickActions.defaultModel"),i=et(t,"quickActions.typeOverrides"),a=et(t,"quickActions.providerSettings");return o===null&&i===null&&a===null&&r===null&&s===null?null:{defaultReasoningEffort:r??"",typeReasoningEffortOverrides:s??{},defaultModel:o??"",typeOverrides:i??{commit:"",pr:"",review:"",fast:""},providerSettings:a??{}}}async setBackgroundAgentSettings(e){return b("settings.update",{changes:Dn({"quickActions.defaultReasoningEffort":e.defaultReasoningEffort,"quickActions.typeReasoningEffortOverrides":e.typeReasoningEffortOverrides,"quickActions.defaultModel":e.defaultModel,"quickActions.typeOverrides":e.typeOverrides,"quickActions.providerSettings":e.providerSettings})})}subscribe(e){return e(null),()=>{}}}function Un(n,e){if(typeof e?.serverId=="string"&&e.serverId&&e.serverId!==n||e?.state!=="stopped"&&e?.state!=="starting"&&e?.state!=="running"&&e?.state!=="error"&&e?.state!=="auth_required")return null;const t={serverId:n,state:e.state};return typeof e.lastError=="string"&&e.lastError&&(t.lastError=e.lastError),t}async function qn(n){try{const e=await u("mcp.servers.list",...n?[{workspaceId:n}]:[]);return Array.isArray(e?.servers)?e.servers:[]}catch{return[]}}function Vr(n){if(typeof n?.name!="string"||!n.name)return null;const e=n.transport==="http"||n.transport==="sse"?n.transport:"stdio",t={name:n.name,type:e};return typeof n.id=="string"&&n.id&&(t.id=n.id),typeof n.command=="string"&&n.command&&(t.command=n.command),Array.isArray(n.args)&&(t.args=n.args),n.env&&typeof n.env=="object"&&(t.env=n.env),typeof n.url=="string"&&n.url&&(t.url=n.url),n.headers&&typeof n.headers=="object"&&(t.headers=n.headers),n.enabled===!1&&(t.disabled=!0),typeof n.workspaceDisabled=="boolean"&&(t.workspaceDisabled=n.workspaceDisabled),typeof n.plugin=="string"&&n.plugin&&(t.plugin=n.plugin),t}function Fn(n,e){const t={name:n.name,transport:n.type,enabled:n.disabled!==!0};return e&&(t.id=e),n.command&&(t.command=n.command),n.args&&(t.args=n.args),n.env&&(t.env=n.env),n.url&&(t.url=n.url),n.headers&&(t.headers=n.headers),t}function pc(n,e){const t=Vr(n);if(!t)return!1;const r=o=>o?Object.entries(o).sort(([i],[a])=>i.localeCompare(a)):null,s=o=>JSON.stringify([o.name,o.type,o.command??null,o.args??null,r(o.env),o.url??null,r(o.headers)]);return s(t)===s(e)}function zr(n,e){for(const t of n)if(t.path===e)return t;return null}function Nt(n,e){const t=zr(n,e);return t&&typeof t.value=="string"?t.value:null}function et(n,e){const t=zr(n,e);return!t||t.value===null||typeof t.value!="object"?null:t.value}function Bt(n){if(!n||typeof n!="object")return null;const e=n.setupScript;return!e||typeof e!="object"?null:e}class gc{async get(e){try{const t=await u("workspace.getSetupScript",{workspaceId:e});return Bt(t)}catch{return null}}async save(e,t){try{const r=await u("workspace.saveSetupScript",{workspaceId:e,script:t});return Bt(r)}catch{return null}}async detectProjectType(e){try{const t=await u("workspace.detectProjectType",{workspaceId:e});return typeof t?.projectType=="string"?t.projectType:null}catch{return null}}async generate(e){try{const t=await u("workspace.generateSetupScript",{workspaceId:e});return Bt(t)}catch{return null}}}const Lt=Ne("LiveSkillsClient"),yc=["machine-offline","machine-update-required"],$n=500,Wn=100;function jt(n){return{name:n.name,description:n.description,location:n.location,...n.resourceDirectory?{resourceDirectory:n.resourceDirectory}:{},scope:n.scope}}class mc{async fetchList(e){const t=[],r=new Set;let s;for(let o=0;o<Wn;o++){const i=await u("skill.list",{workspaceId:e,limit:$n,...s?{nextToken:s}:{}});if(Array.isArray(i))return i.map(jt);for(const a of Array.isArray(i?.skills)?i.skills:[])r.has(a.name)||(r.add(a.name),t.push(jt(a)));if(s=typeof i?.nextToken=="string"?i.nextToken:void 0,!s)return t}return Lt.warn("skill.list paging stopped at the page limit"),t}async list(e){return this.fetchList(e)}async listForAgent(e,t){const r=[],s=new Set;let o=!1,i=null,a;for(let c=0;c<Wn;c++){const l=await u("skill.list",{workspaceId:e,agentId:t,limit:$n,...a?{nextToken:a}:{}});for(const m of Array.isArray(l?.skills)?l.skills:[])s.has(m.name)||(s.add(m.name),r.push(jt(m)));if(o=l?.stale===!0,i=yc.find(m=>m===l?.unavailable)??null,a=typeof l?.nextToken=="string"?l.nextToken:void 0,!a)return{skills:r,stale:o,unavailable:i}}return Lt.warn("skill.list paging stopped at the page limit"),{skills:r,stale:o,unavailable:i}}subscribe(e){let t=!1,r,s;e([]);const o=l=>{this.fetchList(l).then(d=>{t||e(d)}).catch(d=>{Lt.error("Failed to refetch skill list; keeping last known-good view",d)})},i=()=>Jt({eventTypes:["skills:changed"]}).then(l=>{r=l?.subscriptionId,t&&r&&Oe(r)}).catch(()=>{});i();const a=ae(l=>{if(l.method==="skills:changed"&&!t){const m=l.params?.workspaceId;m&&(s=m,o(m))}}),c=ce(()=>{t||(r=void 0,i(),s&&o(s))});return()=>{t=!0,a(),c(),r&&Oe(r)}}}const Dt=Ne("LiveSpecialistsClient"),hc=100,vc=500,bc=100;class kc{async listCatalog(e,t,r){const s={...e?{provider:e}:{},...t?{workspaceId:t}:{},...r?.includeProject?{includeProject:!0}:{}},o=[],i=new Set;let a,c;for(let d=0;d<bc;d++){const m=await u("specialist.list",{...s,limit:vc,...c?{nextToken:c}:{}});for(const I of Array.isArray(m?.specialists)?m.specialists:[])i.has(I.id)||(i.add(I.id),o.push(I));if(d===0&&(a=m?.importDiagnostics),c=typeof m?.nextToken=="string"?m.nextToken:void 0,!c)break}return c&&Dt.warn("specialist.list paging stopped at the page limit"),{specialists:await Promise.all(o.map(d=>d.behaviorPromptOmitted?this.hydrateOmittedPrompt(d,e,t):d)),importDiagnostics:a}}async hydrateOmittedPrompt(e,t,r){try{const o=(await u("specialist.get",{id:e.id,...t?{provider:t}:{},...r?{workspaceId:r}:{}}))?.specialist;if(o&&o.id===e.id&&o.source===e.source&&!o.behaviorPromptOmitted&&typeof o.behaviorPrompt=="string")return{...e,...o,behaviorPromptOmitted:void 0,behaviorPromptBytes:void 0}}catch(s){Dt.warn(`specialist.get for omitted prompt of ${e.id} failed`,s)}return e}async list(e,t){try{return(await this.listCatalog(e,t)).specialists}catch{return[]}}subscribe(e){return this.subscribeCatalogSnapshot(t=>e(t.specialists),()=>e([]))}subscribeCatalog(e){return this.subscribeCatalogSnapshot(e)}subscribeCatalogSnapshot(e,t){let r=!1,s,o;this.listCatalog().then(d=>{r||e(d)}).catch(()=>{r||t?.()});const i=()=>{this.listCatalog().then(d=>{r||e(d)}).catch(d=>{Dt.error("Failed to refetch specialist list; keeping last known-good view",d)})},a=()=>Jt({eventTypes:["specialists:changed","skills:changed"]}).then(d=>{s=d?.subscriptionId,r&&s&&Oe(s)}).catch(()=>{});a();const c=ae(d=>{(d.method==="specialists:changed"||d.method==="skills:changed")&&!r&&(o!==void 0&&clearTimeout(o),o=setTimeout(()=>{o=void 0,i()},hc))}),l=ce(()=>{r||(s=void 0,a(),o!==void 0&&(clearTimeout(o),o=void 0),i())});return()=>{r=!0,o!==void 0&&(clearTimeout(o),o=void 0),c(),l(),s&&Oe(s)}}async create(e,t,r,s,o){const i={id:e,spec:t};return r&&(i.scope=r),s&&(i.workspacePath=s),r==="project"&&o&&(i.workspaceId=o),(await u("specialist.create",i)).specialist}async edit(e,t,r,s,o){const i={id:e,spec:t,scope:r};return s&&(i.workspacePath=s),r==="project"&&o&&(i.workspaceId=o),(await u("specialist.edit",i)).specialist}async delete(e,t,r,s){const o={id:e,scope:t};return r&&(o.workspacePath=r),t==="project"&&s&&(o.workspaceId=s),await u("specialist.delete",o)}}class Ic{async getUsage(e,t,r){const s={period:e,tzOffsetMinutes:r};t!==void 0&&(s.key=t);const o=await u("stats.getUsage",s);for(const i of["byModel","byProvider"])if(!Array.isArray(o[i]))throw new Error(`stats.getUsage result is missing the required \`${i}\` array (PROTOCOL §5.36) — the daemon is likely outdated and predates this field`);return o}}const Sc=12e4;function wc(n){return typeof n.arrayBuffer=="function"?n.arrayBuffer():new Promise((e,t)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>t(r.error??new Error("Blob read failed")),r.readAsArrayBuffer(n)})}async function Ac(n){const e=new Uint8Array(await wc(n)),t=32768;let r="";for(let s=0;s<e.length;s+=t)r+=String.fromCharCode(...e.subarray(s,s+t));return btoa(r)}class Tc{async transcribe(e,t,r,s){const o={audio:await Ac(e),mimeType:t};return r&&(r.prompt!==void 0||r.keyterms!==void 0)&&(o.context=r),typeof s=="string"&&s.trim().length>0&&(o.workspaceId=s),u("voice.transcribe",o,{timeoutMs:Sc})}async getWorkspaceVocabulary(e){return u("voice.getWorkspaceVocabulary",{workspaceId:e})}}const Ec=["stable","beta","alpha","disabled"];function ul(n){return Ec.includes(n)}const M={CHECK_MANUAL:"auto-update:check-manual",DOWNLOAD:"auto-update:download",INSTALL:"auto-update:install",DISMISS_DOWNLOADED_TOAST:"auto-update:dismiss-downloaded-toast",GET_STATE:"auto-update:get-state",SET_CHANNEL:"auto-update:set-channel",SET_SHARE_STATISTICS:"auto-update:set-share-statistics",STATUS_CHANGED:"auto-update:status-changed",PROGRESS:"auto-update:progress",ERROR:"auto-update:error",UP_TO_DATE:"auto-update:up-to-date",SHOW_TOAST:"auto-update:show-toast"},Cc={async checkForUpdatesManual(){const n=await ee(M.CHECK_MANUAL);if(!n.success||n.data===void 0)throw new Error(n.error?.message||T.autoUpdate_client_checkFailed_error());return n.data},async downloadUpdate(){const n=await ee(M.DOWNLOAD);if(!n.success)throw new Error(n.error?.message||T.autoUpdate_client_downloadFailed_error())},async installUpdate(){const n=await ee(M.INSTALL);if(!n.success)throw new Error(n.error?.message||T.autoUpdate_client_installFailed_error())},async dismissDownloadedToast(){const n=await ee(M.DISMISS_DOWNLOADED_TOAST);if(!n.success)throw new Error(n.error?.message||"Could not dismiss the update notice")},async getState(){const n=await ee(M.GET_STATE);if(!n.success||n.data===void 0)throw new Error(n.error?.message||T.autoUpdate_client_getStateFailed_error());return n.data},async setChannel(n){const e=await ee(M.SET_CHANNEL,{channel:n});if(!e.success)throw new Error(e.error?.message||T.autoUpdate_client_setChannelFailed_error())},async setShareStatistics(n){const e=await ee(M.SET_SHARE_STATISTICS,{enabled:n});if(!e.success)throw new Error(e.error?.message||T.autoUpdate_client_setShareStatisticsFailed_error())},onStatusChanged(n){const e=window.electronAPI.on(M.STATUS_CHANGED,n);return()=>{e&&window.electronAPI.offById(M.STATUS_CHANGED,e)}},onProgress(n){const e=window.electronAPI.on(M.PROGRESS,n);return()=>{e&&window.electronAPI.offById(M.PROGRESS,e)}},onError(n){const e=window.electronAPI.on(M.ERROR,n);return()=>{e&&window.electronAPI.offById(M.ERROR,e)}},onShowToast(n){const e=window.electronAPI.on(M.SHOW_TOAST,n);return()=>{e&&window.electronAPI.offById(M.SHOW_TOAST,e)}},onUpToDate(n){const e=window.electronAPI.on(M.UP_TO_DATE,n);return()=>{e&&window.electronAPI.offById(M.UP_TO_DATE,e)}}};class Rc{async status(){try{const e=await u("system.status");return!e||typeof e!="object"?{nodeVersionOk:null,nodeVersion:void 0,auggieInstalled:!1,binaryInstallAvailable:!1}:{nodeVersionOk:typeof e.nodeVersionOk=="boolean"?e.nodeVersionOk:null,nodeVersion:typeof e.nodeVersion=="string"?e.nodeVersion:void 0,auggieInstalled:typeof e.auggieInstalled=="boolean"?e.auggieInstalled:!1,binaryInstallAvailable:typeof e.binaryInstallAvailable=="boolean"?e.binaryInstallAvailable:!1}}catch{return{nodeVersionOk:null,nodeVersion:void 0,auggieInstalled:!1,binaryInstallAvailable:!1}}}async releaseNotes(){return null}async autoUpdate(){try{return{...await Cc.getState(),toastVisible:!1,downloadedToastDismissedAt:null}}catch{return null}}subscribe(e){return this.status().then(t=>e(t)),()=>{}}}class Kr{constructor(e=!1){this.localMachine=e}async pairingInfo(){const e=await u("server.pairingInfo",void 0,this.localMachine?{localMachine:!0}:void 0);if(typeof e?.token!="string"||typeof e?.certFingerprint!="string"||typeof e?.path!="string"||!Array.isArray(e?.localIps)||typeof e?.hostname!="string")throw new Error("Invalid server.pairingInfo response shape");return{token:e.token,certFingerprint:e.certFingerprint,port:e.port??null,path:e.path,localIps:e.localIps,hostname:e.hostname,...typeof e.tcAddress=="string"&&e.tcAddress.length>0?{tcAddress:e.tcAddress}:{},...Array.isArray(e.availableIps)?{availableIps:e.availableIps}:{}}}async rotateToken(){const e=await u("server.rotateToken",void 0,this.localMachine?{localMachine:!0}:void 0);if(typeof e?.token!="string")throw new Error("Invalid server.rotateToken response shape");return{token:e.token}}}function _c(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.enabled=="boolean"&&typeof e.relayUrl=="string"&&(e.daemonId===null||typeof e.daemonId=="string")&&typeof e.linked=="boolean"&&(e.linkedDevices===null||typeof e.linkedDevices=="number")&&typeof e.publishing=="boolean"}class Mc{async status(){let e;try{e=await u("push.status")}catch(c){if(c instanceof Yt&&(c.rpcCode===-32601||c.code==="METHOD_NOT_FOUND"))return null;throw c}if(!_c(e))throw new Error("Invalid push.status response shape");const{enabled:t,relayUrl:r,daemonId:s,linked:o,linkedDevices:i,publishing:a}=e;return{enabled:t,relayUrl:r,daemonId:s,linked:o,linkedDevices:i,publishing:a}}}const Pc=Ne("LiveTasksClient");function Ut(n,e){if(!(!Array.isArray(e)||e.length===0)){if(!e.every(t=>typeof t=="string")){Pc.warn(`discarding malformed ${n}: expected string[], got non-string member`,{value:e});return}return e}}function Jr(n){const e=Ut("dependsOn",n.dependsOn),t=Ut("conflictsWith",n.conflictsWith),r=Ut("unmetDependsOn",n.unmetDependsOn);return{...e?{dependsOn:e}:{},...t?{conflictsWith:t}:{},...r?{unmetDependsOn:r}:{}}}function Yr(n){return typeof n.specLinked=="boolean"?{specLinked:n.specLinked}:{}}function nn(n){const t=n.metadata?.task;return t?{id:String(n.id??""),title:String(n.title??""),status:typeof t.status=="string"?t.status:"not_started",updatedAt:typeof n.updatedAt=="string"?n.updatedAt:typeof n.updated_at=="string"?n.updated_at:void 0,...typeof n.rev=="number"?{rev:n.rev}:{},...Jr(t),...Yr(t)}:null}function Gn(n){const e=nn(n);return e||(typeof n.status!="string"?null:{id:String(n.id??""),title:String(n.title??""),status:n.status,updatedAt:typeof n.updatedAt=="string"?n.updatedAt:typeof n.updated_at=="string"?n.updated_at:void 0,...typeof n.rev=="number"?{rev:n.rev}:{},...Jr(n),...Yr(n)})}function Oc(n){const e=nn(n);return e||(typeof n.status=="string"?{id:String(n.id??""),title:String(n.title??""),status:n.status,...typeof n.updatedAt=="string"?{updatedAt:n.updatedAt}:{},...typeof n.rev=="number"?{rev:n.rev}:{}}:null)}const xc={total:0,completed:0,inProgress:0};function Hn(n){if(!n||typeof n!="object")return null;const e=n,t=e.noteId,r=e.taskKey,s=e.taskText,o=e.agentId,i=e.createdAt;return typeof t!="string"||typeof r!="string"||typeof s!="string"||typeof o!="string"||typeof i!="number"?null:{noteId:t,taskKey:r,taskText:s,agentId:o,createdAt:i}}function Nc(n){if(!n||typeof n!="object")return{...xc};const e=n;return{total:typeof e.total=="number"?e.total:0,completed:typeof e.completed=="number"?e.completed:0,inProgress:typeof e.inProgress=="number"?e.inProgress:0}}class Bc{async list(e){const t=await u("task.list",{workspaceId:e}),r=Array.isArray(t?.tasks)?t.tasks:[],s=[];for(const o of r){const i=Gn(o);i&&(i.id&&He(i.id,e),s.push(i))}return{tasks:s,stats:Nc(t?.stats)}}async get(e){const t=await ie(e);if(!t)return null;try{const r=await Sr(o=>u("note.get",o),{workspaceId:t,noteId:e}),s=r&&typeof r=="object"&&"note"in r?r.note:r;return!s||typeof s!="object"?null:nn(s)}catch{return null}}async updateStatus(e,t,r,s){return this.runTaskMutation(e,"task.updateStatus",{taskText:t,status:r},s)}async update(e,t,r,s){return this.runTaskMutation(e,"task.update",{line:t,...r.text!==void 0?{text:r.text}:{},...r.status!==void 0?{status:r.status}:{},...r.expected!==void 0?{expected:r.expected}:{}},s)}async updateNoteStatus(e,t,r){return this.runTaskMutation(e,"task.updateNoteStatus",{status:t},r)}async markAsTask(e,t,r,s){return this.runTaskMutation(e,"task.markAsTask",{status:t,...r?.acceptanceCriteria!==void 0?{acceptanceCriteria:r.acceptanceCriteria}:{},...r?.effort!==void 0?{effort:r.effort}:{},...r?.dependsOn!==void 0?{dependsOn:r.dependsOn}:{},...r?.conflictsWith!==void 0?{conflictsWith:r.conflictsWith}:{}},s)}async setRelations(e,t){return this.runTaskMutation(e,"task.setRelations",{...t.dependsOn!==void 0?{dependsOn:t.dependsOn}:{},...t.conflictsWith!==void 0?{conflictsWith:t.conflictsWith}:{}})}async assignAgent(e,t,r){return this.runTaskMutation(e,"task.assignAgent",{agentId:t},r)}async createPrerequisite(e,t,r){const s=await ie(e);return s?Wt("task.createPrerequisite",{workspaceId:s,dependentNoteId:e,title:t,...r?.content!==void 0?{content:r.content}:{},...r?.status!==void 0?{status:r.status}:{},idempotencyKey:Q()}):{success:!1,error:`Cannot resolve workspace for note ${e}`}}async listAgentLinks(e){const r=(await u("task.listAgentLinks",{workspaceId:e}))?.linksByNoteId;if(!r||typeof r!="object")return{};const s={};for(const[o,i]of Object.entries(r)){if(!i||typeof i!="object")continue;const a={};for(const[c,l]of Object.entries(i)){const d=Hn(l);d&&(a[c]=d)}Object.keys(a).length>0&&(s[o]=a)}return s}async linkAgent(e,t,r){const s=await u("task.linkAgent",{workspaceId:e,noteId:t,taskText:r.taskText,agentId:r.agentId,...r.taskKey!==void 0?{taskKey:r.taskKey}:{}}),o=Hn(s?.link);return o||{...r,noteId:t}}async unlinkAgent(e,t,r){return(await u("task.unlinkAgent",{workspaceId:e,noteId:t,taskKey:r}))?.removed===!0}async runTaskMutation(e,t,r,s){const o=await ie(e);if(!o)return{success:!1,error:`Cannot resolve workspace for note ${e}`};const i=await Wt(t,{workspaceId:o,noteId:e,...r,...s!==void 0?{expectedVersion:s}:{}}),a=i.conflict?.current;if(a&&typeof a=="object"){const c=Oc(a);if(c)return{...i,conflict:{current:c}}}return i}subscribe(e){return Je({channel:{subscribeMethod:"task.subscribe",unsubscribeMethod:"task.unsubscribe",dynamic:{subscribeIds:en,paramsForId:t=>({workspaceId:t})},continuation:{method:"task.list",key:"tasks",params:t=>({workspaceId:t.workspaceId})}},getId:t=>String(t.id??""),normalize:t=>{const r=Gn(t);return r?.id&&typeof t.workspaceId=="string"&&t.workspaceId&&He(r.id,t.workspaceId),r},handler:e})}}function Lc(n){const e=new TextEncoder().encode(n);let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Vn(n){if(typeof n!="string"||n.length===0)return"";try{const e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return new TextDecoder().decode(t)}catch{return""}}function jc(n,e){if(!n||typeof n!="object")return null;const t=n,r=String(t.terminalId??t.id??"");if(!r)return null;const s=typeof t.workspaceId=="string"?t.workspaceId:e;return{id:r,name:typeof t.name=="string"?t.name:"",workspaceId:s,createdAt:typeof t.createdAt=="string"?t.createdAt:void 0,isConnected:!0,...typeof t.isExecutingCommand=="boolean"?{isExecuting:t.isExecutingCommand}:{}}}function Dc(n){if(!n||typeof n!="object")return null;const e=n;return e.event&&typeof e.event=="object"?e.event:typeof e.type=="string"?e:null}function Uc(n){if(!n||typeof n!="object")return;const e=n.subscriptionId;return typeof e=="string"?e:void 0}class qc{async list(e){const t=await u("terminal.list",{workspaceId:e}),r=Array.isArray(t),s=r?t:Array.isArray(t?.terminals)?t.terminals:[],o=!r&&typeof t?.daemonBootId=="string"?t.daemonBootId:void 0,i=[];for(const a of s){const c=jc(a,e);c&&i.push(c)}return{terminals:i,...o!==void 0?{daemonBootId:o}:{}}}async create(e){try{const t=await u("terminal.create",{workspaceId:e.workspaceId,cols:e.cols,rows:e.rows,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.command!==void 0?{command:e.command}:{},...e.env!==void 0?{env:e.env}:{}}),r=typeof t?.terminalId=="string"?t.terminalId:void 0;return r?{success:!0,id:r}:{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async write(e,t,r){return b("terminal.write",{terminalId:e,data:Lc(t),...r!==void 0?{workspaceId:r}:{}})}async resize(e,t,r,s){return b("terminal.resize",{terminalId:e,cols:t,rows:r,...s!==void 0?{workspaceId:s}:{}})}async kill(e,t){return b("terminal.kill",{terminalId:e,...t!==void 0?{workspaceId:t}:{}})}async getBuffer(e,t,r){try{const s=await u("terminal.getBuffer",{terminalId:e,...r!==void 0?{workspaceId:r}:{},...t!==void 0?{maxBytes:t}:{}});return Vn(s?.data)}catch{return""}}async output(e,t){try{const r=await u("terminal.readOutput",{workspaceId:e,terminalId:t});if(typeof r=="string")return r;const s=r?.output;return typeof s=="string"?s:""}catch{return""}}subscribeEvents(e,t,r){let s=!1,o=0,i;const a=ae(d=>{if(d.method!=="events.event")return;const m=Uc(d.params);if(i===void 0||m!==i)return;const I=Dc(d.params);if(!I||typeof I.type!="string"||!I.type.startsWith("terminal:"))return;const S=I.data??{};if(S.terminalId===e)switch(I.type){case"terminal:data":t.onData?.({terminalId:e,chunk:Vn(S.chunk)});break;case"terminal:exit":t.onExit?.({terminalId:e,exitCode:typeof S.exitCode=="number"?S.exitCode:0});break;case"terminal:cwd":typeof S.cwd=="string"&&t.onCwd?.({terminalId:e,cwd:S.cwd});break;case"terminal:title":typeof S.title=="string"&&t.onTitle?.({terminalId:e,title:S.title});break}}),c=()=>{const d=++o;return Jt({eventTypes:["terminal:data","terminal:exit","terminal:cwd","terminal:title"],...r!==void 0?{workspaceId:r}:{}}).then(m=>{const I=m?.subscriptionId;if(s||d!==o){I&&Oe(I,r);return}i=I}).catch(()=>{})};c();const l=ce(()=>{i=void 0,c()});return()=>{s=!0,a(),l(),i&&Oe(i,r)}}subscribe(e){return e([]),()=>{}}}function Fc(n=qs){return{async begin(e,t,r){const s=Fs.parse(e),o=$s.parse(t);if(te(s.root)!==te(o.review.root))throw new Error("NATIVE_REVIEW_UNAVAILABLE");const i=await n(o);if(te(i.preview.root)!==te(s.root))throw await i.release(),new Error("NATIVE_REVIEW_UNAVAILABLE");let a;try{a=i.onRetired(r)}catch(d){throw await i.release(),d}let c=!1,l;return{...o.review.companion&&i.prepareCompanion?{prepareCompanion(){return l||(l=Promise.resolve().then(async()=>{if(c)throw new Error("NATIVE_REVIEW_UNAVAILABLE");const d=await i.prepareCompanion();if(c||te(d.preview.root)!==te(s.root))throw await d.release(),new Error("NATIVE_REVIEW_UNAVAILABLE");return d}),l)}}:{},preview:i.preview,onRetired:i.onRetired,confirm:i.confirm,reconcile:i.reconcile,async release(){c||(c=!0,a(),l?.then(d=>d.release(),()=>{}),await i.release())}}}}}const $c=Be({root:Ws,editId:P().min(1),admission:P().nullable()}).strict();function Wc(n=Gs){return{async begin(e,t){const r=$c.parse(e),s=await n(r.root);if(te(s.preview.root)!==te(r.root))throw await s.release(),new Error("REPOSITORY_SELECTION_UNAVAILABLE");const o=s.onRetired(t);let i=!1;return{preview:s.preview,onRetired:s.onRetired,confirm:s.confirm,reconcile:s.reconcile,async release(){i||(i=!0,o(),await s.release())}}}}}function Gc(n=Hs){return{async observe(e,t){const r=Object.freeze({...e});let s=!0,o,i;const a=()=>{s&&(s=!1,i?.(),o?.release())},c=()=>{if(s)try{t({type:"unavailable",request:r})}finally{a()}};return(async()=>{if(o=await n(r.gitRootId===void 0?{workspaceId:r.workspaceId,kind:"primary"}:{workspaceId:r.workspaceId,kind:"registered",gitRootId:r.gitRootId}),!s){await o.release();return}if(i=o.onRetired(()=>{if(s)try{t({type:"retired",request:r})}finally{a()}}),!s){i();return}const l=await o.request("workspace.repositoryContext",{workspaceId:r.workspaceId,...r.gitRootId===void 0?{}:{gitRootId:r.gitRootId}});if(!s)return;if(!l.current){try{t({type:"retired",request:r})}finally{a()}return}if(l.settlement.status!=="fulfilled"){c();return}const d=no.parse(l.settlement.value);if(!ro(d,r)){c();return}t({type:"received",response:{request:r,context:d}})})().catch(c),a}}}const Hc="base-refresh-failed",Vc=["auth-required","ssh-host-key","network","timeout","repo-not-found","access-denied","other"];function tt(n){return typeof n=="string"?n:""}function zc(n){if(!n||typeof n!="object")return;const e=n;return e.code!==Hc?void 0:{category:Vc.includes(tt(e.category))?e.category:"other",detail:tt(e.detail),baseRef:tt(e.baseRef),remote:tt(e.remote)}}const Kc=Be({homeId:P().min(1),nodeId:P().min(1).optional(),cloudMachineId:P().min(1).optional(),name:P(),state:P().min(1),since:P(),lastBackupAt:P().optional(),backupWarning:so().optional(),setup:Xs.optional().catch(void 0)});function Zr(n){const e=Kc.safeParse(n);return e.success?e.data:void 0}const Jc=Be({amount:ne().finite(),currency:P().min(1)}).passthrough(),ct=Be({inputTokens:ne().int().nonnegative(),outputTokens:ne().int().nonnegative(),cacheReadTokens:ne().int().nonnegative(),cacheCreationTokens:ne().int().nonnegative(),thoughtTokens:ne().int().nonnegative().optional(),cost:Jc.optional()}).passthrough(),Yc=Be({agentId:P().min(1),model:P().min(1),totals:ct,humanMessages:ne().int().nonnegative(),agentMessages:ne().int().nonnegative()}).passthrough(),zn=new TextEncoder;function Kn(n,e){const t=zn.encode(n),r=zn.encode(e);for(let s=0;s<Math.min(t.length,r.length);s++)if(t[s]!==r[s])return t[s]-r[s];return t.length-r.length}const Zc=oo(Yc).superRefine((n,e)=>{for(const[t,r]of n.entries()){const s=n[t-1];s!==void 0&&(Kn(r.agentId,s.agentId)||Kn(r.model,s.model))<=0&&e.addIssue({code:io.custom,message:"byAgentModel rows must be unique and sorted by agentId, then model",path:[t]})}}),Qr=Be({byAgentId:Tt(P(),ct),totals:ct,byModel:Tt(P(),ct),byAgentModel:Zc.optional(),agentNames:Tt(P(),P()).optional(),lastScanAt:eo({offset:!0}).nullable()}).passthrough();function Qc(n){return Qr.parse(n)}function ll(n){const e=Qr.safeParse(n);return e.success?e.data:null}const Xc=Ne("LiveWorkspacesClient"),eu=12e4,tu=3e5;function nu(n){switch(String(n).toLowerCase()){case"inactive":return De.Inactive;case"archived":return De.Archived;case"retired":return De.Retired;case"deleted":return De.Deleted;default:return De.Active}}function we(n){const e=new Date().toISOString(),t=String(n.id??n.workspaceId??""),{defaultAgentPlacement:r,home:s,...o}=n,i=Zr(s);return s!==void 0&&!i&&Xc.warn("workspace row carried a home outside the contract",{workspaceId:t}),{...o,...r===void 0?{}:{defaultAgentPlacement:to.parse(r)},...i?{home:i}:{},id:dr(t),title:String(n.title??n.name??t),branch:String(n.branch??""),status:nu(n.status),changesets:Array.isArray(n.changesets)?n.changesets:[],timeline:Array.isArray(n.timeline)?n.timeline:[],conversationInfo:Array.isArray(n.conversationInfo)?n.conversationInfo:[],createdAt:String(n.createdAt??e),updatedAt:String(n.updatedAt??e)}}function Jn(n){if(!n||typeof n!="object")return;const e=n.data;if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"&&t.length>0?t:void 0}function ru(n){if(!n||typeof n!="object")return;const e=n.data;if(!e||typeof e!="object")return;const t=e;if(t.code!=="launch-failed"||typeof t.workspaceId!="string"||t.workspaceId.length===0)return;const r=t.launch?.agentId,s=t.cause?.message;return{workspaceId:t.workspaceId,...typeof r=="string"&&r.length>0?{agentId:r}:{},...typeof s=="string"&&s.length>0?{cause:s}:{}}}function Yn(n){if(!n||typeof n!="object")return!1;const e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.type=="string"&&e.type.length>0}function Zn(n,e){if(!Oi(n))throw new Error(`Invalid ${e} response shape`);return n}function su(n){if(n===null||typeof n!="object")return!1;const e=n;return typeof e.id=="string"&&e.id.length>0&&typeof e.title=="string"&&typeof e.archived=="boolean"&&typeof e.linkedAt=="string"}const ou=["applied","dismissed","notResolved"];function iu(n){if(!n||typeof n!="object")return;const{proposalId:e,outcome:t}=n;if(!(typeof e!="string"||typeof t!="string")&&ou.includes(t))return{proposalId:e,outcome:t}}class au{constructor(){y(this,"listRequests",new Map);y(this,"getRequests",new Map)}beginNativeReview(e,t,r){return Fc().begin(e,t,r)}beginRepositorySelectionEdit(e,t){return Wc().begin(e,t)}observeRepositoryContext(e,t){return Gc().observe(e,t)}list(e){const t=e?.includeArchived===!0,r=e?.includeRetired===!0,s=`${t}:${r}`,o=r?void 0:this.listRequests.get(s);if(o)return o;const i={...t?{includeArchived:!0}:{},...r?{includeRetired:!0}:{}},a=ut(l=>u("workspace.list",l),i,"workspaces").then(l=>(Array.isArray(l?.workspaces)?l.workspaces:[]).map(m=>we(m)));if(r)return a;this.listRequests.set(s,a);const c=()=>{this.listRequests.get(s)===a&&this.listRequests.delete(s)};return a.then(c,c),a}get(e){const t=this.getRequests.get(e);if(t)return t;const r=u("workspace.get",{workspaceId:e}).then(o=>{const i=o&&typeof o=="object"&&"workspace"in o?o.workspace:o;return!i||typeof i!="object"?null:we(i)});this.getRequests.set(e,r);const s=()=>{this.getRequests.get(e)===r&&this.getRequests.delete(e)};return r.then(s,s),r}async open(e){return this.get(e)}async create(e){try{const t=await u("workspace.create",{...e,idempotencyKey:e.idempotencyKey??Q()},{timeoutMs:tu}),r=t?.workspace,s=t?.initialAgent,o=iu(t?.proposalOrigin);let i;if(s!=null){if(typeof s!="object"||typeof s.id!="string"||s.id.length===0)return{success:!1,error:"workspace.create returned an initialAgent without a valid daemon-assigned id"};i=s}return r&&typeof r=="object"?{success:!0,workspace:we(r),...i?{initialAgent:i}:{},...o?{proposalOrigin:o}:{}}:{success:!0}}catch(t){const r=_(t),s=lt(t);if(s)return{success:!1,error:r,conflict:s};const o=Jn(t),i=ru(t),a=zc(t?.data);return o?{success:!1,error:r,errorCode:o,...i?{launchFailure:i}:{},...a?{baseRefreshFailure:a}:{}}:{success:!1,error:r}}}async update(e){const{id:t,...r}=e;try{const o=(await u("workspace.update",{workspaceId:t,...r}))?.workspace;return o&&typeof o=="object"?{success:!0,workspace:we(o)}:{success:!0}}catch(s){const o=s instanceof Error?s.message:String(s),i=lt(s);return i?{success:!1,error:o,conflict:i}:{success:!1,error:o}}}async delete(e,t){const r=t?.undoDelayMs;try{const s=await u("workspace.delete",r&&r>0?{workspaceId:e,undoDelayMs:r}:{workspaceId:e},{timeoutMs:eu}),o=s?.scheduled===!0,i=typeof s?.deleteAt=="string"?s.deleteAt:void 0;return o&&i?{success:!0,scheduled:!0,deleteAt:i}:{success:!0}}catch(s){return{success:!1,error:_(s)}}}async findByPullRequest(e){const r=(await u("workspace.findByPullRequest",{url:e}))?.workspaces;if(!Array.isArray(r)||!r.every(su))throw new Error("Invalid workspace.findByPullRequest response shape");return r}async cancelDelete(e){try{return{success:!0,cancelled:(await u("workspace.cancelDelete",{workspaceId:e}))?.cancelled===!0}}catch(t){return{success:!1,error:_(t)}}}async archive(e){return b("workspace.archive",{workspaceId:e})}async unarchive(e){return b("workspace.unarchive",{workspaceId:e})}async retire(e){try{const r=(await u("workspace.retire",{workspaceId:e}))?.workspace;return{success:!0,...r&&typeof r=="object"?{workspace:we(r)}:{}}}catch(t){const r=Jn(t);return{success:!1,error:_(t),...r?{errorCode:r}:{}}}}async markSeen(e){return b("workspace.markSeen",{workspaceId:e})}async setActive(e){return b("workspace.setActive",{workspaceId:e})}async recentViews(){return{}}async getTokenUsage(e){const r=(await u("workspace.getTokenUsage",{workspaceId:e}))?.tokenUsage;return r&&typeof r=="object"?Qc(r):null}async diskUsage(e){try{const t=await u("workspace.diskUsage",{workspaceId:e}),r=t?.diskUsage,s={refreshing:t?.refreshing===!0};return r&&typeof r=="object"&&(s.diskUsage=r),s}catch(t){if(t instanceof Yt&&(t.rpcCode===-32601||t.code==="METHOD_NOT_FOUND"))return null;throw t}}async getContext(e){const t=await u("workspace.getContext",{workspaceId:e});return(Array.isArray(t?.items)?t.items:[]).filter(Yn)}async updateContext(e,t){const r=await u("workspace.updateContext",{workspaceId:e,items:t});return(Array.isArray(r?.items)?r.items:[]).filter(Yn)}async getBrowserClient(e){const t=await u("workspace.getBrowserClient",{workspaceId:e});return Zn(t?.browserClient,"workspace.getBrowserClient")}async setBrowserClient(e,t){const r=await u("workspace.setBrowserClient",{workspaceId:e,clientId:t});return Zn(r?.browserClient,"workspace.setBrowserClient")}async setHome(e,t){const r=await u("workspace.setHome",{workspaceId:e,to:t}),s=Zr(r?.home);if(!s)throw new Error("Invalid workspace.setHome response shape");return s}subscribe(e){return Je({channel:{subscribeMethod:"workspace.subscribe",unsubscribeMethod:"workspace.unsubscribe",continuation:{method:"workspace.list",key:"workspaces",params:t=>({includeArchived:!0,...t.includeRetired===!0?{includeRetired:!0}:{}})}},getId:t=>String(t.id??t.workspaceId??""),normalize:t=>we(t),handler:e})}}class Xr{constructor(){y(this,"workspaces",new au);y(this,"agents",new Ci);y(this,"notes",new Za);y(this,"tasks",new Bc);y(this,"comments",new ca);y(this,"git",new ja);y(this,"files",new wa);y(this,"terminals",new qc);y(this,"settings",new fc);y(this,"specialists",new kc);y(this,"integrations",new qa);y(this,"scripts",new ec);y(this,"setupScripts",new gc);y(this,"events",new da);y(this,"models",new Ha);y(this,"providers",new Qa);y(this,"stats",new Ic);y(this,"voice",new Tc);y(this,"chat",new ta);y(this,"skills",new mc);y(this,"browser",new Bi);y(this,"system",new Rc);y(this,"server",new Kr);y(this,"push",new Mc);y(this,"drafts",new ua);y(this,"clients",new na)}}const nt={FileChanged:"file:changed",AgentIdle:"agent:idle",NoteUpdated:"note:updated",TaskStatusChanged:"task:status-changed"},pt="2026-01-01T00:00:00.000Z",O=dr("ws-mock-1"),cu=Ns("00000000-0000-4000-8000-000000000010"),es=`terminal-${O}-default`,ts=`terminal-${O}-2`,Qn=[{id:es,name:"Terminal",type:"terminal",workspaceId:String(O),createdAt:pt},{id:ts,name:"Terminal 2",type:"terminal",workspaceId:String(O),createdAt:pt}],Xn={[es]:`$ pnpm run dev\r
2
2
  \x1B[32m➜\x1B[0m Local: http://localhost:5173/\r
3
3
  $ `,[ts]:`$ git status\r
4
4
  On branch feat/dark-mode-toggle\r