@inkeep/open-knowledge 0.47.0-beta.26 → 0.47.0-beta.27

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 (414) hide show
  1. package/dist/{abnfDiagram-VRR7QNED-C01LwnLj.mjs → abnfDiagram-VRR7QNED-DQjgDcgA.mjs} +2 -2
  2. package/dist/{acp-harness-probe-BTT3QZDW.mjs → acp-harness-probe-DmKLHS8w.mjs} +3 -3
  3. package/dist/alias-JE7RI5QX-BfILuEvo.mjs +1 -0
  4. package/dist/{arc-CYbidMQb.mjs → arc-CO8jsQkL.mjs} +2 -2
  5. package/dist/architecture-TIHT7OUA-CScIhnar.mjs +1 -0
  6. package/dist/{architectureDiagram-ZJ3FMSHR-54tD72To.mjs → architectureDiagram-ZJ3FMSHR-CkUIG8wd.mjs} +2 -2
  7. package/dist/{array-BqQze_vE.mjs → array-Cerc_8W3.mjs} +1 -1
  8. package/dist/{awk2-BBAGSFUB-C0jQbtG6.mjs → awk2-BBAGSFUB-BH8WxyhW.mjs} +1 -1
  9. package/dist/{banner--DGfdMN8.mjs → banner-CIK2GwPx.mjs} +1 -1
  10. package/dist/{base64-4YMZCVJ5-E_RwmVUf.mjs → base64-4YMZCVJ5-CDuRvFBG.mjs} +1 -1
  11. package/dist/{basename-AA2KJYZQ-Dq2O0Dr6.mjs → basename-AA2KJYZQ-sv8gJZXS.mjs} +1 -1
  12. package/dist/bash-IJWYRKFO-DKUaUgF9.mjs +1 -0
  13. package/dist/{blockDiagram-677ZJIJ3-BFWl-x5e.mjs → blockDiagram-677ZJIJ3-sLhYyPCr.mjs} +2 -2
  14. package/dist/{c4Diagram-LMCZKHZV-BkY5gq8X.mjs → c4Diagram-LMCZKHZV-Cg6dfUXU.mjs} +2 -2
  15. package/dist/{cat-RDUMLXKC-C3vpYzfr.mjs → cat-RDUMLXKC-BtNo16C3.mjs} +1 -1
  16. package/dist/channel-DRk0OEK0.mjs +2 -0
  17. package/dist/{chmod-SYMGL4JA-BzT6KWst.mjs → chmod-SYMGL4JA-B15Xlp42.mjs} +1 -1
  18. package/dist/{chokidar-BCS--vwu.mjs → chokidar-CVNrjmRM.mjs} +1 -1
  19. package/dist/{chunk-2Q5K7J3B-BBA6_zq_.mjs → chunk-2Q5K7J3B-2Es1K_NO.mjs} +2 -2
  20. package/dist/{chunk-2TRDZQLB-C_2g1dOd.mjs → chunk-2TRDZQLB-G1LvPXqq.mjs} +1 -1
  21. package/dist/{chunk-32BRIVSS-Bsc-9o_O.mjs → chunk-32BRIVSS-ok2xg0Je.mjs} +2 -2
  22. package/dist/{chunk-3BS5SKQH-nmqNxSIe.mjs → chunk-3BS5SKQH-CFcrGLDG.mjs} +3 -3
  23. package/dist/{chunk-3H6UQG3A-DLwP7IGN.mjs → chunk-3H6UQG3A-Dx5ykWR0.mjs} +2 -2
  24. package/dist/{chunk-3ZUFRYJ4-DX32azSC.mjs → chunk-3ZUFRYJ4-DzbWfyzV.mjs} +1 -1
  25. package/dist/{chunk-4GTNDTRF-BT6SNd8s.mjs → chunk-4GTNDTRF-COTPYeV6.mjs} +2 -2
  26. package/dist/{chunk-4HHKTUW3-CL0rAYDo.mjs → chunk-4HHKTUW3-BkuKGebe.mjs} +1 -1
  27. package/dist/{chunk-4Q4SM6WR-Cf1guB-L.mjs → chunk-4Q4SM6WR-i8tiQRv3.mjs} +2 -2
  28. package/dist/{chunk-52WLFC77-D0ICJuoG.mjs → chunk-52WLFC77-BaT5_S-q.mjs} +2 -2
  29. package/dist/{chunk-55VFSPNA-B2P94_nY.mjs → chunk-55VFSPNA-Ct9maI6O.mjs} +2 -2
  30. package/dist/{chunk-5FCAYU7R-DamFELXo.mjs → chunk-5FCAYU7R-of7BBDNL.mjs} +2 -2
  31. package/dist/{chunk-5HE753X5-CK-MLDEN.mjs → chunk-5HE753X5-9kILZ5Nr.mjs} +2 -2
  32. package/dist/{chunk-5JV3BV7I-XXAgMX9r.mjs → chunk-5JV3BV7I-BKVVlFxh.mjs} +2 -2
  33. package/dist/{chunk-5QVNJEHU-0Om-Hby0.mjs → chunk-5QVNJEHU-CvZ-NmqQ.mjs} +2 -2
  34. package/dist/{chunk-5TONJI2A-Du5dq0Ys.mjs → chunk-5TONJI2A-CGHpmUrS.mjs} +2 -2
  35. package/dist/{chunk-5V6VZH6T-D9prksm6.mjs → chunk-5V6VZH6T-DdeqP2TW.mjs} +2 -2
  36. package/dist/{chunk-5VM5RSS4-B9nF5Lzd.mjs → chunk-5VM5RSS4-COK1ErrI.mjs} +2 -2
  37. package/dist/{chunk-62RKD26F-pjncC7By.mjs → chunk-62RKD26F-RtrcFE7S.mjs} +2 -2
  38. package/dist/{chunk-64BAICW3-2hCf5wU5.mjs → chunk-64BAICW3-0h-yIc1e.mjs} +2 -2
  39. package/dist/{chunk-6Z5SFZXK-eDS7YpbK.mjs → chunk-6Z5SFZXK-C5owNg1o.mjs} +2 -2
  40. package/dist/{chunk-74CEPOFO-D5a5lNJR.mjs → chunk-74CEPOFO--xsxhUFC.mjs} +1 -1
  41. package/dist/{chunk-7BUUIJ7U-CKtuqKC6.mjs → chunk-7BUUIJ7U-_1oXd84C.mjs} +2 -2
  42. package/dist/{chunk-7L36YK2X-L3jD5RT-.mjs → chunk-7L36YK2X-VlH7dlrD.mjs} +1 -1
  43. package/dist/{chunk-7TSDKFEO-Csacasvr.mjs → chunk-7TSDKFEO-BjOrsK6M.mjs} +1 -1
  44. package/dist/{chunk-A4HU7SVR-B6M8dLIA.mjs → chunk-A4HU7SVR-oMNSpej4.mjs} +1 -1
  45. package/dist/{chunk-A4JSPFCI-CcbmCyG6.mjs → chunk-A4JSPFCI-DtnWqT5O.mjs} +2 -2
  46. package/dist/{chunk-A65PWWJC-D_GAtJYb.mjs → chunk-A65PWWJC-LctFeUxK.mjs} +2 -2
  47. package/dist/{chunk-A7A2DBEE-D1HWRTG-.mjs → chunk-A7A2DBEE-DuuhuGG1.mjs} +1 -1
  48. package/dist/{chunk-A7ICOL4V-C8N1DqNa.mjs → chunk-A7ICOL4V-CzYDHdxM.mjs} +2 -2
  49. package/dist/{chunk-ALLTKNUZ-AOz3zDg8.mjs → chunk-ALLTKNUZ-BnLIZXEI.mjs} +2 -2
  50. package/dist/{chunk-APT7OOP2-e8HVVYt4.mjs → chunk-APT7OOP2-DESh647P.mjs} +2 -2
  51. package/dist/{chunk-BIQX33UG-CLYGAgEl.mjs → chunk-BIQX33UG-BVtPexox.mjs} +2 -2
  52. package/dist/{chunk-C7G6YPKG-6PzAyV0E.mjs → chunk-C7G6YPKG-DpNJWc2e.mjs} +2 -2
  53. package/dist/{chunk-CQNSW5MT-C4GcKMFe.mjs → chunk-CQNSW5MT-B6mAd0WS.mjs} +2 -2
  54. package/dist/{chunk-CYSBUYHQ-Bg8p94kN.mjs → chunk-CYSBUYHQ-CTWbbsmm.mjs} +2 -2
  55. package/dist/{chunk-D4J545R4-DstPCHY3.mjs → chunk-D4J545R4-Dy3lcp_X.mjs} +2 -2
  56. package/dist/{chunk-D6CWQ5DW-B-mbMqx1.mjs → chunk-D6CWQ5DW-Dl4tJcwX.mjs} +2 -2
  57. package/dist/{chunk-D7MEQ3VN-L5KTglFl.mjs → chunk-D7MEQ3VN-B-Qyxyo5.mjs} +2 -2
  58. package/dist/{chunk-DBKNVD4L-TDavYUFP.mjs → chunk-DBKNVD4L-Y2Mnp5lC.mjs} +2 -2
  59. package/dist/{chunk-DCAAORBQ-CVYtUSXu.mjs → chunk-DCAAORBQ-BxtVrSMT.mjs} +2 -2
  60. package/dist/{chunk-EEXR5ZDP-DKmcp163.mjs → chunk-EEXR5ZDP-BcjEP2wd.mjs} +1 -1
  61. package/dist/{chunk-EIZGF4BS-CF3xXFmY.mjs → chunk-EIZGF4BS-DYiqM1Ss.mjs} +2 -2
  62. package/dist/{chunk-EMLP6XTP-DOWW1yTB.mjs → chunk-EMLP6XTP-AFimKO17.mjs} +2 -2
  63. package/dist/{chunk-EX3LRPZG-Bk8s0J-D.mjs → chunk-EX3LRPZG-BYcqQlY8.mjs} +2 -2
  64. package/dist/{chunk-F23WWYKW-B1-WhWYU.mjs → chunk-F23WWYKW-BuCITNd6.mjs} +2 -2
  65. package/dist/{chunk-FWX5IMBZ-BKxaTzwN.mjs → chunk-FWX5IMBZ-BFNo8SGu.mjs} +2 -2
  66. package/dist/{chunk-GCTKCWKD-C-I4uPLP.mjs → chunk-GCTKCWKD-jz3yOk3f.mjs} +1 -1
  67. package/dist/{chunk-GOV5EKKI-DMNNr1LX.mjs → chunk-GOV5EKKI-IRzA9ik3.mjs} +2 -2
  68. package/dist/{chunk-GXVXFKBA-CHoBbpeP.mjs → chunk-GXVXFKBA-CGc4vqMu.mjs} +2 -2
  69. package/dist/{chunk-HDQ56CKY-D4gBGBPX.mjs → chunk-HDQ56CKY-Svz-iz8m.mjs} +2 -2
  70. package/dist/{chunk-HJQJAYMS-DfJokS61.mjs → chunk-HJQJAYMS-SgZmT_QE.mjs} +1 -1
  71. package/dist/{chunk-HJWBQKYG-C34BatAz.mjs → chunk-HJWBQKYG-BqFDM0xp.mjs} +2 -2
  72. package/dist/{chunk-HKLCLINH-DkU4By68.mjs → chunk-HKLCLINH-DKx243zB.mjs} +3 -3
  73. package/dist/{chunk-HL6NGDO2-CX48H9NQ.mjs → chunk-HL6NGDO2-B9GCn41X.mjs} +2 -2
  74. package/dist/{chunk-HOUHSVGY-CM96kWHC.mjs → chunk-HOUHSVGY-Cg_2_CUd.mjs} +2 -2
  75. package/dist/{chunk-HWKDQ44K-DvFquSuN.mjs → chunk-HWKDQ44K-CVxg-h0V.mjs} +2 -2
  76. package/dist/{chunk-I57KEIP3-C-GWJFeH.mjs → chunk-I57KEIP3-FVl4IVXz.mjs} +1 -1
  77. package/dist/{chunk-ICXQ74PX-a_OoZV-J.mjs → chunk-ICXQ74PX-CewdqzeE.mjs} +2 -2
  78. package/dist/{chunk-JG7HCLWE-BL-hOXz_.mjs → chunk-JG7HCLWE-BgiWVzAI.mjs} +2 -2
  79. package/dist/{chunk-JVPRLUMK-KIcPtJsL.mjs → chunk-JVPRLUMK-CH7w4zyh.mjs} +2 -2
  80. package/dist/{chunk-JWPE2WC7-B4cjhMJa.mjs → chunk-JWPE2WC7-cMhWwV9I.mjs} +2 -2
  81. package/dist/{chunk-K6LIBGJA-DifITl-A.mjs → chunk-K6LIBGJA-DI9ZkJey.mjs} +2 -2
  82. package/dist/{chunk-KEIR6QF5-D5fHRjH_.mjs → chunk-KEIR6QF5-BhaMJNB5.mjs} +1 -1
  83. package/dist/{chunk-KMEYNNUA-BulSmamX.mjs → chunk-KMEYNNUA-CabTsa7P.mjs} +2 -2
  84. package/dist/{chunk-KRBPSX3W-DrDWj6yq.mjs → chunk-KRBPSX3W-ciCGjpAL.mjs} +2 -2
  85. package/dist/{chunk-LL3S3NLB-rdnne998.mjs → chunk-LL3S3NLB-r8mDpVuz.mjs} +2 -2
  86. package/dist/{chunk-LTZRCH7N-CcW89saL.mjs → chunk-LTZRCH7N-Cj1hz7m7.mjs} +2 -2
  87. package/dist/{chunk-LWEGUNWT-56p2g4nb.mjs → chunk-LWEGUNWT-C3ON4AHi.mjs} +2 -2
  88. package/dist/{chunk-MDDMCKUK-CL40B1CC.mjs → chunk-MDDMCKUK-D3MZs3FF.mjs} +2 -2
  89. package/dist/{chunk-MDLLFABN-CDjkVtAO.mjs → chunk-MDLLFABN-DgTeOfIY.mjs} +2 -2
  90. package/dist/{chunk-MHTUABJP-D8V0hAkM.mjs → chunk-MHTUABJP-BbSobv_U.mjs} +1 -1
  91. package/dist/{chunk-MIZPJHVH-q38ahMm1.mjs → chunk-MIZPJHVH-CzqfuBdK.mjs} +2 -2
  92. package/dist/{chunk-MLXIYONF-BwLP8wJ5.mjs → chunk-MLXIYONF-BcM04nM_.mjs} +1 -1
  93. package/dist/{chunk-MOJQB5TN-a3t5NDdo.mjs → chunk-MOJQB5TN-CidbQQ7m.mjs} +2 -2
  94. package/dist/{chunk-MOZMSUNE-CxsrZHOL.mjs → chunk-MOZMSUNE-DTiZcqZ1.mjs} +2 -2
  95. package/dist/{chunk-MYE6AGBJ-Dh-4DgDD.mjs → chunk-MYE6AGBJ-B3ukegXT.mjs} +2 -2
  96. package/dist/{chunk-NAERJDUW-BKjqzg55.mjs → chunk-NAERJDUW-CoAYVGR3.mjs} +2 -2
  97. package/dist/{chunk-NCNPKYJZ-D7DW6h8D.mjs → chunk-NCNPKYJZ-C1KcgrGe.mjs} +2 -2
  98. package/dist/{chunk-NUYSJFDK-KW8uL1OU.mjs → chunk-NUYSJFDK-sPbPxu4W.mjs} +2 -2
  99. package/dist/{chunk-OCLXQMOG-DyesF30h.mjs → chunk-OCLXQMOG-BdLZfp3D.mjs} +2 -2
  100. package/dist/{chunk-OCS6LSEM-BuHq4vgI.mjs → chunk-OCS6LSEM-7beNWT9m.mjs} +2 -2
  101. package/dist/{chunk-OGEWGWER-BE748IwJ.mjs → chunk-OGEWGWER-B-Vr80Fa.mjs} +2 -2
  102. package/dist/{chunk-OSBZ3O6U-xu2H_t-I.mjs → chunk-OSBZ3O6U-DwDyo3Ly.mjs} +2 -2
  103. package/dist/{chunk-PBXLG62G-Dt3seCXC.mjs → chunk-PBXLG62G-ww-bn-Tp.mjs} +2 -2
  104. package/dist/{chunk-PP6PSHAB-BoToLAyG.mjs → chunk-PP6PSHAB-xKRHmmOd.mjs} +1 -1
  105. package/dist/{chunk-PUDLZKDR-CgH8fCPb.mjs → chunk-PUDLZKDR-CI0pacGF.mjs} +2 -2
  106. package/dist/{chunk-PXTK5WE2-6yLfmmSs.mjs → chunk-PXTK5WE2-Dfi2FrE5.mjs} +1 -1
  107. package/dist/{chunk-PYSFUGCK-DRdz7MOj.mjs → chunk-PYSFUGCK-BHwvxY2Q.mjs} +2 -2
  108. package/dist/{chunk-Q4XR5HBZ-Dj_gUljr.mjs → chunk-Q4XR5HBZ-4H-m7p0G.mjs} +2 -2
  109. package/dist/{chunk-QBLGF6JB-CZlF3VMT.mjs → chunk-QBLGF6JB-B_tvtCRO.mjs} +2 -2
  110. package/dist/{chunk-QCDB2VPH-BnCQYX4A.mjs → chunk-QCDB2VPH-DHsQu4h6.mjs} +2 -2
  111. package/dist/{chunk-QJ7O6ZN3-IyfDNhDN.mjs → chunk-QJ7O6ZN3-CTKdWbns.mjs} +2 -2
  112. package/dist/{chunk-R6QSAL5T-CK5T9nTq.mjs → chunk-R6QSAL5T-DA60heK6.mjs} +1 -1
  113. package/dist/{chunk-R7FJI6CG-CxRbRaPW.mjs → chunk-R7FJI6CG-BVR1ae7y.mjs} +2 -2
  114. package/dist/{chunk-RPNGRAAP-Dm3Foy2a.mjs → chunk-RPNGRAAP-df7FdhI4.mjs} +2 -2
  115. package/dist/{chunk-RYQCIY6F-DsJ8x3au.mjs → chunk-RYQCIY6F-C8F82Uai.mjs} +2 -2
  116. package/dist/{chunk-SDNKECQQ-eDjS077u.mjs → chunk-SDNKECQQ-BuTL-ot2.mjs} +2 -2
  117. package/dist/{chunk-SNN4IESC-dc9Emx2i.mjs → chunk-SNN4IESC-DVqEOGsL.mjs} +1 -1
  118. package/dist/{chunk-T56QNPHK-DcLcXLAt.mjs → chunk-T56QNPHK-COZC2A_r.mjs} +2 -2
  119. package/dist/{chunk-TLSUDHID-B0bd8ZfM.mjs → chunk-TLSUDHID-DAREQN9J.mjs} +2 -2
  120. package/dist/{chunk-TOMNU26N-CfKJYNUm.mjs → chunk-TOMNU26N-C3JZDC96.mjs} +2 -2
  121. package/dist/{chunk-TP4BZANS-EASixEFX.mjs → chunk-TP4BZANS-C2Z-CHHA.mjs} +2 -2
  122. package/dist/{chunk-TXBZCHCQ-CK2DQwjP.mjs → chunk-TXBZCHCQ-DOaoE5TV.mjs} +2 -2
  123. package/dist/{chunk-U6XO7XAA-ahVBPW6i.mjs → chunk-U6XO7XAA-BpjdcG5R.mjs} +2 -2
  124. package/dist/{chunk-V5MWI2OL-Cd1wUWKd.mjs → chunk-V5MWI2OL-D8SKWVO_.mjs} +1 -1
  125. package/dist/{chunk-V7JOEXUC-Ca3kqXAx.mjs → chunk-V7JOEXUC-CdEIYYNc.mjs} +2 -2
  126. package/dist/{chunk-V7TAPXDL-B4X-oI_G.mjs → chunk-V7TAPXDL-CQbB1mLa.mjs} +2 -2
  127. package/dist/chunk-VAUOI2AC-Ds6ZNp2p.mjs +2 -0
  128. package/dist/{chunk-VJFXDYWH-CYSruK3V.mjs → chunk-VJFXDYWH-C7Lg-Yts.mjs} +2 -2
  129. package/dist/{chunk-VOBGTVA6-D7PSswl5.mjs → chunk-VOBGTVA6-CKl2LR-K.mjs} +2 -2
  130. package/dist/{chunk-VR4S4FIN-DFCLUzSW.mjs → chunk-VR4S4FIN-mH-q10Uq.mjs} +2 -2
  131. package/dist/{chunk-VYOJP4TV-Dv2fFnVt.mjs → chunk-VYOJP4TV-DFxaC5Uc.mjs} +2 -2
  132. package/dist/{chunk-WKFATFPP-Dj6ID3dE.mjs → chunk-WKFATFPP-R7B51gCW.mjs} +2 -2
  133. package/dist/{chunk-WYO6CB5R-CkxB2qiV.mjs → chunk-WYO6CB5R-Cg1RXhAT.mjs} +2 -2
  134. package/dist/{chunk-X2AJGDEF-BAGBpB2e.mjs → chunk-X2AJGDEF-D97qevlv.mjs} +1 -1
  135. package/dist/{chunk-XKQRETAK-BFwrbyC7.mjs → chunk-XKQRETAK-BTmmMuta.mjs} +2 -2
  136. package/dist/{chunk-XKWWSDBF-BTq_A_8q.mjs → chunk-XKWWSDBF-BGzAOrO3.mjs} +2 -2
  137. package/dist/{chunk-XVDPCNWR-BeU4kyoN.mjs → chunk-XVDPCNWR-3ajbQWzU.mjs} +2 -2
  138. package/dist/chunk-XXDRQBXY-BvbdToKZ.mjs +2 -0
  139. package/dist/{chunk-Y2CYZVJY-D-AxePDr.mjs → chunk-Y2CYZVJY-C7FmC3Cl.mjs} +1 -1
  140. package/dist/{chunk-YMMW5UAP-Dk_tcn_t.mjs → chunk-YMMW5UAP-DbBgrudQ.mjs} +2 -2
  141. package/dist/{chunk-YOTPTUD7-BtJLrOsu.mjs → chunk-YOTPTUD7-BSOqhRr-.mjs} +2 -2
  142. package/dist/{chunk-YTNYSM6T-D70kTYmT.mjs → chunk-YTNYSM6T-CoxqCaLl.mjs} +2 -2
  143. package/dist/{chunk-YULBWSET-aTxOIZGk.mjs → chunk-YULBWSET-CuKhTv4j.mjs} +2 -2
  144. package/dist/{chunk-Z6LRHWXI-BGPMNtJW.mjs → chunk-Z6LRHWXI-CujGXDs8.mjs} +1 -1
  145. package/dist/{chunk-Z7JVV2SM-Y0p3CYM_.mjs → chunk-Z7JVV2SM-CiJwkxuY.mjs} +2 -2
  146. package/dist/{chunk-ZGVPDNZ5-DExn7OfJ.mjs → chunk-ZGVPDNZ5-BE_qYP6z.mjs} +2 -2
  147. package/dist/{chunk-ZIRB5QZD-B2znOhor.mjs → chunk-ZIRB5QZD-mhYZnDzb.mjs} +2 -2
  148. package/dist/{chunk-ZZO3UDB3-R3zof8I8.mjs → chunk-ZZO3UDB3-DCkJjNN2.mjs} +2 -2
  149. package/dist/classDiagram-OUVF2IWQ-rKP7gcsT.mjs +2 -0
  150. package/dist/classDiagram-v2-EOCWNBFH-BoWf4tYI.mjs +2 -0
  151. package/dist/{clear-5CZ5X4YR-DiniSeCm.mjs → clear-5CZ5X4YR-BNXs_KRD.mjs} +1 -1
  152. package/dist/cli.mjs +24 -24
  153. package/dist/{column-WLPMMSTS-B1OOeDAs.mjs → column-WLPMMSTS-BrY1gQI1.mjs} +1 -1
  154. package/dist/{comm-5SLSESQG-C4Rjg6X-.mjs → comm-5SLSESQG-aGB098lH.mjs} +1 -1
  155. package/dist/constants-CCTtsxKB.mjs +2 -0
  156. package/dist/{cose-bilkent-JH36ORCC-DwAqPWSx.mjs → cose-bilkent-JH36ORCC-CMfIp4st.mjs} +2 -2
  157. package/dist/{du-WO2ENHXQ-D_erNUzD.mjs → cp-XOYR4ABJ-D0LUaMQT.mjs} +1 -1
  158. package/dist/{curl-47BFPSFW-DtUGPJbr.mjs → curl-47BFPSFW-d1TMPUJw.mjs} +2 -2
  159. package/dist/{cut-OPC3VAGB-Bh_filgx.mjs → cut-OPC3VAGB-FXZX1WQM.mjs} +1 -1
  160. package/dist/cynefin-VYW2F7L2-DtazLHUs.mjs +1 -0
  161. package/dist/{cynefinDiagram-TSTJHNR4-CT6-xML3.mjs → cynefinDiagram-TSTJHNR4-CFbt5v4d.mjs} +2 -2
  162. package/dist/{cytoscape.esm-B3Kjf-Bp.mjs → cytoscape.esm-Dq6ZD9GH.mjs} +1 -1
  163. package/dist/{dagre-CTeiWCGh.mjs → dagre-CbI1Ylqw.mjs} +2 -2
  164. package/dist/{dagre-VKFMJZFB-BGysx5vx.mjs → dagre-VKFMJZFB-BWP36rMX.mjs} +2 -2
  165. package/dist/{head-HT2B6D2J-BkVS3Xmr.mjs → date-DD7FVA2V-7hk1aW9g.mjs} +1 -1
  166. package/dist/{defaultLocale-DPK87u2Z.mjs → defaultLocale-9SlCuWEL.mjs} +1 -1
  167. package/dist/{diagram-FQU43EPY-ZqRG6Q5e.mjs → diagram-FQU43EPY-D2pf7IBH.mjs} +2 -2
  168. package/dist/{diagram-G47NLZAW-DI7dcuHy.mjs → diagram-G47NLZAW-BlOXaBe6.mjs} +2 -2
  169. package/dist/{diagram-NH7WQ7WH-D1oPk0UR.mjs → diagram-NH7WQ7WH-DOwRNWDI.mjs} +2 -2
  170. package/dist/{diagram-OA4YK3LP-Bm3vioHL.mjs → diagram-OA4YK3LP-uyGYHUoX.mjs} +2 -2
  171. package/dist/{diagram-WEI45ONY-Dn8oUVjW.mjs → diagram-WEI45ONY-CmW1X9Kx.mjs} +2 -2
  172. package/dist/diff-HJF2MPDN-bcOaHvDo.mjs +1 -0
  173. package/dist/{dirname-LEMTZZFS-DNEfkSJA.mjs → dirname-LEMTZZFS-RRQ5Ar_Z.mjs} +1 -1
  174. package/dist/{dist-DODzJ7LG.mjs → dist-BmYngy7b.mjs} +1 -1
  175. package/dist/{cp-XOYR4ABJ-sYSLIPgW.mjs → du-WO2ENHXQ-Cg71FvLi.mjs} +1 -1
  176. package/dist/{ebnfDiagram-CCIWWBDH-Cv_KK2i9.mjs → ebnfDiagram-CCIWWBDH-BpBYlrRH.mjs} +2 -2
  177. package/dist/echo-O45JWWI2-BacOdfFs.mjs +1 -0
  178. package/dist/env-5EPCWSXR-T8XCKOX_.mjs +1 -0
  179. package/dist/{erDiagram-Q63AITRT-Bt6lGD8v.mjs → erDiagram-Q63AITRT-ChoKKmxG.mjs} +2 -2
  180. package/dist/eventmodeling-45OFAUF4-BIXp-P6z.mjs +1 -0
  181. package/dist/{execAsync-BUKncp0P.mjs → execAsync-BKp2jujj.mjs} +1 -1
  182. package/dist/{execAsync-DEmazqCE.mjs → execAsync-BuUKdKlz.mjs} +1 -1
  183. package/dist/{expand-DTNXU4LQ-CMN49iyc.mjs → expand-DTNXU4LQ-BD32VJaK.mjs} +1 -1
  184. package/dist/expr-YYCVMXE3-CgQib9F9.mjs +1 -0
  185. package/dist/{date-DD7FVA2V-ByX6dFhf.mjs → file-IGDTDPLG-BAlm5q29.mjs} +1 -1
  186. package/dist/find-DH2ALKQS-z-G7VPmU.mjs +1 -0
  187. package/dist/flag-coverage-6JEX67RU-Cj_NycUm.mjs +2 -0
  188. package/dist/flowDiagram-23GEKE2U-B4VrCGdr.mjs +1 -0
  189. package/dist/{fold-LDSORVYE-CkAvzOUr.mjs → fold-LDSORVYE-CDU-6eOS.mjs} +1 -1
  190. package/dist/{fs-traced-ArlA_yTp.mjs → fs-traced-Cq61rC8q.mjs} +3 -3
  191. package/dist/fs-traced-WMTb98_i.mjs +1 -0
  192. package/dist/{ganttDiagram-NO4QXBWP-DbUuL83g.mjs → ganttDiagram-NO4QXBWP-Cv7sGb-R.mjs} +2 -2
  193. package/dist/{getMachineId-bsd-Ba_eiHKT.mjs → getMachineId-bsd-DtFrm1Uy.mjs} +2 -2
  194. package/dist/{getMachineId-bsd-MpjjBCnQ.mjs → getMachineId-bsd-GFl1-Bje.mjs} +2 -2
  195. package/dist/{getMachineId-darwin-CCowcQE1.mjs → getMachineId-darwin--IR8MP8d.mjs} +2 -2
  196. package/dist/{getMachineId-darwin-CCtDS2VI.mjs → getMachineId-darwin-28jQHa_N.mjs} +2 -2
  197. package/dist/{getMachineId-linux-DMjXicei.mjs → getMachineId-linux-BZgyplQ5.mjs} +1 -1
  198. package/dist/{getMachineId-linux-DdmiwElW.mjs → getMachineId-linux-Bzx3S652.mjs} +1 -1
  199. package/dist/{getMachineId-unsupported-x9lk4Rw9.mjs → getMachineId-unsupported-CyTjujlI.mjs} +1 -1
  200. package/dist/{getMachineId-unsupported-xN2oDqpO.mjs → getMachineId-unsupported-DuB0leRF.mjs} +1 -1
  201. package/dist/{getMachineId-win-DuQfpi_A.mjs → getMachineId-win-BmvAZEMa.mjs} +2 -2
  202. package/dist/{getMachineId-win-mbAJtBuz.mjs → getMachineId-win-CuOFQQ73.mjs} +2 -2
  203. package/dist/gitGraph-TEB2WS4Q-BaTdqV7-.mjs +1 -0
  204. package/dist/{gitGraphDiagram-IHSO6WYX-C-Kq9SCM.mjs → gitGraphDiagram-IHSO6WYX-DxsFHicP.mjs} +2 -2
  205. package/dist/{graphlib-BRVRb9Ce.mjs → graphlib-DKEQBDTz.mjs} +1 -1
  206. package/dist/grep-2HUTXO5U-CsEE08ya.mjs +1 -0
  207. package/dist/gzip-AQXSGOVS-CmMf6H0r.mjs +1 -0
  208. package/dist/{file-IGDTDPLG-CsAmedJu.mjs → head-HT2B6D2J-DSBJixLD.mjs} +1 -1
  209. package/dist/help-VVWX7SA5-BncYWg0B.mjs +1 -0
  210. package/dist/history-J4QRNGRO-CULSDkzp.mjs +1 -0
  211. package/dist/{hostname-BK6HG2DE-TD2KmZjb.mjs → hostname-BK6HG2DE-CaZb-T_R.mjs} +1 -1
  212. package/dist/html-to-markdown-TFCECAGV-CF0t8_d3.mjs +1 -0
  213. package/dist/{index-7O1fNicl.d.mts → index-1MIt1xrM.d.mts} +1 -1
  214. package/dist/index.d.mts +4 -3
  215. package/dist/index.mjs +1 -1
  216. package/dist/info-DKCQHKI2-BxlpeeVn.mjs +1 -0
  217. package/dist/{infoDiagram-FWYZ7A6U-BcXqPzyL.mjs → infoDiagram-FWYZ7A6U-CbPpTq2x.mjs} +2 -2
  218. package/dist/{init-CUut5PRP.mjs → init-B4vStHhv.mjs} +56 -56
  219. package/dist/{init-DotcULIJ.mjs → init-Buw5jj4Q.mjs} +1 -1
  220. package/dist/init-DNKPIF-3.mjs +1 -0
  221. package/dist/{ishikawaDiagram-FXEZZL3T-tlTxPgv8.mjs → ishikawaDiagram-FXEZZL3T-Dd5BEpOv.mjs} +2 -2
  222. package/dist/{join-GG2LDHE5-O6S65p4r.mjs → join-GG2LDHE5-kABASDPB.mjs} +1 -1
  223. package/dist/{journeyDiagram-5HDEW3XC-NczxLuUX.mjs → journeyDiagram-5HDEW3XC-W6Nbr96_.mjs} +2 -2
  224. package/dist/jq-LYZFFBZB-CIwp4u6h.mjs +1 -0
  225. package/dist/{js-exec-VXN6TZ7U-BJsjY3Aj.mjs → js-exec-VXN6TZ7U-1yyCDQqM.mjs} +2 -2
  226. package/dist/{kanban-definition-HUTT4EX6-CJ2cty8a.mjs → kanban-definition-HUTT4EX6-xcwe5vNg.mjs} +2 -2
  227. package/dist/{launch-json-removal-Bwz73HwG.mjs → launch-json-removal-BIdtII1e.mjs} +2 -2
  228. package/dist/{lib-BpZC9d5Z.mjs → lib-BCIeHFfP.mjs} +1 -1
  229. package/dist/{lib-BS_oZ9bm.mjs → lib-TLTWf9qr.mjs} +1 -1
  230. package/dist/{line-CyR2aPKZ.mjs → line-Cq-NoiNn.mjs} +2 -2
  231. package/dist/{linear-DHgeTTi3.mjs → linear-DPbvcrPk.mjs} +2 -2
  232. package/dist/{ln-4TRFBYAT-DErk_Yl0.mjs → ln-4TRFBYAT-Dhr3hBr6.mjs} +1 -1
  233. package/dist/{loader-DVsRTqac.mjs → loader-DyaU7oQR.mjs} +2 -2
  234. package/dist/loader-feaGCk--.mjs +1 -0
  235. package/dist/{logger-5LePyO3n.mjs → logger-BZPV1wv8.mjs} +2 -2
  236. package/dist/ls-KSXFZCWH-BEv3e7-2.mjs +1 -0
  237. package/dist/{lzma-yp9l_vMN.mjs → lzma-Dh_aFpqW.mjs} +1 -1
  238. package/dist/{map-DbF7r1vR.mjs → map-CFzSl60r.mjs} +2 -2
  239. package/dist/{mcp-migrate-event-CWx0WLdE.mjs → mcp-migrate-event-B1gJf6bG.mjs} +1 -1
  240. package/dist/md5sum-INMIK4DX-CJ1G9gTe.mjs +1 -0
  241. package/dist/{mermaid-parser.core-Dq0Vyvhg.mjs → mermaid-parser.core-DejmtVwC.mjs} +2 -2
  242. package/dist/{mermaid.core-CZm3qvuv.mjs → mermaid.core-CB8v9A8r.mjs} +3 -3
  243. package/dist/{mindmap-definition-LN4V7U3C-DYytxufy.mjs → mindmap-definition-LN4V7U3C-BiYp6fzL.mjs} +2 -2
  244. package/dist/mkdir-TDEMSB6C-BY7IIkok.mjs +1 -0
  245. package/dist/mv-Z6MORUFL-C4m2WG8E.mjs +1 -0
  246. package/dist/{nl-U5YJDM32-CgnuF_hC.mjs → nl-U5YJDM32-CrNZhLtI.mjs} +1 -1
  247. package/dist/{od-VJEF2UR5-BTJQNl6y.mjs → od-VJEF2UR5-5RFpmlxK.mjs} +1 -1
  248. package/dist/{open-browser-C5MzSCJR.mjs → open-browser-CwwQWCcr.mjs} +2 -2
  249. package/dist/{ordinal-CUIZW000.mjs → ordinal-D5S_JXYv.mjs} +2 -2
  250. package/dist/packet-7NZHBO7P-DJoR1MQJ.mjs +1 -0
  251. package/dist/paste-7N6AFSDS-DQNANxpk.mjs +1 -0
  252. package/dist/{path-BT3cGQxQ.mjs → path-D4ahAhVD.mjs} +1 -1
  253. package/dist/{pegDiagram-2B236MQR-tT5pVAwT.mjs → pegDiagram-2B236MQR-DMP1ng8V.mjs} +2 -2
  254. package/dist/pie-RZYD4A2V-Ba8iL0H-.mjs +1 -0
  255. package/dist/{pieDiagram-ENE6RG2P-kD_93j1i.mjs → pieDiagram-ENE6RG2P-CSKXRjGQ.mjs} +2 -2
  256. package/dist/preview-BTXMtNk6.mjs +1 -0
  257. package/dist/{preview-MxO7wX5P.mjs → preview-BVOupWPx.mjs} +2 -2
  258. package/dist/printf-CX64KX2P-CKuJk-Cs.mjs +1 -0
  259. package/dist/pwd-D4OZ7N27-CSTLotxZ.mjs +1 -0
  260. package/dist/{python3-DNGS4G3E-BPxhh_Jp.mjs → python3-DNGS4G3E-BZ5fPY5e.mjs} +2 -2
  261. package/dist/{quadrantDiagram-ABIIQ3AL-CyuIUsL6.mjs → quadrantDiagram-ABIIQ3AL-Do93EPf_.mjs} +2 -2
  262. package/dist/radar-I7S5WNFK-HP72Fmhl.mjs +1 -0
  263. package/dist/railroad-3IZDKUUU-DC3PWo_6.mjs +1 -0
  264. package/dist/railroad-abnf-AHOZXSZD-Vgpa9_KI.mjs +1 -0
  265. package/dist/railroad-ebnf-EBAXGLYW-B4SmMMsT.mjs +1 -0
  266. package/dist/railroad-peg-LSFZ7HO6-DLlDiUuB.mjs +1 -0
  267. package/dist/{railroadDiagram-RFXS5EU6-CHD_Jape.mjs → railroadDiagram-RFXS5EU6-BBHONGQu.mjs} +2 -2
  268. package/dist/readlink-MI4GCHJF-V9fwXBrg.mjs +1 -0
  269. package/dist/{repair-launch-json-56bz582u.mjs → repair-launch-json-DaGt48pl.mjs} +2 -2
  270. package/dist/repair-mcp-configs-TwLS0dUD.mjs +2 -0
  271. package/dist/repair-skills-CVT6M7om.mjs +4 -0
  272. package/dist/repair-skills-He_WQsPp.mjs +1 -0
  273. package/dist/{requirementDiagram-TGXJPOKE-CGQTVdQl.mjs → requirementDiagram-TGXJPOKE-CAGy_wFo.mjs} +2 -2
  274. package/dist/{rev-XOSYPP45-BGL4FR9H.mjs → rev-XOSYPP45-G2PvMYC2.mjs} +1 -1
  275. package/dist/rg-XNF3R3II-CuFYIwNn.mjs +1 -0
  276. package/dist/rm-RTZG23RL-BOvMrhon.mjs +1 -0
  277. package/dist/rmdir-XTQXT7RK-Dk19R-p8.mjs +1 -0
  278. package/dist/{rough.cjs-s8-IvpYn.mjs → rough.cjs-LxmwwhvT.mjs} +1 -1
  279. package/dist/{sankeyDiagram-HTMAVEWB-B1AFQN8q.mjs → sankeyDiagram-HTMAVEWB-B59ayZ_U.mjs} +2 -2
  280. package/dist/{sed-JAPPVBEU-YSD3Wwpz.mjs → sed-JAPPVBEU-BUaK4riL.mjs} +1 -1
  281. package/dist/seq-RN5ZUASB-D5aLn_so.mjs +1 -0
  282. package/dist/{sequenceDiagram-DBY2YBRQ-JQ2Wynkh.mjs → sequenceDiagram-DBY2YBRQ-BqY5gm2k.mjs} +2 -2
  283. package/dist/{server-lock-Cg66XiR-.mjs → server-lock--0V-ESY4.mjs} +2 -2
  284. package/dist/server-lock-owrYVjgw.mjs +1 -0
  285. package/dist/sha1sum-VJPNLNU6-DnTKth9v.mjs +1 -0
  286. package/dist/sha256sum-PI32XWXY-Z-xtGDHc.mjs +1 -0
  287. package/dist/{sizeCapture-X5ZJPWSS-Btionz6c.mjs → sizeCapture-X5ZJPWSS-D7Nqbe-W.mjs} +2 -2
  288. package/dist/skill-teardown-POqnRqru.mjs +2 -0
  289. package/dist/{sleep-VZFPZFWA-DNxq1g-4.mjs → sleep-VZFPZFWA-DcISab6N.mjs} +1 -1
  290. package/dist/sort-DCNRDA7U-C1gRzOOY.mjs +1 -0
  291. package/dist/{split-SITCSYCZ-Dl-r5t6o.mjs → split-SITCSYCZ-D4U2N_sH.mjs} +1 -1
  292. package/dist/{sqlite3-TE5AIOTF-DV5JBdcO.mjs → sqlite3-TE5AIOTF-DcjYN7WW.mjs} +1 -1
  293. package/dist/{src-nvx4LAFk.mjs → src-BuBt_xnY.mjs} +2 -2
  294. package/dist/{src-BVOdbrbz.mjs → src-C9LMhuL4.mjs} +12 -12
  295. package/dist/src-CKL2S7dl.mjs +20 -0
  296. package/dist/{src-BLAyDRF9.mjs → src-n6rcQokc.mjs} +1 -1
  297. package/dist/start-DJONNZUB.mjs +1 -0
  298. package/dist/{start-BVMhwbcE.mjs → start-iMpGNdo0.mjs} +3 -3
  299. package/dist/stat-BT5A227F-B4qwqNn_.mjs +1 -0
  300. package/dist/{stateDiagram-2N3HPSRC-BzNiMGRR.mjs → stateDiagram-2N3HPSRC-BD1FBZi9.mjs} +2 -2
  301. package/dist/stateDiagram-v2-6OUMAXLB-CqmBRdZY.mjs +2 -0
  302. package/dist/strings-7PLOGTPD-BJ6vWsQi.mjs +1 -0
  303. package/dist/{swimlanes-5IMT3BWC-BrdJ_D0k.mjs → swimlanes-5IMT3BWC-D2eO0gTx.mjs} +2 -2
  304. package/dist/swimlanesDiagram-G3AALYLV-BiRCZWbo.mjs +9 -0
  305. package/dist/{tac-SJGXQ4T2-ByjKkvjF.mjs → tac-SJGXQ4T2-D-bfDFKg.mjs} +1 -1
  306. package/dist/tail-S5ULNTJU-CWnyTuXg.mjs +1 -0
  307. package/dist/{tar-MZQD7NO4-B2cyr2d4.mjs → tar-MZQD7NO4-Cx5bpVMY.mjs} +1 -1
  308. package/dist/tee-O7VXZDCO-B_duU1hV.mjs +1 -0
  309. package/dist/time-DEUO3QV2-CekCKA2I.mjs +1 -0
  310. package/dist/{timeline-definition-FHXFAJF6-ByhSkc7M.mjs → timeline-definition-FHXFAJF6-DZHpuaV_.mjs} +2 -2
  311. package/dist/{timeout-VRKMCG72-BJzTDNVp.mjs → timeout-VRKMCG72-DaJVXXR3.mjs} +1 -1
  312. package/dist/touch-DX2IJOQ4-CZteiICw.mjs +1 -0
  313. package/dist/tr-2HXZRDSW-D4XuTGWg.mjs +1 -0
  314. package/dist/tree-LYXBS7DC-CUIzQKTG.mjs +1 -0
  315. package/dist/treeView-QDETBFTQ-C9yOsbGY.mjs +1 -0
  316. package/dist/treemap-6X3UGDF4-iowse2nY.mjs +1 -0
  317. package/dist/true-WHJNXCHG-BzxCUQFd.mjs +1 -0
  318. package/dist/unexpand-RGTMIGZM-x3XCmR3I.mjs +1 -0
  319. package/dist/uniq-SUNANL47-DpupkNiO.mjs +1 -0
  320. package/dist/{vennDiagram-L72KCM5P-CosAdslh.mjs → vennDiagram-L72KCM5P-CGoW4QcS.mjs} +2 -2
  321. package/dist/wardley-OPB4EBWU-BL1Dan_S.mjs +1 -0
  322. package/dist/{wardleyDiagram-EHGQE667-Bdo1uN9O.mjs → wardleyDiagram-EHGQE667-DHS8jBWZ.mjs} +2 -2
  323. package/dist/wc-TQB3VNOX-D8llmcL9.mjs +1 -0
  324. package/dist/which-XZHEH76L-imZgNd5x.mjs +1 -0
  325. package/dist/whoami-DGKU3D2X-CzLNG51j.mjs +1 -0
  326. package/dist/{write-project-skill-BT53Ejz2.mjs → write-project-skill-DvqoihuV.mjs} +7 -7
  327. package/dist/xan-UD7JYIL2-_38Iv1cI.mjs +1 -0
  328. package/dist/xan-view-OW2TB7Z3-RT-IKMgr.mjs +1 -0
  329. package/dist/xargs-I6EZUCYF-Bu8VhXV_.mjs +1 -0
  330. package/dist/{xychartDiagram-FW5EYKEG-CBeluzNN.mjs → xychartDiagram-FW5EYKEG-CG0DSvm_.mjs} +2 -2
  331. package/dist/yq-OAKYHSXH-BcCBaLJN.mjs +1 -0
  332. package/package.json +4 -4
  333. package/dist/alias-JE7RI5QX-BvhaFG9J.mjs +0 -1
  334. package/dist/architecture-TIHT7OUA-BVYsZR9r.mjs +0 -1
  335. package/dist/bash-IJWYRKFO-BWspyNyq.mjs +0 -1
  336. package/dist/channel-DppMxZyL.mjs +0 -2
  337. package/dist/chunk-VAUOI2AC-CLylHljB.mjs +0 -2
  338. package/dist/chunk-XXDRQBXY-ClPfCVft.mjs +0 -2
  339. package/dist/classDiagram-OUVF2IWQ-c5qgwZAE.mjs +0 -2
  340. package/dist/classDiagram-v2-EOCWNBFH-D9ilZPqi.mjs +0 -2
  341. package/dist/constants-Bp8I4KQS.mjs +0 -2
  342. package/dist/cynefin-VYW2F7L2-CEVi_iCC.mjs +0 -1
  343. package/dist/diff-HJF2MPDN-DhZaF2MX.mjs +0 -1
  344. package/dist/echo-O45JWWI2-B8YWvx1Q.mjs +0 -1
  345. package/dist/env-5EPCWSXR-Cor7cJ6o.mjs +0 -1
  346. package/dist/eventmodeling-45OFAUF4-BENS2g0X.mjs +0 -1
  347. package/dist/expr-YYCVMXE3-VEQOsPiP.mjs +0 -1
  348. package/dist/find-DH2ALKQS-D4DqPp7j.mjs +0 -1
  349. package/dist/flag-coverage-6JEX67RU-C21BAvUp.mjs +0 -2
  350. package/dist/flowDiagram-23GEKE2U-BHZRRZtz.mjs +0 -1
  351. package/dist/fs-traced-C9U9YUGm.mjs +0 -1
  352. package/dist/gitGraph-TEB2WS4Q-C-obuzNL.mjs +0 -1
  353. package/dist/grep-2HUTXO5U-BHpyAWOj.mjs +0 -1
  354. package/dist/gzip-AQXSGOVS-kgzROhmg.mjs +0 -1
  355. package/dist/help-VVWX7SA5-Cnq4Pk95.mjs +0 -1
  356. package/dist/history-J4QRNGRO-ChaCzoJD.mjs +0 -1
  357. package/dist/html-to-markdown-TFCECAGV-DRmuleyA.mjs +0 -1
  358. package/dist/info-DKCQHKI2-_AQUrTgC.mjs +0 -1
  359. package/dist/init-BC0u4teF.mjs +0 -1
  360. package/dist/jq-LYZFFBZB-DTUwGGgl.mjs +0 -1
  361. package/dist/loader-DwZ-kNkG.mjs +0 -1
  362. package/dist/ls-KSXFZCWH-DQIF-HgH.mjs +0 -1
  363. package/dist/md5sum-INMIK4DX-BElHH82h.mjs +0 -1
  364. package/dist/mkdir-TDEMSB6C-BnpJKc8r.mjs +0 -1
  365. package/dist/mv-Z6MORUFL-CFyBiApv.mjs +0 -1
  366. package/dist/packet-7NZHBO7P-CHMfNci8.mjs +0 -1
  367. package/dist/paste-7N6AFSDS-CnLMuz8G.mjs +0 -1
  368. package/dist/pie-RZYD4A2V-02sGjUcO.mjs +0 -1
  369. package/dist/preview-B9XDskoX.mjs +0 -1
  370. package/dist/printf-CX64KX2P-DyVBy6Mg.mjs +0 -1
  371. package/dist/pwd-D4OZ7N27-Pga3crue.mjs +0 -1
  372. package/dist/radar-I7S5WNFK-gNSWd2rG.mjs +0 -1
  373. package/dist/railroad-3IZDKUUU-tTi02nbm.mjs +0 -1
  374. package/dist/railroad-abnf-AHOZXSZD-DD6KwCgt.mjs +0 -1
  375. package/dist/railroad-ebnf-EBAXGLYW-zJw8iMTp.mjs +0 -1
  376. package/dist/railroad-peg-LSFZ7HO6-8PbAUZs1.mjs +0 -1
  377. package/dist/readlink-MI4GCHJF-D9QYkCU0.mjs +0 -1
  378. package/dist/repair-mcp-configs-DPiYn_Ou.mjs +0 -2
  379. package/dist/repair-skills-qZNnVHuG.mjs +0 -1
  380. package/dist/repair-skills-wKMPJS9U.mjs +0 -4
  381. package/dist/rg-XNF3R3II-BMfKONjk.mjs +0 -1
  382. package/dist/rm-RTZG23RL-vsz0Vtsc.mjs +0 -1
  383. package/dist/rmdir-XTQXT7RK-C9jARGFn.mjs +0 -1
  384. package/dist/seq-RN5ZUASB-hcgHczjD.mjs +0 -1
  385. package/dist/server-lock-DyY9o-h3.mjs +0 -1
  386. package/dist/sha1sum-VJPNLNU6-KpqF3VUr.mjs +0 -1
  387. package/dist/sha256sum-PI32XWXY-BI7zTPJ3.mjs +0 -1
  388. package/dist/sort-DCNRDA7U-urKKiOkB.mjs +0 -1
  389. package/dist/src-DBN0I6LD.mjs +0 -20
  390. package/dist/start-ecRmiiD7.mjs +0 -1
  391. package/dist/stat-BT5A227F-BzZhqUU7.mjs +0 -1
  392. package/dist/stateDiagram-v2-6OUMAXLB-8Ywz0Hzd.mjs +0 -2
  393. package/dist/strings-7PLOGTPD-BYF-zQB5.mjs +0 -1
  394. package/dist/swimlanesDiagram-G3AALYLV-Df_BjTMR.mjs +0 -9
  395. package/dist/tail-S5ULNTJU-Bu45hbfn.mjs +0 -1
  396. package/dist/tee-O7VXZDCO-D5VPiyFZ.mjs +0 -1
  397. package/dist/time-DEUO3QV2-DTXF6o9u.mjs +0 -1
  398. package/dist/touch-DX2IJOQ4-CJL2LWzm.mjs +0 -1
  399. package/dist/tr-2HXZRDSW-BMEHkLkI.mjs +0 -1
  400. package/dist/tree-LYXBS7DC-B9nDoMUt.mjs +0 -1
  401. package/dist/treeView-QDETBFTQ-b0kDTk8s.mjs +0 -1
  402. package/dist/treemap-6X3UGDF4-CbmqvOp3.mjs +0 -1
  403. package/dist/true-WHJNXCHG-BrTi18ZN.mjs +0 -1
  404. package/dist/unexpand-RGTMIGZM-Cz9o379Y.mjs +0 -1
  405. package/dist/uniq-SUNANL47-Jq_1JF4a.mjs +0 -1
  406. package/dist/wardley-OPB4EBWU-58Nq0iPk.mjs +0 -1
  407. package/dist/wc-TQB3VNOX-8TWuJ_OV.mjs +0 -1
  408. package/dist/which-XZHEH76L-C0nS7069.mjs +0 -1
  409. package/dist/whoami-DGKU3D2X-BRFeF7SV.mjs +0 -1
  410. package/dist/xan-UD7JYIL2-CsuyuKIz.mjs +0 -1
  411. package/dist/xan-view-OW2TB7Z3-BQPByClA.mjs +0 -1
  412. package/dist/xargs-I6EZUCYF-CfQ6WD0x.mjs +0 -1
  413. package/dist/yq-OAKYHSXH-q34fmnbQ.mjs +0 -1
  414. /package/dist/{expansion-VBDYWVZR-e2HuIG0U.mjs → expansion-VBDYWVZR-CeY6vkty.mjs} +0 -0
@@ -1,7 +1,7 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as ee,W as te,Y as ne,Z as re,_ as ie,_t as E,at as D,b as ae,bt as O,ct as oe,d as se,dt as k,et as ce,f as le,ft as ue,g as de,gt as fe,ht as A,i as pe,it as j,jt as me,kt as he,l as ge,lt as _e,mt as M,n as ve,nt as ye,ot as be,pt as N,q as P,r as xe,st as Se,t as Ce,tt as we,v as Te,vt as F,w as Ee,wt as De,xt as Oe,y as ke,yt as I}from"./sleep-ByqzSHar.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Co as et,Cr as tt,Ct as nt,D as rt,Da as it,Di as at,Dn as ot,Do as st,Dr as ct,Dt as lt,E as ut,Ea as dt,Ei as ft,En as pt,Er as mt,Et as ht,F as gt,Fa as _t,Fi as vt,Fn as yt,Fr as eee,G as bt,Ga as xt,Gi as tee,Gn as nee,Go as St,Gr as Ct,Gt as wt,H as Tt,Ha as Et,Hi as ree,Hn as iee,Ho as Dt,Hr as aee,Ht as Ot,I as kt,Ia as At,Ii as jt,In as oee,Io as Mt,Ir as Nt,It as Pt,J as Ft,Ja as It,Ji as Lt,Jn as Rt,Jo as zt,Jr as Bt,Jt as Vt,K as Ht,Ka as Ut,Ki as Wt,Kn as Gt,Ko as Kt,Kr as qt,Kt as Jt,L as Yt,La as see,Li as cee,Ln as lee,Lr as uee,Lt as Xt,M as Zt,Mi as Qt,Mn as dee,Mr as fee,Mt as $t,N as en,Na as tn,Ni as nn,Nn as rn,No as an,Nr as on,Nt as sn,O as cn,Oa as ln,Oi as un,On as dn,Oo as fn,Or as pee,Ot as pn,P as mn,Pa as hn,Pi as gn,Pn as _n,Po as vn,Pr as yn,Qa as bn,Qi as xn,Qn as Sn,Qo as Cn,Qr as wn,Qt as Tn,Ra as En,Ri as Dn,Rn as On,Ro as kn,Rr as An,Rt as jn,S as Mn,Sa as Nn,Si as Pn,Sn as mee,So as Fn,Sr as In,Ss as Ln,St as Rn,T as zn,Ta as Bn,Ti as Vn,Tn as Hn,To as Un,Tr as hee,Tt as Wn,U as Gn,Ua as Kn,Ui as qn,Un as gee,Uo as Jn,Ur as _ee,Ut as Yn,V as vee,Va as yee,Vi as bee,Vn as Xn,Vo as Zn,Vr as xee,Vt as Qn,W as $n,Wa as See,Wi as Cee,Wn as wee,Wo as er,Wr as tr,Wt as nr,X as rr,Xa as ir,Xi as ar,Xn as Tee,Xo as or,Xr as sr,Xt as cr,Ya as lr,Yi as ur,Yn as dr,Yo as fr,Yr as pr,Yt as mr,Za as hr,Zi as gr,Zn as Eee,Zr as _r,Zt as vr,_ as yr,_a as Dee,_i as br,_n as xr,_o as Sr,_r as Cr,_s as wr,_t as Tr,a as Er,aa as Dr,ai as Or,an as kr,ao as Ar,ar as Oee,as as jr,at as Mr,b as Nr,ba as Pr,bi as Fr,bn as Ir,bo as Lr,br as Rr,bt as zr,c as Br,ca as Vr,ci as Hr,cn as Ur,co as Wr,cr as Gr,cs as Kr,ct as qr,d as Jr,da as Yr,di as Xr,dn as Zr,do as Qr,dr as $r,ds as ei,dt as ti,ea as ni,ei as ri,en as ii,eo as ai,er as oi,es as si,et as ci,f as li,fa as ui,fi as di,fn as fi,fr as pi,fs as mi,ft as hi,g as gi,ga as _i,gi as vi,gn as yi,go as bi,gr as xi,gs as Si,gt as Ci,h as wi,ha as Ti,hi as Ei,hn as Di,ho as Oi,hr as ki,hs as Ai,ht as ji,i as Mi,ia as Ni,ii as Pi,in as Fi,io as Ii,ir as Li,is as Ri,it as zi,j as Bi,ja as Vi,ji as Hi,jn as Ui,jo as Wi,jr as Gi,jt as Ki,k as qi,ka as Ji,ki as Yi,kn as Xi,ko as Zi,kr as Qi,kt as $i,l as ea,la as ta,li as na,ln as ra,lo as ia,lr as aa,ls as oa,lt as sa,ma as ca,mi as la,mn as ua,mo as da,mr as fa,ms as pa,mt as ma,n as ha,na as ga,ni as kee,nn as Aee,no as jee,nr as Mee,ns as _a,nt as va,o as ya,oa as ba,oi as xa,on as Nee,or as Pee,os as Sa,ot as Ca,p as wa,pa as Ta,pi as Fee,pn as Ea,pr as Iee,ps as Da,pt as Oa,q as ka,qa as Lee,qi as Aa,qn as Ree,qo as ja,qr as zee,qt as Bee,r as Ma,ra as Na,ri as Vee,rn as Hee,ro as Uee,rr as Wee,rs as Pa,rt as Fa,s as Ia,sa as La,si as Gee,sn as Kee,so as qee,sr as Ra,ss as za,st as Ba,t as Va,ta as Ha,ti as Ua,tn as Jee,to as Wa,tr as Yee,ts as Ga,tt as Ka,u as qa,ua as Xee,ui as Zee,un as Qee,ur as $ee,us as Ja,ut as Ya,v as Xa,va as ete,vi as tte,vn as Za,vr as nte,vs as Qa,vt as $a,w as eo,wa as to,wi as no,wn as rte,wo as ro,wr as ite,wt as io,x as ao,xa as oo,xi as ate,xn as so,xr as co,xt as lo,y as uo,ya as fo,yi as po,yn as mo,yo as ho,yr as ote,ys as go,yt as _o,z as vo,za as yo,zi as bo,zn as ste,zo as xo,zr as So,zt as Co}from"./src-Bnk118Ag.mjs";import{c as wo,i as To,l as Eo,n as Do,s as Oo}from"./esm-DxvI2ZVA.mjs";import{n as ko,t as Ao}from"./md-manager-BURSRub5.mjs";import{A as jo,C as Mo,D as No,E as Po,F as Fo,N as Io,O as Lo,S as Ro,T as zo,_ as Bo,a as Vo,b as Ho,c as Uo,d as Wo,f as Go,g as Ko,h as qo,i as Jo,j as Yo,k as Xo,l as Zo,m as Qo,n as $o,o as es,p as ts,r as ns,s as rs,t as is,u as as,v as os,w as ss,x as cs,y as ls}from"./fs-traced-ArlA_yTp.mjs";import{D as us,E as ds,S as fs,T as ps,a as ms,b as hs,l as gs,p as _s,r as L,s as vs,x as ys,y as bs}from"./logger-5LePyO3n.mjs";import{a as xs,i as Ss,o as Cs,r as ws,s as Ts,t as Es}from"./git-handle-DDjBzdsL.mjs";import{S as Ds,a as Os,b as ks,c as As,d as js,f as Ms,g as Ns,h as Ps,i as Fs,l as Is,m as Ls,n as Rs,r as zs,x as Bs,y as Vs}from"./server-lock-Cg66XiR-.mjs";import{t as Hs}from"./libesm-DzwC_yFw.mjs";import{n as Us,t as Ws}from"./build-DYQrG4v7.mjs";import{t as Gs}from"./yazl-BafwB467.mjs";import{t as Ks}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as qs,c as Js,d as Ys,f as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,o as nc,p as rc,r as ic,s as ac,t as oc,u as sc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as cc,B as lc,C as uc,D as dc,E as fc,F as pc,H as mc,I as hc,L as gc,M as _c,N as vc,O as yc,P as bc,S as xc,T as Sc,V as Cc,_ as wc,a as Tc,b as Ec,c as Dc,d as Oc,f as kc,g as Ac,h as jc,i as Mc,j as Nc,k as Pc,l as Fc,m as Ic,n as Lc,o as Rc,p as zc,r as Bc,s as Vc,t as Hc,u as Uc,v as Wc,w as Gc,x as Kc,y as qc,z as Jc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Yc,c as Xc,d as Zc,i as Qc,l as $c,n as el,o as tl,r as nl,s as rl,t as il,u as al}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as ol,r as sl,t as cl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as ll}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as ul}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as dl,t as fl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as pl,t as ml}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as hl,r as gl,t as _l}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as vl,t as yl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as bl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as xl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Sl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Cl}from"node:module";import{execFile as wl,execFileSync as Tl,spawn as El,spawnSync as Dl}from"node:child_process";import*as Ol from"node:path";import{basename as kl,delimiter as Al,dirname as R,extname as jl,isAbsolute as Ml,join as z,normalize as Nl,posix as Pl,relative as B,resolve as V,sep as Fl,win32 as Il}from"node:path";import{URLSearchParams as Ll,fileURLToPath as Rl,pathToFileURL as zl}from"node:url";import*as Bl from"node:fs";import{appendFileSync as Vl,chmodSync as Hl,closeSync as Ul,constants as Wl,createReadStream as Gl,createWriteStream as Kl,existsSync as H,lstatSync as ql,mkdirSync as Jl,mkdtempSync as Yl,openSync as Xl,readFile as Zl,readFileSync as U,readSync as Ql,readdirSync as $l,readlinkSync as eu,realpathSync as W,renameSync as tu,rmSync as nu,rmdirSync as ru,statSync as iu,unlinkSync as au,writeFileSync as ou,writeSync as su}from"node:fs";import{arch as cu,availableParallelism as lu,homedir as uu,hostname as du,platform as fu,tmpdir as pu}from"node:os";import{access as mu,chmod as hu,constants as gu,lstat as _u,readFile as vu,readdir as yu,realpath as bu,stat as xu,writeFile as Su}from"node:fs/promises";import{Readable as Cu,Transform as wu,Writable as Tu}from"node:stream";import Eu,{createHash as Du,randomUUID as Ou,webcrypto as ku}from"node:crypto";import Au from"crypto";import{Readable as ju}from"stream";import{Worker as Mu}from"node:worker_threads";import{monitorEventLoopDelay as Nu,performance as Pu}from"node:perf_hooks";import{createInterface as Fu}from"node:readline";import{pipeline as Iu}from"node:stream/promises";import{setImmediate as Lu,setTimeout as Ru}from"node:timers/promises";import{promisify as zu}from"node:util";import{lookup as Bu}from"node:dns/promises";import{request as Vu}from"node:http";import{request as cte}from"node:https";import{createBrotliDecompress as lte,createGunzip as Hu,createInflate as Uu}from"node:zlib";import{Http2ServerRequest as Wu,constants as Gu}from"http2";import{AsyncLocalStorage as ute}from"node:async_hooks";import{lookup as dte}from"node:dns";import fte from"node:tls";function pte(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),mte(n)}function mte(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Ku=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Ml(t)?t:V(this.gitDir,t))}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:td(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=U(z(t.path,`config`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Xu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!ed(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Ml(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=hte(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return td(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function qu(e){return Yu(V(e),``)}function Ju(e){let t=V(e),n=V(uu());if(t===n)return{kind:`absent`};let r=Yu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=R(i);if(e===i||e===n)return{kind:`absent`};let r=Yu(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Yu(e,t){let n=z(e,`.git`),r;try{r=iu(n)}catch(e){return $u(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Ku(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Ml(o)?o:V(e,o);try{if(!iu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Ku(`linked`,e,t,n,s)}}function Xu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Zu(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=Qu(i[1]);if(a.length>0)return a}return null}function Zu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Qu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function $u(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function ed(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function hte(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?ed(t[1])?{kind:`symbolic`,target:t[1]}:null:td(e)?{kind:`oid`,oid:e}:null}function td(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function gte(e){return`git-author-${nt(e.trim().toLowerCase())}`}const _te=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function nd(e){let t=Ju(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function rd(e){let t=nd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function id(e){let t=nd(e);switch(t.kind){case`directory`:return V(t.path,ad(t.projectSubPath));case`linked`:if(!H(t.path))throw new cd(t.gitPath,t.path);return V(t.path,ad(t.projectSubPath));case`malformed-pointer`:throw new cd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ld(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function ad(e){return e===``?`ok`:`ok-${od(e)}`}function od(e){let t=e.split(Fl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=sd(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function sd(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var cd=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,n){let r=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${r}. Run \`git worktree prune\` from the source repo and try again.`,n),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},ld=class extends Error{gitPath;constructor(e,t){let n=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${n}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function ud(e){let t;try{t=id(e)}catch(e){if(e instanceof cd||e instanceof ld)return null;throw e}return H(V(t,`HEAD`))?t:null}function dd(e){return`refs/wip/${e}/`}function fd(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as ee,W as te,Y as ne,Z as re,_ as ie,_t as E,at as D,b as ae,bt as O,ct as oe,d as se,dt as k,et as ce,f as le,ft as ue,g as de,gt as fe,ht as A,i as pe,it as j,jt as me,kt as he,l as ge,lt as _e,mt as M,n as ve,nt as ye,ot as be,pt as N,q as P,r as xe,st as Se,t as Ce,tt as we,v as Te,vt as F,w as Ee,wt as De,xt as Oe,y as ke,yt as I}from"./sleep-ByqzSHar.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Co as et,Cr as tt,Ct as nt,D as rt,Da as it,Di as at,Dn as ot,Do as st,Dr as ct,Dt as lt,E as ut,Ea as dt,Ei as ft,En as pt,Er as mt,Et as ht,F as gt,Fa as _t,Fi as vt,Fn as yt,Fr as eee,G as bt,Ga as xt,Gi as tee,Gn as nee,Go as St,Gr as Ct,Gt as wt,H as Tt,Ha as Et,Hi as ree,Hn as iee,Ho as Dt,Hr as aee,Ht as Ot,I as kt,Ia as At,Ii as jt,In as oee,Io as Mt,Ir as Nt,It as Pt,J as Ft,Ja as It,Ji as Lt,Jn as Rt,Jo as zt,Jr as Bt,Jt as Vt,K as Ht,Ka as Ut,Ki as Wt,Kn as Gt,Ko as Kt,Kr as qt,Kt as Jt,L as Yt,La as see,Li as cee,Ln as lee,Lr as uee,Lt as Xt,M as Zt,Mi as Qt,Mn as dee,Mr as fee,Mt as $t,N as en,Na as tn,Ni as nn,Nn as rn,No as an,Nr as on,Nt as sn,O as cn,Oa as ln,Oi as un,On as dn,Oo as fn,Or as pee,Ot as pn,P as mn,Pa as hn,Pi as gn,Pn as _n,Po as vn,Pr as yn,Qa as bn,Qi as xn,Qn as Sn,Qo as Cn,Qr as wn,Qt as Tn,Ra as En,Ri as Dn,Rn as On,Ro as kn,Rr as An,Rt as jn,S as Mn,Sa as Nn,Si as Pn,Sn as mee,So as Fn,Sr as In,Ss as Ln,St as Rn,T as zn,Ta as Bn,Ti as Vn,Tn as Hn,To as Un,Tr as hee,Tt as Wn,U as Gn,Ua as Kn,Ui as qn,Un as gee,Uo as Jn,Ur as _ee,Ut as Yn,V as vee,Va as yee,Vi as bee,Vn as Xn,Vo as Zn,Vr as xee,Vt as Qn,W as $n,Wa as See,Wi as Cee,Wn as wee,Wo as er,Wr as tr,Wt as nr,X as rr,Xa as ir,Xi as ar,Xn as Tee,Xo as or,Xr as sr,Xt as cr,Ya as lr,Yi as ur,Yn as dr,Yo as fr,Yr as pr,Yt as mr,Za as hr,Zi as gr,Zn as Eee,Zr as _r,Zt as vr,_ as yr,_a as Dee,_i as br,_n as xr,_o as Sr,_r as Cr,_s as wr,_t as Tr,a as Er,aa as Dr,ai as Or,an as kr,ao as Ar,ar as Oee,as as jr,at as Mr,b as Nr,ba as Pr,bi as Fr,bn as Ir,bo as Lr,br as Rr,bt as zr,c as Br,ca as Vr,ci as Hr,cn as Ur,co as Wr,cr as Gr,cs as Kr,ct as qr,d as Jr,da as Yr,di as Xr,dn as Zr,do as Qr,dr as $r,ds as ei,dt as ti,ea as ni,ei as ri,en as ii,eo as ai,er as oi,es as si,et as ci,f as li,fa as ui,fi as di,fn as fi,fr as pi,fs as mi,ft as hi,g as gi,ga as _i,gi as vi,gn as yi,go as bi,gr as xi,gs as Si,gt as Ci,h as wi,ha as Ti,hi as Ei,hn as Di,ho as Oi,hr as ki,hs as Ai,ht as ji,i as Mi,ia as Ni,ii as Pi,in as Fi,io as Ii,ir as Li,is as Ri,it as zi,j as Bi,ja as Vi,ji as Hi,jn as Ui,jo as Wi,jr as Gi,jt as Ki,k as qi,ka as Ji,ki as Yi,kn as Xi,ko as Zi,kr as Qi,kt as $i,l as ea,la as ta,li as na,ln as ra,lo as ia,lr as aa,ls as oa,lt as sa,ma as ca,mi as la,mn as ua,mo as da,mr as fa,ms as pa,mt as ma,n as ha,na as ga,ni as kee,nn as Aee,no as jee,nr as Mee,ns as _a,nt as va,o as ya,oa as ba,oi as xa,on as Nee,or as Pee,os as Sa,ot as Ca,p as wa,pa as Ta,pi as Fee,pn as Ea,pr as Iee,ps as Da,pt as Oa,q as ka,qa as Lee,qi as Aa,qn as Ree,qo as ja,qr as zee,qt as Bee,r as Ma,ra as Na,ri as Vee,rn as Hee,ro as Uee,rr as Wee,rs as Pa,rt as Fa,s as Ia,sa as La,si as Gee,sn as Kee,so as qee,sr as Ra,ss as za,st as Ba,t as Va,ta as Ha,ti as Ua,tn as Jee,to as Wa,tr as Yee,ts as Ga,tt as Ka,u as qa,ua as Xee,ui as Zee,un as Qee,ur as $ee,us as Ja,ut as Ya,v as Xa,va as ete,vi as tte,vn as Za,vr as nte,vs as Qa,vt as $a,w as eo,wa as to,wi as no,wn as rte,wo as ro,wr as ite,wt as io,x as ao,xa as oo,xi as ate,xn as so,xr as co,xt as lo,y as uo,ya as fo,yi as po,yn as mo,yo as ho,yr as ote,ys as go,yt as _o,z as vo,za as yo,zi as bo,zn as ste,zo as xo,zr as So,zt as Co}from"./src-Bnk118Ag.mjs";import{c as wo,i as To,l as Eo,n as Do,s as Oo}from"./esm-DxvI2ZVA.mjs";import{n as ko,t as Ao}from"./md-manager-BURSRub5.mjs";import{A as jo,C as Mo,D as No,E as Po,F as Fo,N as Io,O as Lo,S as Ro,T as zo,_ as Bo,a as Vo,b as Ho,c as Uo,d as Wo,f as Go,g as Ko,h as qo,i as Jo,j as Yo,k as Xo,l as Zo,m as Qo,n as $o,o as es,p as ts,r as ns,s as rs,t as is,u as as,v as os,w as ss,x as cs,y as ls}from"./fs-traced-Cq61rC8q.mjs";import{D as us,E as ds,S as fs,T as ps,a as ms,b as hs,l as gs,p as _s,r as L,s as vs,x as ys,y as bs}from"./logger-BZPV1wv8.mjs";import{a as xs,i as Ss,o as Cs,r as ws,s as Ts,t as Es}from"./git-handle-DDjBzdsL.mjs";import{S as Ds,a as Os,b as ks,c as As,d as js,f as Ms,g as Ns,h as Ps,i as Fs,l as Is,m as Ls,n as Rs,r as zs,x as Bs,y as Vs}from"./server-lock--0V-ESY4.mjs";import{t as Hs}from"./libesm-DzwC_yFw.mjs";import{n as Us,t as Ws}from"./build-DYQrG4v7.mjs";import{t as Gs}from"./yazl-BafwB467.mjs";import{t as Ks}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as qs,c as Js,d as Ys,f as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,o as nc,p as rc,r as ic,s as ac,t as oc,u as sc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as cc,B as lc,C as uc,D as dc,E as fc,F as pc,H as mc,I as hc,L as gc,M as _c,N as vc,O as yc,P as bc,S as xc,T as Sc,V as Cc,_ as wc,a as Tc,b as Ec,c as Dc,d as Oc,f as kc,g as Ac,h as jc,i as Mc,j as Nc,k as Pc,l as Fc,m as Ic,n as Lc,o as Rc,p as zc,r as Bc,s as Vc,t as Hc,u as Uc,v as Wc,w as Gc,x as Kc,y as qc,z as Jc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Yc,c as Xc,d as Zc,i as Qc,l as $c,n as el,o as tl,r as nl,s as rl,t as il,u as al}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as ol,r as sl,t as cl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as ll}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as ul}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as dl,t as fl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as pl,t as ml}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as hl,r as gl,t as _l}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as vl,t as yl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as bl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as xl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Sl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Cl}from"node:module";import{execFile as wl,execFileSync as Tl,spawn as El,spawnSync as Dl}from"node:child_process";import*as Ol from"node:path";import{basename as kl,delimiter as Al,dirname as R,extname as jl,isAbsolute as Ml,join as z,normalize as Nl,posix as Pl,relative as B,resolve as V,sep as Fl,win32 as Il}from"node:path";import{URLSearchParams as Ll,fileURLToPath as Rl,pathToFileURL as zl}from"node:url";import*as Bl from"node:fs";import{appendFileSync as Vl,chmodSync as Hl,closeSync as Ul,constants as Wl,createReadStream as Gl,createWriteStream as Kl,existsSync as H,lstatSync as ql,mkdirSync as Jl,mkdtempSync as Yl,openSync as Xl,readFile as Zl,readFileSync as U,readSync as Ql,readdirSync as $l,readlinkSync as eu,realpathSync as W,renameSync as tu,rmSync as nu,rmdirSync as ru,statSync as iu,unlinkSync as au,writeFileSync as ou,writeSync as su}from"node:fs";import{arch as cu,availableParallelism as lu,homedir as uu,hostname as du,platform as fu,tmpdir as pu}from"node:os";import{access as mu,chmod as hu,constants as gu,lstat as _u,readFile as vu,readdir as yu,realpath as bu,stat as xu,writeFile as Su}from"node:fs/promises";import{Readable as Cu,Transform as wu,Writable as Tu}from"node:stream";import Eu,{createHash as Du,randomUUID as Ou,webcrypto as ku}from"node:crypto";import Au from"crypto";import{Readable as ju}from"stream";import{Worker as Mu}from"node:worker_threads";import{monitorEventLoopDelay as Nu,performance as Pu}from"node:perf_hooks";import{createInterface as Fu}from"node:readline";import{pipeline as Iu}from"node:stream/promises";import{setImmediate as Lu,setTimeout as Ru}from"node:timers/promises";import{promisify as zu}from"node:util";import{lookup as Bu}from"node:dns/promises";import{request as Vu}from"node:http";import{request as cte}from"node:https";import{createBrotliDecompress as lte,createGunzip as Hu,createInflate as Uu}from"node:zlib";import{Http2ServerRequest as Wu,constants as Gu}from"http2";import{AsyncLocalStorage as ute}from"node:async_hooks";import{lookup as dte}from"node:dns";import fte from"node:tls";function pte(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),mte(n)}function mte(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Ku=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Ml(t)?t:V(this.gitDir,t))}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:td(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=U(z(t.path,`config`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Xu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!ed(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Ml(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=hte(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return td(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function qu(e){return Yu(V(e),``)}function Ju(e){let t=V(e),n=V(uu());if(t===n)return{kind:`absent`};let r=Yu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=R(i);if(e===i||e===n)return{kind:`absent`};let r=Yu(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Yu(e,t){let n=z(e,`.git`),r;try{r=iu(n)}catch(e){return $u(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Ku(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Ml(o)?o:V(e,o);try{if(!iu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Ku(`linked`,e,t,n,s)}}function Xu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Zu(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=Qu(i[1]);if(a.length>0)return a}return null}function Zu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Qu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function $u(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function ed(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function hte(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?ed(t[1])?{kind:`symbolic`,target:t[1]}:null:td(e)?{kind:`oid`,oid:e}:null}function td(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function gte(e){return`git-author-${nt(e.trim().toLowerCase())}`}const _te=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function nd(e){let t=Ju(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function rd(e){let t=nd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function id(e){let t=nd(e);switch(t.kind){case`directory`:return V(t.path,ad(t.projectSubPath));case`linked`:if(!H(t.path))throw new cd(t.gitPath,t.path);return V(t.path,ad(t.projectSubPath));case`malformed-pointer`:throw new cd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new ld(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function ad(e){return e===``?`ok`:`ok-${od(e)}`}function od(e){let t=e.split(Fl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=sd(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function sd(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var cd=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,n){let r=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${r}. Run \`git worktree prune\` from the source repo and try again.`,n),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},ld=class extends Error{gitPath;constructor(e,t){let n=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${n}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function ud(e){let t;try{t=id(e)}catch(e){if(e instanceof cd||e instanceof ld)return null;throw e}return H(V(t,`HEAD`))?t:null}function dd(e){return`refs/wip/${e}/`}function fd(e){if(!e)return[];let t=[];for(let n of e.split(`
2
2
  `)){let e=n.trim();if(e.startsWith(`ok-contributors: `))try{let n=JSON.parse(e.slice(17));if(typeof n==`object`&&n&&`id`in n&&typeof n.id==`string`&&`name`in n&&typeof n.name==`string`&&`docs`in n&&Array.isArray(n.docs)&&n.docs.every(e=>typeof e==`string`)&&(!(`colorSeed`in n)||typeof n.colorSeed==`string`)){let e=n;if(`summaries`in e){let t=e.summaries;(!Array.isArray(t)||!t.every(e=>typeof e==`string`))&&delete e.summaries}t.push(n)}}catch{}}return t}const pd=`ok-actor: `;function md(e){let{summaries:t,previous_paths:n,...r}=e,i={...r};return t&&t.length>0&&(i.summaries=t),n&&n.length>0&&(i.previous_paths=n),`${pd}${JSON.stringify(i)}`}function hd(e){if(e.v!==1||!(`display_name`in e)||typeof e.display_name!=`string`||!(`docs`in e)||!Array.isArray(e.docs))return null;let t=typeof e.principal==`string`?e.principal:null,n=typeof e.agent_session==`string`?e.agent_session:null,r;if(typeof e.writer_id==`string`&&e.writer_id.length>0)r=e.writer_id;else if(n)r=`agent-${n}`;else if(t)r=t;else switch(e.display_name){case`File System`:r=`file-system`;break;case`Git (upstream)`:r=`git-upstream`;break;default:r=`openknowledge-service`}let i=`summaries`in e&&Array.isArray(e.summaries)&&e.summaries.every(e=>typeof e==`string`)?e.summaries:void 0,a=gd(e);return{v:1,writer_id:r,principal:t,agent_session:n,agent_type:typeof e.agent_type==`string`?e.agent_type:null,client_name:typeof e.client_name==`string`?e.client_name:null,client_version:typeof e.client_version==`string`?e.client_version:null,label:typeof e.label==`string`?e.label:null,display_name:e.display_name,color_seed:typeof e.color_seed==`string`?e.color_seed:`unknown`,docs:e.docs.filter(e=>typeof e==`string`),...i&&i.length>0?{summaries:i}:{},...a&&a.length>0?{previous_paths:a}:{}}}function gd(e){if(!(`previous_paths`in e)||!Array.isArray(e.previous_paths))return;let t=[];for(let n of e.previous_paths){if(typeof n!=`object`||!n)continue;let e=n;typeof e.from!=`string`||typeof e.to!=`string`||t.push({from:e.from,to:e.to})}return t}function _d(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(pd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:hd(n)}return null}function vd(e){if(!e)return[];let t=[];for(let n of e.split(`
4
- `)){let e=n.trim();if(!e.startsWith(pd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=hd(r);i&&t.push(i)}return t}function vte(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function yd(e){let t=vd(e);return t.length>0?t.map(vte):fd(e)}function bd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function xd(e){return`reconcile: ${e}`}function Sd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function yte(e,t){return`park: ${e} -> ${t}`}function Cd(e,t){return`rename: ${e} -> ${t}`}function wd(e){return`checkpoint: ${e}`}function bte(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const xte=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Td(e){return e.replace(xte,` `)}function Ste(e,t){let n=Td(e);if(t.length===0)return n;if(t.length>=2)return`${n} (${t.length} edits)`;let[r]=t;if(r===void 0)return n;let i=Td(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function Ed(e){return _te.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Dd(e){let t=nd(e);if(t.kind!==`linked`)return V(e);try{let n=U(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function Od(e){return e.kind??`other`}function Cte(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var kd=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Od(t),i=Cte(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=Od(t);if(this.hasAllowAlways(e,r))return;let i=[...this.loadGrants(),{agentId:e,toolKind:r}];this.grants=i;try{let{tracedMkdir:e,tracedWriteFile:t}=await import(`./fs-traced-C9U9YUGm.mjs`);await e(z(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(U(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const Ad=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],jd={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Md=`acp-agents.json`,Nd=`acp-registry-cache.json`;function Pd(){let e=fu(),t=cu(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}function Fd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function Id(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Fd):null}var Ld=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=Id(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await import(`./fs-traced-C9U9YUGm.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Nd),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=Id(await vu(z(this.localDir,Nd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Rd(e,t){let n;try{n=await vu(z(e,Md),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Md} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${Md} entry`)}return i}const zd={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},Bd={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_connect:`mcp/connect`,mcp_message:`mcp/message`,mcp_disconnect:`mcp/disconnect`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},Vd={cancel_request:`$/cancel_request`},Hd=Symbol(`skippedItem`);function G(e,t){return e.catch(t)}function Ud(e,t){let n=e.catch(t);return O().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function Wd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Gd(e,t,n){return e.superRefine((e,r)=>{let i=Wd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Kd(e,t,n){return O().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return S}let o=a.data,s=Wd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function qd(e){return j(e.catch(Hd)).transform(e=>e.filter(e=>e!==Hd))}const Jd=I([N(),F()]).nullable(),Yd=F(),Xd=M({sessionId:Yd,path:F(),content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zd=M({sessionId:Yd,path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qd=F(),$d=I([k(`read`),k(`edit`),k(`delete`),k(`move`),k(`search`),k(`execute`),k(`think`),k(`fetch`),k(`switch_mode`),k(`other`)]),ef=I([k(`pending`),k(`in_progress`),k(`completed`),k(`failed`)]),tf=M({audience:G(qd(I([k(`assistant`),k(`user`)])).nullish(),()=>void 0),lastModified:G(F().nullish(),()=>void 0),priority:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wte=M({annotations:G(tf.nullish(),()=>void 0),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tte=M({annotations:G(tf.nullish(),()=>void 0),data:F(),mimeType:F(),uri:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ete=M({annotations:G(tf.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dte=M({annotations:G(tf.nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),mimeType:G(F().nullish(),()=>void 0),name:F(),size:G(N().nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ote=I([M({mimeType:G(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({blob:F(),mimeType:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})]),kte=M({annotations:G(tf.nullish(),()=>void 0),resource:Ote,_meta:G(E(F(),O()).nullish(),()=>void 0)}),nf=I([wte.and(M({type:k(`text`)})),Tte.and(M({type:k(`image`)})),Ete.and(M({type:k(`audio`)})),Dte.and(M({type:k(`resource_link`)})),kte.and(M({type:k(`resource`)}))]),Ate=M({content:nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),jte=M({path:F(),oldText:G(F().nullish(),()=>void 0),newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rf=F(),Mte=M({terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),af=I([Ate.and(M({type:k(`content`)})),jte.and(M({type:k(`diff`)})),Mte.and(M({type:k(`terminal`)}))]),of=M({path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sf=M({toolCallId:Qd,kind:G($d.nullish(),()=>void 0),status:G(ef.nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),content:G(qd(af).nullish(),()=>void 0),locations:G(qd(of).nullish(),()=>void 0),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cf=F(),Nte=I([k(`allow_once`),k(`allow_always`),k(`reject_once`),k(`reject_always`)]),lf=M({sessionId:Yd,toolCall:sf,options:j(M({optionId:cf,name:F(),kind:Nte,_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),uf=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),df=M({sessionId:Yd,command:F(),args:G(qd(F()).optional(),()=>[]),env:G(qd(uf).optional(),()=>[]),cwd:G(F().nullish(),()=>void 0),outputByteLimit:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ff=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),pf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),mf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),hf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),gf=M({sessionId:Yd,toolCallId:G(Qd.nullish(),()=>void 0)}),_f=M({requestId:Jd}),Pte=k(`object`),Fte=I([k(`email`),k(`uri`),k(`date`),k(`date-time`)]),vf=M({const:F(),title:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),yf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:Fte.nullish(),default:G(F().nullish(),()=>void 0),enum:j(F()).nullish(),oneOf:j(vf).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),default:G(D().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cf=M({enum:j(F()),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wf=M({anyOf:j(vf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tf=Kd(I([Cf.and(M({type:k(`string`)})),Gd(M({type:F()}),`type`,[`string`]),wf]),`type`,[`string`]),Ef=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minItems:N().nullish(),maxItems:N().nullish(),items:Tf,default:G(qd(F()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Df=Kd(I([yf.and(M({type:k(`string`)})),bf.and(M({type:k(`number`)})),xf.and(M({type:k(`integer`)})),Sf.and(M({type:k(`boolean`)})),Ef.and(M({type:k(`array`)})),Gd(M({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Of=M({type:G(Pte.optional().default(`object`),()=>`object`),title:G(F().nullish(),()=>void 0),properties:E(F(),Df).optional().default({}),required:j(F()).nullish(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),kf=_e(I([gf,_f]),M({requestedSchema:Of})),Af=F(),jf=_e(I([gf,_f]),M({elicitationId:Af,url:Oe()})),Mf=Kd(_e(I([kf.and(M({mode:k(`form`)})),jf.and(M({mode:k(`url`)})),Gd(_e(I([gf,_f]),M({mode:F()})),`mode`,[`form`,`url`])]),M({message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Nf=F(),Pf=M({serverId:Nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ff=F(),If=M({connectionId:Ff,method:F(),params:E(F(),O()).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lf=M({connectionId:Ff,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rf=O();M({id:Jd,method:F(),params:I([Xd,Zd,lf,df,ff,pf,mf,hf,Mf,Pf,If,Lf,Rf]).nullish()});const zf=oe().gte(0).lte(65535),Bf=M({image:G(D().optional().default(!1),()=>!1),audio:G(D().optional().default(!1),()=>!1),embeddedContext:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vf=M({http:G(D().optional().default(!1),()=>!1),sse:G(D().optional().default(!1),()=>!1),acp:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Uf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jf=M({list:G(Hf.nullish(),()=>void 0),delete:G(Uf.nullish(),()=>void 0),additionalDirectories:G(Wf.nullish(),()=>void 0),fork:G(Gf.nullish(),()=>void 0),resume:G(Kf.nullish(),()=>void 0),close:G(qf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yf=M({logout:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qf=M({syncKind:I([k(`full`),k(`incremental`)]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),$f=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ep=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),np=M({document:G(M({didOpen:G(Zf.nullish(),()=>void 0),didChange:G(Qf.nullish(),()=>void 0),didClose:G($f.nullish(),()=>void 0),didSave:G(ep.nullish(),()=>void 0),didFocus:G(tp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rp=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ip=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ap=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),op=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),cp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),lp=M({recentFiles:G(rp.nullish(),()=>void 0),relatedSnippets:G(ip.nullish(),()=>void 0),editHistory:G(ap.nullish(),()=>void 0),userActions:G(op.nullish(),()=>void 0),openFiles:G(sp.nullish(),()=>void 0),diagnostics:G(cp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),up=M({events:G(np.nullish(),()=>void 0),context:G(lp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dp=I([k(`utf-16`),k(`utf-32`),k(`utf-8`)]),fp=M({loadSession:G(D().optional().default(!1),()=>!1),promptCapabilities:G(Bf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:G(Vf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:G(Jf.optional().default({}),()=>({})),auth:G(Yf.optional().default({}),()=>({})),providers:G(Xf.nullish(),()=>void 0),nes:G(up.nullish(),()=>void 0),positionEncoding:G(dp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pp=F(),mp=M({name:F(),label:G(F().nullish(),()=>void 0),secret:G(D().optional().default(!0),()=>!0),optional:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hp=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),vars:Ud(qd(mp),()=>[]),link:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gp=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),args:G(qd(F()).optional(),()=>[]),env:G(E(F(),F()).optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_p=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vp=I([hp.and(M({type:k(`env_var`)})),gp.and(M({type:k(`terminal`)})),_p]),yp=M({name:F(),title:G(F().nullish(),()=>void 0),version:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bp=M({protocolVersion:zf,agentCapabilities:G(fp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:G(qd(vp).optional().default([]),()=>[]),agentInfo:G(yp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sp=F(),Cp=I([k(`anthropic`),k(`openai`),k(`azure`),k(`vertex`),k(`bedrock`),F()]),wp=M({apiType:Cp,baseUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tp=M({providers:j(M({providerId:Sp,supported:Ud(qd(Cp),()=>[]),required:D(),current:wp.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ep=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Op=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),kp=F(),Ap=M({currentModeId:kp,availableModes:Ud(qd(M({id:kp,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),jp=F(),Mp=I([k(`mode`),k(`model`),k(`model_config`),k(`thought_level`),F()]),Np=F(),Pp=M({value:Np,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fp=M({group:F(),name:F(),options:Ud(qd(Pp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ip=M({currentValue:Np,options:I([j(Pp),j(Fp)])}),Lp=M({currentValue:D()}),Rp=_e(I([Ip.and(M({type:k(`select`)})),Lp.and(M({type:k(`boolean`)}))]),M({id:jp,name:F(),description:G(F().nullish(),()=>void 0),category:G(Mp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),zp=M({sessionId:Yd,modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bp=M({modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vp=M({sessions:Ud(qd(M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),nextCursor:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Up=M({sessionId:Yd,modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wp=M({modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),qp=M({configOptions:Ud(qd(Rp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jp=M({stopReason:I([k(`end_turn`),k(`max_tokens`),k(`max_turn_requests`),k(`refusal`),k(`cancelled`)]),usage:G(M({totalTokens:N(),inputTokens:N(),outputTokens:N(),thoughtTokens:G(N().nullish(),()=>void 0),cachedReadTokens:G(N().nullish(),()=>void 0),cachedWriteTokens:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yp=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xp=F(),Zp=M({line:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qp=M({start:Zp,end:Zp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$p=M({range:Qp,newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),em=M({id:Xp,uri:F(),edits:j($p),cursorPosition:G(Zp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tm=M({id:Xp,uri:F(),position:Zp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),nm=M({id:Xp,uri:F(),position:Zp,newName:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rm=M({id:Xp,uri:F(),search:F(),replace:F(),isRegex:D().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),im=M({suggestions:j(I([em.and(M({kind:k(`edit`)})),tm.and(M({kind:k(`jump`)})),nm.and(M({kind:k(`rename`)})),rm.and(M({kind:k(`searchAndReplace`)}))])),_meta:G(E(F(),O()).nullish(),()=>void 0)}),am=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),om=O(),sm=O(),cm=M({code:I([k(-32700),k(-32600),k(-32601),k(-32602),k(-32603),k(-32800),k(-32e3),k(-32002),oe().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:G(O().optional(),()=>void 0)});I([M({id:Jd,result:I([bp,xp,Tp,Ep,Dp,Op,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,im,am,om,sm])}),M({id:Jd,error:cm})]);const lm=M({content:nf,messageId:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),um=M({toolCallId:Qd,title:F(),kind:G($d.optional(),()=>void 0),status:G(ef.optional(),()=>void 0),content:G(qd(af).optional(),()=>[]),locations:G(qd(of).optional(),()=>[]),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dm=I([k(`high`),k(`medium`),k(`low`)]),fm=I([k(`pending`),k(`in_progress`),k(`completed`)]),pm=M({content:F(),priority:dm,status:fm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),mm=M({entries:Ud(qd(pm),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hm=F(),gm=M({planId:hm,entries:Ud(qd(pm),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_m=M({planId:hm,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vm=M({planId:hm,content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ite=M({plan:I([gm.and(M({type:k(`items`)})),_m.and(M({type:k(`file`)})),vm.and(M({type:k(`markdown`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lte=M({planId:hm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rte=M({hint:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zte=M({availableCommands:Ud(qd(M({name:F(),description:F(),input:G(Rte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bte=M({currentModeId:kp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vte=M({configOptions:Ud(qd(Rp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hte=M({title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ute=M({amount:N(),currency:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wte=M({used:N(),size:N(),cost:G(Ute.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ym=M({sessionId:Yd,update:I([lm.and(M({sessionUpdate:k(`user_message_chunk`)})),lm.and(M({sessionUpdate:k(`agent_message_chunk`)})),lm.and(M({sessionUpdate:k(`agent_thought_chunk`)})),um.and(M({sessionUpdate:k(`tool_call`)})),sf.and(M({sessionUpdate:k(`tool_call_update`)})),mm.and(M({sessionUpdate:k(`plan`)})),Ite.and(M({sessionUpdate:k(`plan_update`)})),Lte.and(M({sessionUpdate:k(`plan_removed`)})),zte.and(M({sessionUpdate:k(`available_commands_update`)})),Bte.and(M({sessionUpdate:k(`current_mode_update`)})),Vte.and(M({sessionUpdate:k(`config_option_update`)})),Hte.and(M({sessionUpdate:k(`session_info_update`)})),Wte.and(M({sessionUpdate:k(`usage_update`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bm=M({elicitationId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xm=M({connectionId:Ff,method:F(),params:G(E(F(),O()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sm=O();M({method:F(),params:I([ym,bm,xm,Sm]).nullish()});const Gte=M({readTextFile:G(D().optional().default(!1),()=>!1),writeTextFile:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kte=M({configOptions:G(M({boolean:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jte=M({terminal:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zte=M({form:G(Yte.nullish(),()=>void 0),url:G(Xte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),$te=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tne=M({jump:G(Qte.nullish(),()=>void 0),rename:G($te.nullish(),()=>void 0),searchAndReplace:G(ene.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cm=M({protocolVersion:zf,clientCapabilities:G(M({fs:G(Gte.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:G(D().optional().default(!1),()=>!1),session:G(Kte.nullish(),()=>void 0),plan:G(qte.nullish(),()=>void 0),auth:G(Jte.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:G(Zte.nullish(),()=>void 0),nes:G(tne.nullish(),()=>void 0),positionEncodings:G(qd(dp).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:G(yp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wm=M({methodId:pp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Em=M({providerId:Sp,apiType:Cp,baseUrl:F(),headers:E(F(),F()).optional(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dm=M({providerId:Sp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Om=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),km=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),nne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ine=M({name:F(),serverId:Nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),ane=M({name:F(),command:F(),args:j(F()),env:j(uf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Am=I([nne.and(M({type:k(`http`)})),rne.and(M({type:k(`sse`)})),ine.and(M({type:k(`acp`)})),ane]),jm=M({cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:Ud(qd(Am),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mm=M({mcpServers:Ud(qd(Am),()=>[]),cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Nm=M({cwd:F().nullish(),cursor:F().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fm=M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:G(qd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Im=M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:G(qd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rm=M({sessionId:Yd,modeId:kp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),zm=_e(I([M({value:D(),type:k(`boolean`)}),M({value:Np})]),M({sessionId:Yd,configId:jp,_meta:G(E(F(),O()).nullish(),()=>void 0)})),Bm=M({sessionId:Yd,prompt:j(nf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),one=M({uri:F(),name:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sne=M({name:F(),owner:F(),remoteUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vm=M({workspaceUri:G(F().nullish(),()=>void 0),workspaceFolders:j(one).nullish(),repository:G(sne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cne=I([k(`automatic`),k(`diagnostic`),k(`manual`)]),lne=M({uri:F(),languageId:F(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),une=M({startLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dne=M({uri:F(),excerpts:j(une),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fne=M({uri:F(),diff:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pne=M({action:F(),uri:F(),position:Zp,timestampMs:N(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mne=M({uri:F(),languageId:F(),visibleRange:G(Qp.nullish(),()=>void 0),lastFocusedMs:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hne=I([k(`error`),k(`warning`),k(`information`),k(`hint`)]),gne=M({uri:F(),range:Qp,severity:hne,message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_ne=M({recentFiles:j(lne).nullish(),relatedSnippets:j(dne).nullish(),editHistory:j(fne).nullish(),userActions:j(pne).nullish(),openFiles:j(mne).nullish(),diagnostics:j(gne).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hm=M({sessionId:Yd,uri:F(),version:N(),position:Zp,selection:Qp.nullish(),triggerKind:cne,context:_ne.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Um=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)});M({id:Jd,method:F(),params:I([Cm,wm,Tm,Em,Dm,Om,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,If,Rf]).nullish()});const vne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),yne=M({content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bne=M({optionId:cf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xne=M({outcome:I([M({outcome:k(`cancelled`)}),bne.and(M({outcome:k(`selected`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sne=M({terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wne=M({output:F(),truncated:D(),exitStatus:G(Cne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ene=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),One=I([F(),N(),N(),D(),j(F())]),Wm=M({content:E(F(),One).nullish()});I([M({id:Jd,result:I([vne,yne,xne,Sne,wne,Tne,Ene,Dne,Kd(_e(I([Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)}),Gd(M({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:G(E(F(),O()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Ff,_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),sm,om])}),M({id:Jd,error:cm})]);const Gm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Km=M({sessionId:Yd,uri:F(),languageId:F(),version:N(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),kne=M({range:Qp.nullish(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qm=M({sessionId:Yd,uri:F(),version:N(),contentChanges:Ud(qd(kne),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jm=M({sessionId:Yd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ym=M({sessionId:Yd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xm=M({sessionId:Yd,uri:F(),version:N(),position:Zp,visibleRange:Qp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zm=M({sessionId:Yd,id:Xp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qm=M({sessionId:Yd,id:Xp,reason:G(I([k(`rejected`),k(`ignored`),k(`replaced`),k(`cancelled`)]).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)});M({method:F(),params:I([Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,xm,Sm]).nullish()}),M({requestId:Jd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),kf.and(M({mode:k(`form`)})).and(M({message:F()})),jf.and(M({mode:k(`url`)})).and(M({message:F()})),I([gf,_f]).and(M({message:F()})),yf.and(M({type:k(`string`)})),bf.and(M({type:k(`number`)})),xf.and(M({type:k(`integer`)})),Sf.and(M({type:k(`boolean`)})),Ef.and(M({type:k(`array`)})),Cf.and(M({type:k(`string`)})),Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)});const $m=`$/cancel_request`;function eh(e){return typeof e==`object`&&!!e}function Ane(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function jne(e){if(!(!eh(e)||!Ane(e.requestId)))return e.requestId}const th={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function nh(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Mne(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Nne(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function rh(e){if(e instanceof oh)return e.toResult();if(Nne(e))return oh.invalidParams(e.format()).toResult();let t=Mne(e);try{return oh.internalError(t?JSON.parse(t):{}).toResult()}catch{return oh.internalError({details:t}).toResult()}}function Pne(e){return e instanceof oh&&e.code===-32800?e:oh.requestCancelled(e)}function Fne(e,t){let n=Ine(e,t);return n?n.toResult():rh(e)}function Ine(e,t){if(!(!t.aborted||!Lne(e)))return Pne(t.reason)}function Lne(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Rne=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof oh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?nh(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},ih=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},zne=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ah=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new zne(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)]);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a])}static builder(){return new Bne}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new ih(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return nh(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification($m,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?nh(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return th.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;t&&this.receiveMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!eh(e)){console.error(`Invalid message`,{message:e});return}`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(oh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Fne(n,t.responder.signal));else{let t=rh(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;return this.incomingRequests.set(e.id,t),{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:new Rne(e.id,t=>this.sendMessage({jsonrpc:`2.0`,id:e.id,...t}),t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)})}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),`result`in e)t.resolve(e.result);else if(`error`in e&&eh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new oh(n,r,i))}else t.reject(oh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==$m)return;let t=jne(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(oh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?nh(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Bne=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??th.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?th.no(r):await n(t(r.params),r.responder,i)??th.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?th.no(r):await n(t(r.params),i)??th.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new ah(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},oh=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}},Vne=class{#e=[];push(e){let t=[],n=0,r=e.indexOf(10,n);for(;r!==-1;)t.push(this.#t(e.subarray(n,r))),n=r+1,r=e.indexOf(10,n);return n<e.byteLength&&this.#e.push(n===0?e:new Uint8Array(e.subarray(n))),t}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array)}#t(e){if(this.#e.length===0)return e;let t=e.byteLength;for(let e of this.#e)t+=e.byteLength;let n=new Uint8Array(t),r=0;for(let e of this.#e)n.set(e,r),r+=e.byteLength;return n.set(e,r),this.#e=[],n}};function Hne(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Vne,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);eh(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
4
+ `)){let e=n.trim();if(!e.startsWith(pd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=hd(r);i&&t.push(i)}return t}function vte(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function yd(e){let t=vd(e);return t.length>0?t.map(vte):fd(e)}function bd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function xd(e){return`reconcile: ${e}`}function Sd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function yte(e,t){return`park: ${e} -> ${t}`}function Cd(e,t){return`rename: ${e} -> ${t}`}function wd(e){return`checkpoint: ${e}`}function bte(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const xte=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Td(e){return e.replace(xte,` `)}function Ste(e,t){let n=Td(e);if(t.length===0)return n;if(t.length>=2)return`${n} (${t.length} edits)`;let[r]=t;if(r===void 0)return n;let i=Td(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function Ed(e){return _te.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Dd(e){let t=nd(e);if(t.kind!==`linked`)return V(e);try{let n=U(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function Od(e){return e.kind??`other`}function Cte(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var kd=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Od(t),i=Cte(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=Od(t);if(this.hasAllowAlways(e,r))return;let i=[...this.loadGrants(),{agentId:e,toolKind:r}];this.grants=i;try{let{tracedMkdir:e,tracedWriteFile:t}=await import(`./fs-traced-WMTb98_i.mjs`);await e(z(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(U(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const Ad=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],jd={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Md=`acp-agents.json`,Nd=`acp-registry-cache.json`;function Pd(){let e=fu(),t=cu(),n=e===`darwin`?`darwin`:e===`linux`?`linux`:e===`win32`?`windows`:null,r=t===`arm64`?`aarch64`:t===`x64`?`x86_64`:null;return n===null||r===null?null:`${n}-${r}`}function Fd(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.id==`string`&&t.id.length>0&&typeof t.name==`string`&&typeof t.version==`string`&&typeof t.distribution==`object`&&t.distribution!==null}function Id(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Fd):null}var Ld=class{localDir;log;ttlMs;fetchImpl;memory=null;inflight=null;constructor(e){this.localDir=e.localDir,this.log=e.log,this.ttlMs=e.ttlMs??36e5,this.fetchImpl=e.fetchImpl??fetch}async getCatalog(){return this.memory!==null&&Date.now()-this.memory.fetchedAt<this.ttlMs&&!this.memory.stale?this.memory:(this.inflight===null&&(this.inflight=this.refresh().finally(()=>{this.inflight=null})),this.inflight)}async getAgent(e){let{agents:t}=await this.getCatalog();return t.find(t=>t.id===e)}async refresh(){try{let e=await this.fetchImpl(`https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json`,{signal:AbortSignal.timeout(15e3)});if(!e.ok)throw Error(`registry fetch failed: HTTP ${e.status}`);let t=await e.text(),n=Id(t);if(n===null)throw Error(`registry payload did not parse as a catalog`);this.memory={agents:n,fetchedAt:Date.now(),stale:!1};try{let{tracedMkdir:e,tracedWriteFile:n}=await import(`./fs-traced-WMTb98_i.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Nd),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=Id(await vu(z(this.localDir,Nd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Rd(e,t){let n;try{n=await vu(z(e,Md),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Md} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${Md} entry`)}return i}const zd={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},Bd={session_request_permission:`session/request_permission`,session_update:`session/update`,fs_write_text_file:`fs/write_text_file`,fs_read_text_file:`fs/read_text_file`,terminal_create:`terminal/create`,terminal_output:`terminal/output`,terminal_release:`terminal/release`,terminal_wait_for_exit:`terminal/wait_for_exit`,terminal_kill:`terminal/kill`,mcp_connect:`mcp/connect`,mcp_message:`mcp/message`,mcp_disconnect:`mcp/disconnect`,elicitation_create:`elicitation/create`,elicitation_complete:`elicitation/complete`},Vd={cancel_request:`$/cancel_request`},Hd=Symbol(`skippedItem`);function G(e,t){return e.catch(t)}function Ud(e,t){let n=e.catch(t);return O().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function Wd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Gd(e,t,n){return e.superRefine((e,r)=>{let i=Wd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Kd(e,t,n){return O().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return S}let o=a.data,s=Wd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function qd(e){return j(e.catch(Hd)).transform(e=>e.filter(e=>e!==Hd))}const Jd=I([N(),F()]).nullable(),Yd=F(),Xd=M({sessionId:Yd,path:F(),content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zd=M({sessionId:Yd,path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qd=F(),$d=I([k(`read`),k(`edit`),k(`delete`),k(`move`),k(`search`),k(`execute`),k(`think`),k(`fetch`),k(`switch_mode`),k(`other`)]),ef=I([k(`pending`),k(`in_progress`),k(`completed`),k(`failed`)]),tf=M({audience:G(qd(I([k(`assistant`),k(`user`)])).nullish(),()=>void 0),lastModified:G(F().nullish(),()=>void 0),priority:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wte=M({annotations:G(tf.nullish(),()=>void 0),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tte=M({annotations:G(tf.nullish(),()=>void 0),data:F(),mimeType:F(),uri:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ete=M({annotations:G(tf.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dte=M({annotations:G(tf.nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),mimeType:G(F().nullish(),()=>void 0),name:F(),size:G(N().nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ote=I([M({mimeType:G(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({blob:F(),mimeType:G(F().nullish(),()=>void 0),uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})]),kte=M({annotations:G(tf.nullish(),()=>void 0),resource:Ote,_meta:G(E(F(),O()).nullish(),()=>void 0)}),nf=I([wte.and(M({type:k(`text`)})),Tte.and(M({type:k(`image`)})),Ete.and(M({type:k(`audio`)})),Dte.and(M({type:k(`resource_link`)})),kte.and(M({type:k(`resource`)}))]),Ate=M({content:nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),jte=M({path:F(),oldText:G(F().nullish(),()=>void 0),newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rf=F(),Mte=M({terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),af=I([Ate.and(M({type:k(`content`)})),jte.and(M({type:k(`diff`)})),Mte.and(M({type:k(`terminal`)}))]),of=M({path:F(),line:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sf=M({toolCallId:Qd,kind:G($d.nullish(),()=>void 0),status:G(ef.nullish(),()=>void 0),title:G(F().nullish(),()=>void 0),content:G(qd(af).nullish(),()=>void 0),locations:G(qd(of).nullish(),()=>void 0),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cf=F(),Nte=I([k(`allow_once`),k(`allow_always`),k(`reject_once`),k(`reject_always`)]),lf=M({sessionId:Yd,toolCall:sf,options:j(M({optionId:cf,name:F(),kind:Nte,_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),uf=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),df=M({sessionId:Yd,command:F(),args:G(qd(F()).optional(),()=>[]),env:G(qd(uf).optional(),()=>[]),cwd:G(F().nullish(),()=>void 0),outputByteLimit:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ff=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),pf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),mf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),hf=M({sessionId:Yd,terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),gf=M({sessionId:Yd,toolCallId:G(Qd.nullish(),()=>void 0)}),_f=M({requestId:Jd}),Pte=k(`object`),Fte=I([k(`email`),k(`uri`),k(`date`),k(`date-time`)]),vf=M({const:F(),title:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),yf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:Fte.nullish(),default:G(F().nullish(),()=>void 0),enum:j(F()).nullish(),oneOf:j(vf).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sf=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),default:G(D().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cf=M({enum:j(F()),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wf=M({anyOf:j(vf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tf=Kd(I([Cf.and(M({type:k(`string`)})),Gd(M({type:F()}),`type`,[`string`]),wf]),`type`,[`string`]),Ef=M({title:G(F().nullish(),()=>void 0),description:G(F().nullish(),()=>void 0),minItems:N().nullish(),maxItems:N().nullish(),items:Tf,default:G(qd(F()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Df=Kd(I([yf.and(M({type:k(`string`)})),bf.and(M({type:k(`number`)})),xf.and(M({type:k(`integer`)})),Sf.and(M({type:k(`boolean`)})),Ef.and(M({type:k(`array`)})),Gd(M({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Of=M({type:G(Pte.optional().default(`object`),()=>`object`),title:G(F().nullish(),()=>void 0),properties:E(F(),Df).optional().default({}),required:j(F()).nullish(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),kf=_e(I([gf,_f]),M({requestedSchema:Of})),Af=F(),jf=_e(I([gf,_f]),M({elicitationId:Af,url:Oe()})),Mf=Kd(_e(I([kf.and(M({mode:k(`form`)})),jf.and(M({mode:k(`url`)})),Gd(_e(I([gf,_f]),M({mode:F()})),`mode`,[`form`,`url`])]),M({message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Nf=F(),Pf=M({serverId:Nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ff=F(),If=M({connectionId:Ff,method:F(),params:E(F(),O()).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lf=M({connectionId:Ff,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rf=O();M({id:Jd,method:F(),params:I([Xd,Zd,lf,df,ff,pf,mf,hf,Mf,Pf,If,Lf,Rf]).nullish()});const zf=oe().gte(0).lte(65535),Bf=M({image:G(D().optional().default(!1),()=>!1),audio:G(D().optional().default(!1),()=>!1),embeddedContext:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vf=M({http:G(D().optional().default(!1),()=>!1),sse:G(D().optional().default(!1),()=>!1),acp:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Uf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),qf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jf=M({list:G(Hf.nullish(),()=>void 0),delete:G(Uf.nullish(),()=>void 0),additionalDirectories:G(Wf.nullish(),()=>void 0),fork:G(Gf.nullish(),()=>void 0),resume:G(Kf.nullish(),()=>void 0),close:G(qf.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yf=M({logout:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zf=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qf=M({syncKind:I([k(`full`),k(`incremental`)]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),$f=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ep=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),np=M({document:G(M({didOpen:G(Zf.nullish(),()=>void 0),didChange:G(Qf.nullish(),()=>void 0),didClose:G($f.nullish(),()=>void 0),didSave:G(ep.nullish(),()=>void 0),didFocus:G(tp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rp=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ip=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ap=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),op=M({maxCount:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),cp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),lp=M({recentFiles:G(rp.nullish(),()=>void 0),relatedSnippets:G(ip.nullish(),()=>void 0),editHistory:G(ap.nullish(),()=>void 0),userActions:G(op.nullish(),()=>void 0),openFiles:G(sp.nullish(),()=>void 0),diagnostics:G(cp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),up=M({events:G(np.nullish(),()=>void 0),context:G(lp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dp=I([k(`utf-16`),k(`utf-32`),k(`utf-8`)]),fp=M({loadSession:G(D().optional().default(!1),()=>!1),promptCapabilities:G(Bf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:G(Vf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:G(Jf.optional().default({}),()=>({})),auth:G(Yf.optional().default({}),()=>({})),providers:G(Xf.nullish(),()=>void 0),nes:G(up.nullish(),()=>void 0),positionEncoding:G(dp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pp=F(),mp=M({name:F(),label:G(F().nullish(),()=>void 0),secret:G(D().optional().default(!0),()=>!0),optional:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hp=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),vars:Ud(qd(mp),()=>[]),link:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),gp=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),args:G(qd(F()).optional(),()=>[]),env:G(E(F(),F()).optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_p=M({id:pp,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vp=I([hp.and(M({type:k(`env_var`)})),gp.and(M({type:k(`terminal`)})),_p]),yp=M({name:F(),title:G(F().nullish(),()=>void 0),version:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bp=M({protocolVersion:zf,agentCapabilities:G(fp.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:G(qd(vp).optional().default([]),()=>[]),agentInfo:G(yp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),xp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sp=F(),Cp=I([k(`anthropic`),k(`openai`),k(`azure`),k(`vertex`),k(`bedrock`),F()]),wp=M({apiType:Cp,baseUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tp=M({providers:j(M({providerId:Sp,supported:Ud(qd(Cp),()=>[]),required:D(),current:wp.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)})),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ep=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Op=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),kp=F(),Ap=M({currentModeId:kp,availableModes:Ud(qd(M({id:kp,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),jp=F(),Mp=I([k(`mode`),k(`model`),k(`model_config`),k(`thought_level`),F()]),Np=F(),Pp=M({value:Np,name:F(),description:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fp=M({group:F(),name:F(),options:Ud(qd(Pp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ip=M({currentValue:Np,options:I([j(Pp),j(Fp)])}),Lp=M({currentValue:D()}),Rp=_e(I([Ip.and(M({type:k(`select`)})),Lp.and(M({type:k(`boolean`)}))]),M({id:jp,name:F(),description:G(F().nullish(),()=>void 0),category:G(Mp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),zp=M({sessionId:Yd,modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bp=M({modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vp=M({sessions:Ud(qd(M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),nextCursor:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Up=M({sessionId:Yd,modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wp=M({modes:G(Ap.nullish(),()=>void 0),configOptions:G(qd(Rp).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Gp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kp=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),qp=M({configOptions:Ud(qd(Rp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jp=M({stopReason:I([k(`end_turn`),k(`max_tokens`),k(`max_turn_requests`),k(`refusal`),k(`cancelled`)]),usage:G(M({totalTokens:N(),inputTokens:N(),outputTokens:N(),thoughtTokens:G(N().nullish(),()=>void 0),cachedReadTokens:G(N().nullish(),()=>void 0),cachedWriteTokens:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yp=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xp=F(),Zp=M({line:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qp=M({start:Zp,end:Zp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),$p=M({range:Qp,newText:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),em=M({id:Xp,uri:F(),edits:j($p),cursorPosition:G(Zp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),tm=M({id:Xp,uri:F(),position:Zp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),nm=M({id:Xp,uri:F(),position:Zp,newName:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rm=M({id:Xp,uri:F(),search:F(),replace:F(),isRegex:D().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),im=M({suggestions:j(I([em.and(M({kind:k(`edit`)})),tm.and(M({kind:k(`jump`)})),nm.and(M({kind:k(`rename`)})),rm.and(M({kind:k(`searchAndReplace`)}))])),_meta:G(E(F(),O()).nullish(),()=>void 0)}),am=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),om=O(),sm=O(),cm=M({code:I([k(-32700),k(-32600),k(-32601),k(-32602),k(-32603),k(-32800),k(-32e3),k(-32002),oe().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:G(O().optional(),()=>void 0)});I([M({id:Jd,result:I([bp,xp,Tp,Ep,Dp,Op,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,im,am,om,sm])}),M({id:Jd,error:cm})]);const lm=M({content:nf,messageId:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),um=M({toolCallId:Qd,title:F(),kind:G($d.optional(),()=>void 0),status:G(ef.optional(),()=>void 0),content:G(qd(af).optional(),()=>[]),locations:G(qd(of).optional(),()=>[]),rawInput:G(O().optional(),()=>void 0),rawOutput:G(O().optional(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dm=I([k(`high`),k(`medium`),k(`low`)]),fm=I([k(`pending`),k(`in_progress`),k(`completed`)]),pm=M({content:F(),priority:dm,status:fm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),mm=M({entries:Ud(qd(pm),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hm=F(),gm=M({planId:hm,entries:Ud(qd(pm),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_m=M({planId:hm,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),vm=M({planId:hm,content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ite=M({plan:I([gm.and(M({type:k(`items`)})),_m.and(M({type:k(`file`)})),vm.and(M({type:k(`markdown`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lte=M({planId:hm,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rte=M({hint:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),zte=M({availableCommands:Ud(qd(M({name:F(),description:F(),input:G(Rte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)})),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Bte=M({currentModeId:kp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vte=M({configOptions:Ud(qd(Rp),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hte=M({title:G(F().nullish(),()=>void 0),updatedAt:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ute=M({amount:N(),currency:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Wte=M({used:N(),size:N(),cost:G(Ute.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ym=M({sessionId:Yd,update:I([lm.and(M({sessionUpdate:k(`user_message_chunk`)})),lm.and(M({sessionUpdate:k(`agent_message_chunk`)})),lm.and(M({sessionUpdate:k(`agent_thought_chunk`)})),um.and(M({sessionUpdate:k(`tool_call`)})),sf.and(M({sessionUpdate:k(`tool_call_update`)})),mm.and(M({sessionUpdate:k(`plan`)})),Ite.and(M({sessionUpdate:k(`plan_update`)})),Lte.and(M({sessionUpdate:k(`plan_removed`)})),zte.and(M({sessionUpdate:k(`available_commands_update`)})),Bte.and(M({sessionUpdate:k(`current_mode_update`)})),Vte.and(M({sessionUpdate:k(`config_option_update`)})),Hte.and(M({sessionUpdate:k(`session_info_update`)})),Wte.and(M({sessionUpdate:k(`usage_update`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bm=M({elicitationId:Af,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xm=M({connectionId:Ff,method:F(),params:G(E(F(),O()).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sm=O();M({method:F(),params:I([ym,bm,xm,Sm]).nullish()});const Gte=M({readTextFile:G(D().optional().default(!1),()=>!1),writeTextFile:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Kte=M({configOptions:G(M({boolean:G(M({_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jte=M({terminal:G(D().optional().default(!1),()=>!1),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Yte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zte=M({form:G(Yte.nullish(),()=>void 0),url:G(Xte.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qte=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),$te=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),ene=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),tne=M({jump:G(Qte.nullish(),()=>void 0),rename:G($te.nullish(),()=>void 0),searchAndReplace:G(ene.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cm=M({protocolVersion:zf,clientCapabilities:G(M({fs:G(Gte.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:G(D().optional().default(!1),()=>!1),session:G(Kte.nullish(),()=>void 0),plan:G(qte.nullish(),()=>void 0),auth:G(Jte.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:G(Zte.nullish(),()=>void 0),nes:G(tne.nullish(),()=>void 0),positionEncodings:G(qd(dp).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:G(yp.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wm=M({methodId:pp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tm=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Em=M({providerId:Sp,apiType:Cp,baseUrl:F(),headers:E(F(),F()).optional(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dm=M({providerId:Sp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Om=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),km=M({name:F(),value:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),nne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),rne=M({name:F(),url:F(),headers:j(km),_meta:G(E(F(),O()).nullish(),()=>void 0)}),ine=M({name:F(),serverId:Nf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),ane=M({name:F(),command:F(),args:j(F()),env:j(uf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Am=I([nne.and(M({type:k(`http`)})),rne.and(M({type:k(`sse`)})),ine.and(M({type:k(`acp`)})),ane]),jm=M({cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:Ud(qd(Am),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Mm=M({mcpServers:Ud(qd(Am),()=>[]),cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Nm=M({cwd:F().nullish(),cursor:F().nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Pm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Fm=M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:G(qd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Im=M({sessionId:Yd,cwd:F(),additionalDirectories:G(qd(F()).optional(),()=>[]),mcpServers:G(qd(Am).optional(),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Lm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Rm=M({sessionId:Yd,modeId:kp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),zm=_e(I([M({value:D(),type:k(`boolean`)}),M({value:Np})]),M({sessionId:Yd,configId:jp,_meta:G(E(F(),O()).nullish(),()=>void 0)})),Bm=M({sessionId:Yd,prompt:j(nf),_meta:G(E(F(),O()).nullish(),()=>void 0)}),one=M({uri:F(),name:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),sne=M({name:F(),owner:F(),remoteUrl:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Vm=M({workspaceUri:G(F().nullish(),()=>void 0),workspaceFolders:j(one).nullish(),repository:G(sne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),cne=I([k(`automatic`),k(`diagnostic`),k(`manual`)]),lne=M({uri:F(),languageId:F(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),une=M({startLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),dne=M({uri:F(),excerpts:j(une),_meta:G(E(F(),O()).nullish(),()=>void 0)}),fne=M({uri:F(),diff:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),pne=M({action:F(),uri:F(),position:Zp,timestampMs:N(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),mne=M({uri:F(),languageId:F(),visibleRange:G(Qp.nullish(),()=>void 0),lastFocusedMs:G(N().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),hne=I([k(`error`),k(`warning`),k(`information`),k(`hint`)]),gne=M({uri:F(),range:Qp,severity:hne,message:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),_ne=M({recentFiles:j(lne).nullish(),relatedSnippets:j(dne).nullish(),editHistory:j(fne).nullish(),userActions:j(pne).nullish(),openFiles:j(mne).nullish(),diagnostics:j(gne).nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Hm=M({sessionId:Yd,uri:F(),version:N(),position:Zp,selection:Qp.nullish(),triggerKind:cne,context:_ne.nullish(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Um=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)});M({id:Jd,method:F(),params:I([Cm,wm,Tm,Em,Dm,Om,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,If,Rf]).nullish()});const vne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),yne=M({content:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),bne=M({optionId:cf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),xne=M({outcome:I([M({outcome:k(`cancelled`)}),bne.and(M({outcome:k(`selected`)}))]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Sne=M({terminalId:rf,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Cne=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),wne=M({output:F(),truncated:D(),exitStatus:G(Cne.nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Tne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ene=M({exitCode:G(oe().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(F().nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Dne=M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),One=I([F(),N(),N(),D(),j(F())]),Wm=M({content:E(F(),One).nullish()});I([M({id:Jd,result:I([vne,yne,xne,Sne,wne,Tne,Ene,Dne,Kd(_e(I([Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)}),Gd(M({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),M({_meta:G(E(F(),O()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),M({connectionId:Ff,_meta:G(E(F(),O()).nullish(),()=>void 0)}),M({_meta:G(E(F(),O()).nullish(),()=>void 0)}),sm,om])}),M({id:Jd,error:cm})]);const Gm=M({sessionId:Yd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Km=M({sessionId:Yd,uri:F(),languageId:F(),version:N(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),kne=M({range:Qp.nullish(),text:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),qm=M({sessionId:Yd,uri:F(),version:N(),contentChanges:Ud(qd(kne),()=>[]),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Jm=M({sessionId:Yd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Ym=M({sessionId:Yd,uri:F(),_meta:G(E(F(),O()).nullish(),()=>void 0)}),Xm=M({sessionId:Yd,uri:F(),version:N(),position:Zp,visibleRange:Qp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Zm=M({sessionId:Yd,id:Xp,_meta:G(E(F(),O()).nullish(),()=>void 0)}),Qm=M({sessionId:Yd,id:Xp,reason:G(I([k(`rejected`),k(`ignored`),k(`replaced`),k(`cancelled`)]).nullish(),()=>void 0),_meta:G(E(F(),O()).nullish(),()=>void 0)});M({method:F(),params:I([Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,xm,Sm]).nullish()}),M({requestId:Jd,_meta:G(E(F(),O()).nullish(),()=>void 0)}),kf.and(M({mode:k(`form`)})).and(M({message:F()})),jf.and(M({mode:k(`url`)})).and(M({message:F()})),I([gf,_f]).and(M({message:F()})),yf.and(M({type:k(`string`)})),bf.and(M({type:k(`number`)})),xf.and(M({type:k(`integer`)})),Sf.and(M({type:k(`boolean`)})),Ef.and(M({type:k(`array`)})),Cf.and(M({type:k(`string`)})),Wm.and(M({action:k(`accept`)})),M({action:k(`decline`)}),M({action:k(`cancel`)});const $m=`$/cancel_request`;function eh(e){return typeof e==`object`&&!!e}function Ane(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function jne(e){if(!(!eh(e)||!Ane(e.requestId)))return e.requestId}const th={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function nh(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Mne(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Nne(e){return typeof e==`object`&&!!e&&`name`in e&&e.name===`ZodError`&&`issues`in e&&Array.isArray(e.issues)&&`format`in e&&typeof e.format==`function`}function rh(e){if(e instanceof oh)return e.toResult();if(Nne(e))return oh.invalidParams(e.format()).toResult();let t=Mne(e);try{return oh.internalError(t?JSON.parse(t):{}).toResult()}catch{return oh.internalError({details:t}).toResult()}}function Pne(e){return e instanceof oh&&e.code===-32800?e:oh.requestCancelled(e)}function Fne(e,t){let n=Ine(e,t);return n?n.toResult():rh(e)}function Ine(e,t){if(!(!t.aborted||!Lne(e)))return Pne(t.reason)}function Lne(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Rne=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof oh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?nh(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},ih=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},zne=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ah=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new zne(this);receiveReader;constructor(e,t,n,r){if(typeof e==`function`){let i=e,a=t,o=n;this.initialize(o,[...r?.handlers??[],this.legacyHandler(i,a)]);return}let i=e,a=t,o=n;this.initialize(i,[...o?.handlers??[],...a])}static builder(){return new Bne}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let e of this.retryQueue.splice(0))this.processIncomingMessage(e).catch(e=>this.close(e));return new ih(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return nh(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification($m,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?nh(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return th.yes()}}}async receive(){let e;try{let e=this.stream.readable.getReader();this.receiveReader=e;try{for(;!this.abortController.signal.aborted;){let{value:t,done:n}=await e.read();if(this.abortController.signal.aborted||n)break;t&&this.receiveMessage(t)}}finally{this.receiveReader===e&&(this.receiveReader=void 0),e.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveMessage(e){if(!this.abortController.signal.aborted){if(!eh(e)){console.error(`Invalid message`,{message:e});return}`method`in e?(`id`in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e)).catch(e=>this.close(e))):`id`in e?this.handleResponse(e):console.error(`Invalid message`,{message:e})}}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let e of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let r=await e.handleMessage(t,this.context)??{handled:!0};if(r.handled)return;t=r.message??t,n||=!!r.retry}n?this.retryQueue.push(t):t.kind===`request`&&await t.responder.respondWithError(oh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Fne(n,t.responder.signal));else{let t=rh(n);`error`in t&&console.error(`Error handling notification`,e.raw,t.error)}}}toIncomingMessage(e){if(`id`in e){let t=new AbortController;return this.incomingRequests.set(e.id,t),{kind:`request`,method:e.method,params:e.params,raw:e,signal:t.signal,responder:new Rne(e.id,t=>this.sendMessage({jsonrpc:`2.0`,id:e.id,...t}),t.signal,()=>{this.incomingRequests.get(e.id)===t&&this.incomingRequests.delete(e.id)})}}return{kind:`notification`,method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),`result`in e)t.resolve(e.result);else if(`error`in e&&eh(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new oh(n,r,i))}else t.reject(oh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==$m)return;let t=jne(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(oh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?nh(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Bne=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??th.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?th.no(r):await n(t(r.params),r.responder,i)??th.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?th.no(r):await n(t(r.params),i)??th.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new ah(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},oh=class e extends Error{code;data;constructor(e,t,n){super(t),this.code=e,this.name=`RequestError`,this.data=n}static parseError(t,n){return new e(-32700,`Parse error${n?`: ${n}`:``}`,t)}static invalidRequest(t,n){return new e(-32600,`Invalid request${n?`: ${n}`:``}`,t)}static methodNotFound(t){return new e(-32601,`"Method not found": ${t}`,{method:t})}static invalidParams(t,n){return new e(-32602,`Invalid params${n?`: ${n}`:``}`,t)}static internalError(t,n){return new e(-32603,`Internal error${n?`: ${n}`:``}`,t)}static requestCancelled(t,n){return new e(-32800,`Request cancelled${n?`: ${n}`:``}`,t)}static authRequired(t,n){return new e(-32e3,`Authentication required${n?`: ${n}`:``}`,t)}static resourceNotFound(t){return new e(-32002,`Resource not found${t?`: ${t}`:``}`,t&&{uri:t})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}},Vne=class{#e=[];push(e){let t=[],n=0,r=e.indexOf(10,n);for(;r!==-1;)t.push(this.#t(e.subarray(n,r))),n=r+1,r=e.indexOf(10,n);return n<e.byteLength&&this.#e.push(n===0?e:new Uint8Array(e.subarray(n))),t}flush(){if(this.#e.length!==0)return this.#t(new Uint8Array)}#t(e){if(this.#e.length===0)return e;let t=e.byteLength;for(let e of this.#e)t+=e.byteLength;let n=new Uint8Array(t),r=0;for(let e of this.#e)n.set(e,r),r+=e.byteLength;return n.set(e,r),this.#e=[],n}};function Hne(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Vne,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);eh(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
5
5
  `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}function sh(e){return e??{}}function Une(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function Wne(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}const ch={agent:{initialize:zd.initialize,authenticate:zd.authenticate,logout:zd.logout,providers:{list:zd.providers_list,set:zd.providers_set,disable:zd.providers_disable},session:{new:zd.session_new,load:zd.session_load,list:zd.session_list,delete:zd.session_delete,fork:zd.session_fork,resume:zd.session_resume,close:zd.session_close,setMode:zd.session_set_mode,setConfigOption:zd.session_set_config_option,prompt:zd.session_prompt,cancel:zd.session_cancel},nes:{start:zd.nes_start,suggest:zd.nes_suggest,accept:zd.nes_accept,reject:zd.nes_reject,close:zd.nes_close},document:{didOpen:zd.document_did_open,didChange:zd.document_did_change,didClose:zd.document_did_close,didSave:zd.document_did_save,didFocus:zd.document_did_focus}},client:{session:{requestPermission:Bd.session_request_permission,update:Bd.session_update},fs:{writeTextFile:Bd.fs_write_text_file,readTextFile:Bd.fs_read_text_file},terminal:{create:Bd.terminal_create,output:Bd.terminal_output,release:Bd.terminal_release,waitForExit:Bd.terminal_wait_for_exit,kill:Bd.terminal_kill},elicitation:{create:Bd.elicitation_create,complete:Bd.elicitation_complete}},protocol:{cancelRequest:Vd.cancel_request}},lh=Symbol(`startActiveSession`);var uh=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},dh=class e extends uh{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){let r=Nh[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},fh=class e extends uh{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}[lh](e,t){return this.sendRequest(zd.session_new,e,e=>this.attachSession(e),t)}buildSession(e){return typeof e==`string`?bh.create(this,{cwd:e,mcpServers:[]}):bh.create(this,e)}attachSession(e){let t=new vh,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=zh(this.connectionContext).attach(e,t),a=new ih(()=>{n.removeEventListener(`abort`,r)});return xh.create(this,e,t,[i,a])}request(e,t,n){let r=Mh[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},ph=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},mh=class extends ph{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=dh.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Bh(this,this.connectHandlers))}},hh=class extends ph{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=fh.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Bh(this,this.connectHandlers))}};function gh(e,t=[]){return new mh(e,t)}function _h(e,t=[]){return new hh(e,t)}var vh=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:`value`,value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:`error`,error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind===`value`)}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind===`error`?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function yh(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var bh=class e{cx;request;constructor(e,t){this.cx=e,this.request=yh(t)}static create(t,n){return new e(t,n)}toRequest(){return yh(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[lh](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},xh=class e{cx;sessionResponse;updates;registrations;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r}static create(t,n,r,i){return new e(t,n,r,i)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let n=this.cx.request(zd.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return n.then(e=>{this.updates.enqueue({kind:`stop`,response:e,stopReason:e.stopReason})},e=>{this.updates.reject(e)}),n}nextUpdate(){return this.updates.next()}async readText(){let e=``;for(;;){let t=await this.nextUpdate();if(t.kind===`stop`)return e;let{update:n}=t;n.sessionUpdate===`agent_message_chunk`&&n.content.type===`text`&&(e+=n.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error(`Active session disposed`))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e==`string`?[{type:`text`,text:e}]:Array.isArray(e)?e:[e]}};function Sh(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function Ch(e,t,n){return{method:e,params:t,mapResponse:n}}function wh(e,t){return{method:e,params:t}}function Th(e,t,n,r){e.onReceiveRequest(t.method,e=>Sh(t.params,e),async(e,i,a)=>{let o=await r(n(e,a,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(o):o)})}function Eh(e,t,n,r){e.onReceiveNotification(t.method,e=>Sh(t.params,e),(e,t)=>r(n(e,t,t.signal)))}function Dh(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const Oh={initialize:Ch(zd.initialize,Cm),newSession:Ch(zd.session_new,jm),loadSession:Ch(zd.session_load,Mm,sh),unstable_forkSession:Ch(zd.session_fork,Fm),listSessions:Ch(zd.session_list,Nm),deleteSession:Ch(zd.session_delete,Pm,sh),resumeSession:Ch(zd.session_resume,Im),closeSession:Ch(zd.session_close,Lm,sh),setSessionMode:Ch(zd.session_set_mode,Rm,sh),setSessionConfigOption:Ch(zd.session_set_config_option,zm),authenticate:Ch(zd.authenticate,wm,sh),unstable_listProviders:Ch(zd.providers_list,Tm),unstable_setProvider:Ch(zd.providers_set,Em,sh),unstable_disableProvider:Ch(zd.providers_disable,Dm,sh),logout:Ch(zd.logout,Om,sh),prompt:Ch(zd.session_prompt,Bm),unstable_startNes:Ch(zd.nes_start,Vm),unstable_suggestNes:Ch(zd.nes_suggest,Hm),unstable_closeNes:Ch(zd.nes_close,Um,sh)},kh={cancel:wh(zd.session_cancel,Gm),unstable_didOpenDocument:wh(zd.document_did_open,Km),unstable_didChangeDocument:wh(zd.document_did_change,qm),unstable_didCloseDocument:wh(zd.document_did_close,Jm),unstable_didSaveDocument:wh(zd.document_did_save,Ym),unstable_didFocusDocument:wh(zd.document_did_focus,Xm),unstable_acceptNes:wh(zd.nes_accept,Zm),unstable_rejectNes:wh(zd.nes_reject,Qm)},Ah={requestPermission:Ch(Bd.session_request_permission,lf),writeTextFile:Ch(Bd.fs_write_text_file,Xd,sh),readTextFile:Ch(Bd.fs_read_text_file,Zd),createTerminal:Ch(Bd.terminal_create,df),terminalOutput:Ch(Bd.terminal_output,ff),releaseTerminal:Ch(Bd.terminal_release,pf,sh),waitForTerminalExit:Ch(Bd.terminal_wait_for_exit,mf),killTerminal:Ch(Bd.terminal_kill,hf,sh),unstable_createElicitation:Ch(Bd.elicitation_create,Mf)},jh={sessionUpdate:wh(Bd.session_update,ym),unstable_completeElicitation:wh(Bd.elicitation_complete,bm)},Mh=Dh(Oh);Dh(kh);const Nh=Dh(Ah),Ph=Dh(jh);function Fh(e,t,n,r){return{params:e,requestId:r,signal:n,agent:t}}function Ih(e,t,n){return{params:e,signal:n,agent:t}}var Lh=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==Bd.session_update)return th.no(e);let t=ym.parse(e.params),n={kind:`session_update`,notification:t,update:t.update},r=this.activeSessions.get(t.sessionId);if(r&&r.size>0)for(let e of r)e.enqueue(n);return th.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new ih(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}};const Rh=new WeakMap;function zh(e){let t=Rh.get(e);return t||(t=new Lh,Rh.set(e,t)),t}function Bh(e,t){for(let n of t){let t;try{t=n(e)}catch(t){throw e.close(t),t}Promise.resolve(t).catch(t=>{e.close(t)})}}const Vh=Symbol(`appBuilder`),Hh=Symbol(`runAgentConnectHandlers`),Uh=Symbol(`runClientConnectHandlers`);function Wh(e){return new Gh(e)}var Gh=class{builder=ah.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(e,t)=>zh(t).handleMessage(e),describe:()=>`client-session-update-router`})}[Vh](){return this.builder}[Uh](e){Bh(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(n)return this.request({method:e,params:t},n);let r=Nh[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(r,t)}onNotification(e,t,n){if(n)return this.notification({method:e,params:t},n);let r=Ph[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return Th(this.builder,e,(e,t,n,r)=>Fh(e,fh.create(t,r),n,r),t),this}notification(e,t){return Eh(this.builder,e,(e,t,n)=>Ih(e,fh.create(t),n),t),this}connectConnection(e){if(Une(e)){let t=this.openStreamConnection(e);return this[Uh](t.connection),t}let[t,n]=Wne(),r=e[Vh]().connect(n),i=gh(r),a=this.openStreamConnection(t);a.rawConnection.closed.then(()=>i.close()),r.closed.then(()=>a.connection.close());try{e[Hh](i),this[Uh](a.connection)}catch(e){throw i.close(e),a.connection.close(e),e}return a}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:_h(t,this.connectHandlers)}}};new Set([zd.initialize,zd.authenticate,zd.providers_list,zd.providers_set,zd.providers_disable,zd.session_new,zd.session_load,zd.session_set_mode,zd.session_set_config_option,zd.session_prompt,zd.session_list,zd.session_delete,zd.session_fork,zd.session_resume,zd.session_close,zd.logout,zd.nes_start,zd.nes_suggest,zd.nes_close]),new Set([zd.session_cancel,zd.nes_accept,zd.nes_reject,zd.document_did_open,zd.document_did_change,zd.document_did_close,zd.document_did_save,zd.document_did_focus]),new Set([Bd.session_request_permission,Bd.fs_write_text_file,Bd.fs_read_text_file,Bd.terminal_create,Bd.terminal_output,Bd.terminal_release,Bd.terminal_wait_for_exit,Bd.terminal_kill,Bd.elicitation_create]),new Set([Bd.session_update,Bd.elicitation_complete]);function Kh(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const qh=/^[a-zA-Z0-9_-]+$/,Jh=64;function Yh(e){return typeof e!=`string`||e.length===0||e.length>64||!qh.test(e)?null:e}function Xh(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function Zh(e){return!e.startsWith(`principal-`)}function Qh(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function $h(e){let t=Yh(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:Xh(t),displayName:typeof e.agentName==`string`?Kh(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?Kh(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?Kh(e.clientVersion):void 0,label:typeof e.label==`string`?Kh(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}const eg=()=>new Map,tg=e=>{let t=eg();return e.forEach((e,n)=>{t.set(n,e)}),t},ng=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},rg=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},ig=()=>new Set,ag=e=>e[e.length-1],og=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},sg=Array.from,cg=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},lg=Array.isArray;var ug=class{constructor(){this._observers=eg()}on(e,t){return ng(this._observers,e,ig).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return sg((this._observers.get(e)||eg()).values()).forEach(e=>e(...t))}destroy(){this._observers=eg()}};const dg=Math.floor,fg=Math.abs,pg=(e,t)=>e<t?e:t,mg=(e,t)=>e>t?e:t;Number.isNaN;const hg=e=>e===0?1/e<0:e<0,gg=2**53-1,_g=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&dg(e)===e);Number.isNaN,Number.parseInt;const vg=String.fromCharCode;String.fromCodePoint,vg(65535);const yg=e=>e.toLowerCase(),bg=/^\s*/g,xg=e=>e.replace(bg,``),Sg=/([A-Z])/g,Cg=(e,t)=>xg(e.replace(Sg,e=>`${t}${yg(e)}`)),wg=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Tg=typeof TextEncoder<`u`?new TextEncoder:null,Eg=Tg?e=>Tg.encode(e):wg;let Dg=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Dg&&Dg.decode(new Uint8Array).length===1&&(Dg=null);var Og=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const kg=()=>new Og,Ag=e=>{let t=kg();return e(t),Mg(t)},jg=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Mg=e=>{let t=new Uint8Array(jg(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Ng=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(mg(n,t)*2),e.cpos=0)},Pg=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Fg=Pg,Ig=(e,t)=>{for(;t>127;)Pg(e,128|127&t),t=dg(t/128);Pg(e,127&t)},Lg=(e,t)=>{let n=hg(t);for(n&&(t=-t),Pg(e,(t>63?128:0)|(n?64:0)|63&t),t=dg(t/64);t>0;)Pg(e,(t>127?128:0)|127&t),t=dg(t/128)},Rg=new Uint8Array(3e4),zg=Rg.length/3,Bg=Tg&&Tg.encodeInto?(e,t)=>{if(t.length<zg){let n=Tg.encodeInto(t,Rg).written||0;Ig(e,n);for(let t=0;t<n;t++)Pg(e,Rg[t])}else Hg(e,Eg(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Ig(e,r);for(let t=0;t<r;t++)Pg(e,n.codePointAt(t))},Vg=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=pg(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(mg(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Hg=(e,t)=>{Ig(e,t.byteLength),Vg(e,t)},Ug=(e,t)=>{Ng(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Wg=(e,t)=>Ug(e,4).setFloat32(0,t,!1),Gg=(e,t)=>Ug(e,8).setFloat64(0,t,!1),Kg=(e,t)=>Ug(e,8).setBigInt64(0,t,!1),qg=new DataView(new ArrayBuffer(4)),Jg=e=>(qg.setFloat32(0,e),qg.getFloat32(0)===e),Yg=(e,t)=>{switch(typeof t){case`string`:Pg(e,119),Bg(e,t);break;case`number`:_g(t)&&fg(t)<=2147483647?(Pg(e,125),Lg(e,t)):Jg(t)?(Pg(e,124),Wg(e,t)):(Pg(e,123),Gg(e,t));break;case`bigint`:Pg(e,122),Kg(e,t);break;case`object`:if(t===null)Pg(e,126);else if(lg(t)){Pg(e,117),Ig(e,t.length);for(let n=0;n<t.length;n++)Yg(e,t[n])}else if(t instanceof Uint8Array)Pg(e,116),Hg(e,t);else{Pg(e,118);let n=Object.keys(t);Ig(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Bg(e,i),Yg(e,t[i])}}break;case`boolean`:Pg(e,t?120:121);break;default:Pg(e,127)}};var Xg=class extends Og{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Ig(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const Zg=e=>{e.count>0&&(Lg(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Ig(e.encoder,e.count-2))};var Qg=class{constructor(){this.encoder=new Og,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Zg(this),this.count=1,this.s=e)}toUint8Array(){return Zg(this),Mg(this.encoder)}};const $g=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Lg(e.encoder,t),e.count>1&&Ig(e.encoder,e.count-2)}};var e_=class{constructor(){this.encoder=new Og,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):($g(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return $g(this),Mg(this.encoder)}},t_=class{constructor(){this.sarr=[],this.s=``,this.lensE=new Qg}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Og;return this.sarr.push(this.s),this.s=``,Bg(e,this.sarr.join(``)),Vg(e,this.lensE.toUint8Array()),Mg(e)}};const n_=e=>Error(e),r_=()=>{throw n_(`Method unimplemented`)},i_=()=>{throw n_(`Unexpected case`)},a_=n_(`Unexpected end of array`),o_=n_(`Integer out of Range`);var s_=class{constructor(e){this.arr=e,this.pos=0}};const c_=e=>new s_(e),l_=e=>e.pos!==e.arr.length,u_=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},d_=e=>u_(e,p_(e)),f_=e=>e.arr[e.pos++],p_=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>gg)throw o_}throw a_},m_=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>gg)throw o_}throw a_},h_=Dg?e=>Dg.decode(d_(e)):e=>{let t=p_(e);if(t===0)return``;{let n=String.fromCodePoint(f_(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(f_(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},g_=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},__=[e=>void 0,e=>null,m_,e=>g_(e,4).getFloat32(0,!1),e=>g_(e,8).getFloat64(0,!1),e=>g_(e,8).getBigInt64(0,!1),e=>!1,e=>!0,h_,e=>{let t=p_(e),n={};for(let r=0;r<t;r++){let t=h_(e);n[t]=v_(e)}return n},e=>{let t=p_(e),n=[];for(let r=0;r<t;r++)n.push(v_(e));return n},d_],v_=e=>__[127-f_(e)](e);var y_=class extends s_{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),l_(this)?this.count=p_(this)+1:this.count=-1),this.count--,this.s}},b_=class extends s_{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=m_(this);let e=hg(this.s);this.count=1,e&&(this.s=-this.s,this.count=p_(this)+2)}return this.count--,this.s}},x_=class extends s_{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=m_(this),t=e&1;this.diff=dg(e/2),this.count=1,t&&(this.count=p_(this)+2)}return this.s+=this.diff,this.count--,this.s}},S_=class{constructor(e){this.decoder=new b_(e),this.str=h_(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};ku.subtle;const C_=ku.getRandomValues.bind(ku),w_=()=>C_(new Uint32Array(1))[0],T_=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^w_()&15>>e/4).toString(16)),E_=Date.now,D_=e=>new Promise(e);Promise.all.bind(Promise);const O_=e=>e===void 0?null:e;let k_=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(k_=localStorage)}catch{}const A_=k_,j_=Symbol(`Equality`),M_=(e,t)=>e===t||!!e?.[j_]?.(t)||!1,N_=Object.assign,P_=Object.keys,F_=(e,t)=>{for(let n in e)t(e[n],n)},I_=e=>P_(e).length,L_=e=>{for(let t in e)return!1;return!0},R_=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},z_=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),B_=(e,t)=>e===t||I_(e)===I_(t)&&R_(e,(e,n)=>(e!==void 0||z_(t,n))&&M_(t[n],e)),V_=Object.freeze,H_=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&H_(e[t])}return V_(e)},U_=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&U_(e,t,n+1)}},W_=e=>e,G_=(e,t)=>t.includes(e),K_=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,q_=typeof window<`u`&&typeof document<`u`&&!K_;typeof navigator<`u`&&/Mac/.test(navigator.platform);let J_;const Y_=[],X_=()=>{if(J_===void 0)if(K_){J_=eg();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&J_.set(t,``),t=r):t===null?Y_.push(r):(J_.set(t,r),t=null)}t!==null&&J_.set(t,``)}else typeof location==`object`?(J_=eg(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);J_.set(`--${Cg(t,`-`)}`,n),J_.set(`-${Cg(t,`-`)}`,n)}})):J_=eg();return J_},Z_=e=>X_().has(e),Q_=e=>O_(K_?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:A_.getItem(e)),$_=e=>Z_(`--`+e)||Q_(e)!==null;$_(`production`);const ev=K_&&G_(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!Z_(`--no-colors`)&&!$_(`no-color`)&&(!K_||process.stdout.isTTY)&&(!K_||Z_(`--color`)||Q_(`COLORTERM`)!==null||(Q_(`TERM`)||``).includes(`color`)),tv=e=>new Uint8Array(e),nv=q_?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=vg(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),rv=e=>{let t=tv(e.byteLength);return t.set(e),t},iv=e=>Ag(t=>Yg(t,e)),av=Symbol,ov=av(),sv=av(),cv=av(),lv=av(),uv=av(),dv=av(),fv=av(),pv=av(),mv=av(),hv=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};E_();const gv={[ov]:`\x1B[1m`,[sv]:`\x1B[2m`,[cv]:`\x1B[34m`,[uv]:`\x1B[32m`,[lv]:`\x1B[37m`,[dv]:`\x1B[31m`,[fv]:`\x1B[35m`,[pv]:`\x1B[38;5;208m`,[mv]:`\x1B[0m`},_v=ev?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r],i=gv[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n}:hv,vv=(...e)=>{console.log(..._v(e))},yv=(...e)=>{console.warn(..._v(e))},bv=e=>({[Symbol.iterator](){return this},next:e}),xv=(e,t)=>bv(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),Sv=(e,t)=>bv(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var Cv=class{constructor(e,t){this.clock=e,this.len=t}},wv=class{constructor(){this.clients=new Map}};const Tv=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Ly(e,i,o.clock,o.len,n)}}),Ev=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=dg((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},Dv=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&Ev(n,t.clock)!==null},Ov=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new Cv(r.clock,mg(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},kv=e=>{let t=new wv;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)og(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return Ov(t),t},Av=(e,t,n,r)=>{ng(e.clients,t,()=>[]).push(new Cv(n,r))},jv=()=>new wv,Mv=e=>{let t=jv();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new Cv(i,a))}}r.length>0&&t.clients.set(n,r)}),t},Nv=(e,t)=>{Ig(e.restEncoder,t.clients.size),sg(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Ig(e.restEncoder,t);let r=n.length;Ig(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Pv=e=>{let t=new wv,n=p_(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=p_(e.restDecoder),r=p_(e.restDecoder);if(r>0){let i=ng(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new Cv(e.readDsClock(),e.readDsLen()))}}return t},Fv=(e,t,n)=>{let r=new wv,i=p_(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=p_(e.restDecoder),a=p_(e.restDecoder),o=n.clients.get(i)||[],s=ky(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&Av(r,i,s,a-s);let e=jy(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,_x(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,_x(t,c,a-c.id.clock)),c.delete(t))}else Av(r,i,n,a-n)}}if(r.clients.size>0){let e=new Kv;return Ig(e.restEncoder,0),Nv(e,r),e.toUint8Array()}return null},Iv=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},Lv=w_;var Rv=class e extends ug{constructor({guid:e=T_(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Lv(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Dy,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=D_(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>D_(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Gy(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(sg(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Gy(this,e,t)}get(e,t=bb){let n=ng(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==bb&&r!==t)if(r===bb){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,Bb)}getText(e=``){return this.get(e,ex)}getMap(e=``){return this.get(e,Vb)}getXmlElement(e=``){return this.get(e,rx)}getXmlFragment(e=``){return this.get(e,nx)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,sg(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Gy(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},zv=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return p_(this.restDecoder)}readDsLen(){return p_(this.restDecoder)}},Bv=class extends zv{readLeftID(){return _y(p_(this.restDecoder),p_(this.restDecoder))}readRightID(){return _y(p_(this.restDecoder),p_(this.restDecoder))}readClient(){return p_(this.restDecoder)}readInfo(){return f_(this.restDecoder)}readString(){return h_(this.restDecoder)}readParentInfo(){return p_(this.restDecoder)===1}readTypeRef(){return p_(this.restDecoder)}readLen(){return p_(this.restDecoder)}readAny(){return v_(this.restDecoder)}readBuf(){return rv(d_(this.restDecoder))}readJSON(){return JSON.parse(h_(this.restDecoder))}readKey(){return h_(this.restDecoder)}},Vv=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=p_(this.restDecoder),this.dsCurrVal}readDsLen(){let e=p_(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Hv=class extends Vv{constructor(e){super(e),this.keys=[],p_(e),this.keyClockDecoder=new x_(d_(e)),this.clientDecoder=new b_(d_(e)),this.leftClockDecoder=new x_(d_(e)),this.rightClockDecoder=new x_(d_(e)),this.infoDecoder=new y_(d_(e),f_),this.stringDecoder=new S_(d_(e)),this.parentInfoDecoder=new y_(d_(e),f_),this.typeRefDecoder=new b_(d_(e)),this.lenDecoder=new b_(d_(e))}readLeftID(){return new hy(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new hy(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return v_(this.restDecoder)}readBuf(){return d_(this.restDecoder)}readJSON(){return v_(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},Uv=class{constructor(){this.restEncoder=kg()}toUint8Array(){return Mg(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Ig(this.restEncoder,e)}writeDsLen(e){Ig(this.restEncoder,e)}},Wv=class extends Uv{writeLeftID(e){Ig(this.restEncoder,e.client),Ig(this.restEncoder,e.clock)}writeRightID(e){Ig(this.restEncoder,e.client),Ig(this.restEncoder,e.clock)}writeClient(e){Ig(this.restEncoder,e)}writeInfo(e){Fg(this.restEncoder,e)}writeString(e){Bg(this.restEncoder,e)}writeParentInfo(e){Ig(this.restEncoder,+!!e)}writeTypeRef(e){Ig(this.restEncoder,e)}writeLen(e){Ig(this.restEncoder,e)}writeAny(e){Yg(this.restEncoder,e)}writeBuf(e){Hg(this.restEncoder,e)}writeJSON(e){Bg(this.restEncoder,JSON.stringify(e))}writeKey(e){Bg(this.restEncoder,e)}},Gv=class{constructor(){this.restEncoder=kg(),this.dsCurrVal=0}toUint8Array(){return Mg(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Ig(this.restEncoder,t)}writeDsLen(e){e===0&&i_(),Ig(this.restEncoder,e-1),this.dsCurrVal+=e}},Kv=class extends Gv{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new e_,this.clientEncoder=new Qg,this.leftClockEncoder=new e_,this.rightClockEncoder=new e_,this.infoEncoder=new Xg(Fg),this.stringEncoder=new t_,this.parentInfoEncoder=new Xg(Fg),this.typeRefEncoder=new Qg,this.lenEncoder=new Qg}toUint8Array(){let e=kg();return Ig(e,0),Hg(e,this.keyClockEncoder.toUint8Array()),Hg(e,this.clientEncoder.toUint8Array()),Hg(e,this.leftClockEncoder.toUint8Array()),Hg(e,this.rightClockEncoder.toUint8Array()),Hg(e,Mg(this.infoEncoder)),Hg(e,this.stringEncoder.toUint8Array()),Hg(e,Mg(this.parentInfoEncoder)),Hg(e,this.typeRefEncoder.toUint8Array()),Hg(e,this.lenEncoder.toUint8Array()),Vg(e,Mg(this.restEncoder)),Mg(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Yg(this.restEncoder,e)}writeBuf(e){Hg(this.restEncoder,e)}writeJSON(e){Yg(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const qv=(e,t,n,r)=>{r=mg(r,t[0].id.clock);let i=jy(t,r);Ig(e.restEncoder,t.length-i),e.writeClient(n),Ig(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},Jv=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{ky(t,n)>e&&r.set(n,e)}),Oy(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Ig(e.restEncoder,r.size),sg(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{qv(e,t.clients.get(n),n,r)})},Yv=(e,t)=>{let n=eg(),r=p_(e.restDecoder);for(let i=0;i<r;i++){let r=p_(e.restDecoder),i=Array(r),a=e.readClient(),o=p_(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new ox(_y(a,o),t),o+=t;break}case 10:{let t=p_(e.restDecoder);i[n]=new Sx(_y(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new bx(_y(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,xx(e,r));i[n]=c,o+=c.length}}}}return n},Xv=(e,t,n)=>{let r=[],i=sg(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new Dy,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==Sx){let i=ng(d,u.id.client,()=>ky(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,ky(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new Kv;return Jv(e,s,new Map),Ig(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},Zv=(e,t)=>Jv(e,t.doc.store,t.beforeState),Qv=(e,t,n,r=new Hv(e))=>Gy(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=Xv(e,i,Yv(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<ky(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=tb([o.update,a.update])}}else i.pendingStructs=a;let s=Fv(r,e,i);if(i.pendingDs){let t=new Hv(c_(i.pendingDs));p_(t.restDecoder);let n=Fv(t,e,i);s&&n?i.pendingDs=tb([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,$v(e.doc,t)}},n,!1),$v=(e,t,n,r=Hv)=>{let i=c_(t);Qv(i,e,n,new r(i))},ey=(e,t,n)=>$v(e,t,n,Bv),ty=(e,t,n=new Map)=>{Jv(e,t.store,n),Nv(e,Mv(t.store))},ny=(e,t=new Uint8Array([0]),n=new Kv)=>{ty(n,e,ay(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(nb(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Wv)return $y(r.map((e,t)=>t===0?e:sb(e)));if(n.constructor===Kv)return tb(r)}return r[0]},ry=(e,t)=>ny(e,t,new Wv),iy=e=>{let t=new Map,n=p_(e.restDecoder);for(let r=0;r<n;r++){let n=p_(e.restDecoder),r=p_(e.restDecoder);t.set(n,r)}return t},ay=e=>iy(new zv(c_(e))),oy=(e,t)=>(Ig(e.restEncoder,t.size),sg(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Ig(e.restEncoder,t),Ig(e.restEncoder,n)}),e),sy=(e,t)=>oy(e,Oy(t.store)),cy=(e,t=new Gv)=>(e instanceof Map?oy(t,e):sy(t,e),t.toUint8Array()),ly=e=>cy(e,new Uv);var uy=class{constructor(){this.l=[]}};const dy=()=>new uy,fy=(e,t)=>e.l.push(t),py=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},my=(e,t,n)=>U_(e.l,[t,n]);var hy=class{constructor(e,t){this.client=e,this.clock=t}};const gy=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,_y=(e,t)=>new hy(e,t),vy=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw i_()},yy=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var by=class{constructor(e,t){this.ds=e,this.sv=t}};const xy=(e,t)=>new by(e,t);xy(jv(),new Map);const Sy=e=>xy(Mv(e.store),Oy(e.store)),Cy=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Dv(t.ds,e.id),wy=(e,t)=>{let n=ng(e.meta,wy,ig),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<ky(r,n)&&Py(e,_y(n,t))}),Tv(e,t.ds,e=>{}),n.add(t))},Ty=(e,t,n=Hv)=>{let r=new n(c_(t)),i=new Zy(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=kv([e.ds,Pv(r)]);return Iv(e.ds,a)},Ey=(e,t)=>Ty(e,t,Bv);var Dy=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const Oy=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},ky=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Ay=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw i_()}n.push(t)},jy=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=dg(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=dg((n+r)/2)}throw i_()},My=(e,t)=>{let n=e.clients.get(t.client);return n[jy(n,t.clock)]},Ny=(e,t,n)=>{let r=jy(t,n),i=t[r];return i.id.clock<n&&i instanceof bx?(t.splice(r+1,0,_x(e,i,n-i.id.clock)),r+1):r},Py=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Ny(e,n,t.clock)]},Fy=(e,t,n)=>{let r=t.clients.get(n.client),i=jy(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==ox&&r.splice(i+1,0,_x(e,a,n.clock-a.id.clock+1)),a},Iy=(e,t,n)=>{let r=e.clients.get(t.id.client);r[jy(r,t.id.clock)]=n},Ly=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Ny(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Ny(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Ry=class{constructor(e,t,n){this.doc=e,this.deleteSet=new wv,this.beforeState=Oy(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const zy=(e,t)=>t.deleteSet.clients.size===0&&!rg(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(Ov(t.deleteSet),Zv(e,t),Nv(e,t.deleteSet),!0),By=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&ng(e.changed,t,ig).add(n)},Vy=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof bx&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},Hy=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=jy(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof bx&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Uy=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=pg(r.length-1,1+jy(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Vy(r,e)}})},Wy=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{Ov(a),n.afterState=Oy(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{my(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Zne(n)})}),U_(e,[])}finally{r.gc&&Hy(a,i,r.gcFilter),Uy(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=mg(jy(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Vy(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=jy(r,n);a+1<r.length&&Vy(r,a+1)>1||a>0&&Vy(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(vv(pv,ov,`[yjs] `,sv,dv,`Changed the client-id because another client seems to be using it.`),r.clientID=Lv()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Wv;zy(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Kv;zy(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):Wy(e,t+1)}}},Gy=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Ry(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&Wy(i,0)}}return o};var Ky=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const qy=(e,t,n)=>{Tv(e,n.deletions,n=>{n instanceof bx&&t.scope.some(t=>t===e.doc||yy(t,n))&&gx(n,!1)})},Jy=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Gy(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;Tv(n,o.insertions,e=>{if(e instanceof bx){if(e.redone!==null){let{item:t,diff:i}=Tre(r,e.id);i>0&&(t=Py(n,_y(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||yy(t,e))&&c.push(e)}}),Tv(n,o.deletions,e=>{e instanceof bx&&a.some(t=>t===n.doc||yy(t,e))&&!Dv(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=yx(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var Yy=class extends ug{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=lg(e)?e[0].doc:e instanceof Rv?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new wv;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&Av(i,n,r,a)});let a=E_(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=kv([t.deletions,e.deleteSet]),t.insertions=kv([t.insertions,i])}else r.push(new Ky(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),Tv(e,e.deleteSet,t=>{t instanceof bx&&this.scope.some(n=>n===e.doc||yy(n,t))&&gx(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=lg(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof bb?e.doc!==this.doc:e!==this.doc)&&yv(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>qy(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>qy(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Jy(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Jy(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*Xy(e){let t=p_(e.restDecoder);for(let n=0;n<t;n++){let t=p_(e.restDecoder),n=e.readClient(),r=p_(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=p_(e.restDecoder);yield new Sx(_y(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new bx(_y(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,xx(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new ox(_y(n,r),t),r+=t}}}}var Zy=class{constructor(e,t){this.gen=Xy(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===Sx);return this.curr}},Qy=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const $y=e=>tb(e,Bv,Wv),eb=(e,t)=>{if(e.constructor===ox){let{client:n,clock:r}=e.id;return new ox(_y(n,r+t),e.length-t)}else if(e.constructor===Sx){let{client:n,clock:r}=e.id;return new Sx(_y(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new bx(_y(r,i+t),null,_y(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},tb=(e,t=Hv,n=Kv)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(c_(e))),i=r.map(e=>new Zy(e,!0)),a=null,o=new n,s=new Qy(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Sx?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)ib(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===Sx)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{ib(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new Sx(_y(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===Sx?a.struct.length-=t:n=eb(n,t)),a.struct.mergeWith(n)||(ib(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==Sx;n=e.next())ib(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(ib(s,a.struct,a.offset),a=null),ab(s),Nv(o,kv(r.map(e=>Pv(e)))),o.toUint8Array()},nb=(e,t,n=Hv,r=Kv)=>{let i=ay(t),a=new r,o=new Qy(a),s=new n(c_(e)),c=new Zy(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===Sx){c.next();continue}if(e.id.clock+e.length>n)for(ib(o,e,mg(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)ib(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return ab(o),Nv(a,Pv(s)),a.toUint8Array()},rb=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Mg(e.encoder.restEncoder)}),e.encoder.restEncoder=kg(),e.written=0)},ib=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&rb(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Ig(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ab=e=>{rb(e);let t=e.encoder.restEncoder;Ig(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Ig(t,r.written),Vg(t,r.restEncoder)}},ob=(e,t,n,r)=>{let i=new n(c_(e)),a=new Zy(i,!1),o=new r,s=new Qy(o);for(let e=a.curr;e!==null;e=a.next())ib(s,t(e),0);return ab(s),Nv(o,Pv(i)),o.toUint8Array()},sb=e=>ob(e,W_,Hv,Wv),cb=`You must not compute changes after the event-handler fired.`;var lb=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=ub(this.currentTarget,this.target)}deletes(e){return Dv(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw n_(cb);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=ag(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=ag(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=ag(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw n_(cb);let t=this.target,n=ig(),r=ig(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const ub=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},db=()=>{yv(`Invalid access: Add Yjs type to a document before reading data.`)};let fb=0;var pb=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=fb++}};const mb=e=>{e.timestamp=fb++},hb=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=fb++},gb=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return hb(r,t,n),r}else{let r=new pb(t,n);return e.push(r),r}},_b=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>fg(t-e.index)<fg(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,mb(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&fg(n.index-i)<r.parent.length/80?(hb(n,r,i),n):gb(e._searchMarker,r,i)},vb=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=mg(t,i.index+n))}},yb=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;ng(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;my(r._eH,n,t)};var bb=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=dy(),this._dEH=dy(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw r_()}clone(){throw r_()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){fy(this._eH,e)}observeDeep(e){fy(this._dEH,e)}unobserve(e){py(this._eH,e)}unobserveDeep(e){py(this._dEH,e)}toJSON(){}};const xb=(e,t,n)=>{e.doc??db(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},Sb=e=>{e.doc??db();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Cb=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&Cy(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},wb=(e,t)=>{let n=0,r=e._start;for(e.doc??db();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Tb=(e,t)=>{let n=[];return wb(e,(r,i)=>{n.push(t(r,i,e))}),n},Eb=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Db=(e,t)=>{e.doc??db();let n=_b(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},Ob=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new bx(_y(o,ky(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new px(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new bx(_y(o,ky(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new sx(new Uint8Array(n))),i.integrate(e,0);break;case Rv:i=new bx(_y(o,ky(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new ux(n)),i.integrate(e,0);break;default:if(n instanceof bb)i=new bx(_y(o,ky(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new hx(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},kb=()=>n_(`Length exceeded!`),Ab=(e,t,n,r)=>{if(n>t._length)throw kb();if(n===0)return t._searchMarker&&vb(t._searchMarker,n,r.length),Ob(e,t,null,r);let i=n,a=_b(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Py(e,_y(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&vb(t._searchMarker,i,r.length),Ob(e,t,o,r)},jb=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return Ob(e,t,r,n)},Mb=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=_b(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Py(e,_y(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Py(e,_y(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw kb();t._searchMarker&&vb(t._searchMarker,i,-a+r)},Nb=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Pb=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new px([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new px([r]);break;case Uint8Array:s=new sx(r);break;case Rv:s=new ux(r);break;default:if(r instanceof bb)s=new hx(r);else throw Error(`Unexpected content type`)}new bx(_y(o,ky(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},Fb=(e,t)=>{e.doc??db();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Ib=e=>{let t={};return e.doc??db(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Lb=(e,t)=>{e.doc??db();let n=e._map.get(t);return n!==void 0&&!n.deleted},Rb=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Cy(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},zb=e=>(e.doc??db(),xv(e._map.entries(),e=>!e[1].deleted));var Gne=class extends lb{},Bb=class e extends bb{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof bb?e.clone():e)),t}get length(){return this.doc??db(),this._length}_callObserver(e,t){super._callObserver(e,t),yb(this,e,new Gne(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Gy(this.doc,n=>{Ab(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Gy(this.doc,t=>{jb(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Gy(this.doc,n=>{Mb(n,this,e,t)})}get(e){return Db(this,e)}toArray(){return Sb(this)}slice(e=0,t=this.length){return xb(this,e,t)}toJSON(){return this.map(e=>e instanceof bb?e.toJSON():e)}map(e){return Tb(this,e)}forEach(e){wb(this,e)}[Symbol.iterator](){return Eb(this)}_write(e){e.writeTypeRef(_re)}};const Kne=e=>new Bb;var qne=class extends lb{constructor(e,t,n){super(e,t),this.keysChanged=n}},Vb=class e extends bb{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof bb?e.clone():e)}),t}_callObserver(e,t){yb(this,e,new qne(this,e,t))}toJSON(){this.doc??db();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof bb?r.toJSON():r}}),e}get size(){return[...zb(this)].length}keys(){return Sv(zb(this),e=>e[0])}values(){return Sv(zb(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Sv(zb(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??db(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):Gy(this.doc,t=>{Nb(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Gy(this.doc,n=>{Pb(n,this,e,t)}),t}get(e){return Fb(this,e)}has(e){return Lb(this,e)}clear(){this.doc===null?this._prelimContent.clear():Gy(this.doc,e=>{this.forEach(function(t,n,r){Nb(e,r,n)})})}_write(e){e.writeTypeRef(vre)}};const Jne=e=>new Vb,Hb=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&B_(e,t);var Ub=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&i_(),this.right.content.constructor){case fx:this.right.deleted||qb(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const Wb=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case fx:t.right.deleted||qb(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Py(e,_y(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Gb=(e,t,n,r)=>{let i=new Map,a=r?_b(t,n):null;return a?Wb(e,new Ub(a.p.left,a.p,a.index,i),n-a.index):Wb(e,new Ub(null,t._start,0,i),n)},Kb=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===fx&&Hb(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new bx(_y(a,ky(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new fx(o,r));l.integrate(e,0),n.right=l,n.forward()})},qb=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Jb=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===fx&&Hb(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Yb=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!Hb(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new bx(_y(a,ky(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new fx(s,c)),n.right.integrate(e,0),n.forward()}}return o},Xb=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Jb(n,i);let s=Yb(e,t,n,i),c=r.constructor===String?new mx(r):r instanceof bb?new hx(r):new dx(r),{left:l,right:u,index:d}=n;t._searchMarker&&vb(t._searchMarker,n.index,c.getLength()),u=new bx(_y(o,ky(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Kb(e,t,n,s)},Zb=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Jb(n,i);let s=Yb(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===fx));){if(!n.right.deleted)switch(n.right.content.constructor){case fx:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Hb(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Py(e,_y(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
6
6
  `;n.right=new bx(_y(o,ky(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new mx(i)),n.right.integrate(e,0),n.forward()}Kb(e,t,n,s)},Qb=(e,t,n,r,i)=>{let a=t,o=eg();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===fx){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case fx:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&qb(i,n);break}}}t=t.right}return s},Yne=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===fx){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Xne=e=>{let t=0;return Gy(e.doc,n=>{let r=e._start,i=e._start,a=eg(),o=tg(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case fx:qb(o,i.content);break;default:t+=Qb(n,r,i,a,o),a=tg(o),r=i;break}i=i.right}}),t},Zne=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Ly(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===fx&&e.constructor!==ox&&t.add(e.parent)})}Gy(n,n=>{Tv(e,e.deleteSet,e=>{if(e instanceof ox||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===fx?t.add(r):Yne(n,e)});for(let e of t)Xne(e)})},$b=(e,t,n)=>{let r=n,i=tg(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case hx:case dx:case mx:n<t.right.length&&Py(e,_y(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Qb(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&vb(o._searchMarker,t.index,-r+n),t};var Qne=class extends lb{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Gy(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},L_(o)||(e.attributes=N_({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case hx:case dx:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case mx:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case fx:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Hb(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Hb(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Hb(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Hb(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),qb(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},ex=class e extends bb{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??db(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new Qne(this,e,t);yb(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??db();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===mx&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Gy(this.doc,n=>{let r=new Ub(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
7
7
  `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Xb(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&$b(n,r,a.delete):Zb(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??db();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Cy(s,e)||t!==void 0&&Cy(s,t))switch(s.content.constructor){case mx:{let r=i.get(`ychange`);e!==void 0&&!Cy(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Cy(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case hx:case dx:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case fx:Cy(s,e)&&(c(),qb(i,s.content));break}s=s.right}c()};return e||t?Gy(a,n=>{e&&wy(n,e),t&&wy(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Gy(r,r=>{let i=Gb(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Xb(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Gy(r,r=>{let i=Gb(r,this,e,!n);Xb(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Gy(n,n=>{$b(n,Gb(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Gy(r,r=>{let i=Gb(r,this,e,!1);i.right!==null&&Zb(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Gy(this.doc,t=>{Nb(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Gy(this.doc,n=>{Pb(n,this,e,t)})}getAttribute(e){return Fb(this,e)}getAttributes(){return Ib(this)}_write(e){e.writeTypeRef(yre)}};const $ne=e=>new ex;var tx=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??db()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===rx||t.constructor===nx)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},nx=class e extends bb{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof bb?e.clone():e)),t}get length(){return this.doc??db(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new tx(this,e)}querySelector(e){e=e.toUpperCase();let t=new tx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),sg(new tx(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){yb(this,e,new nre(this,t,e))}toString(){return Tb(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),wb(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Gy(this.doc,n=>{Ab(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Gy(this.doc,n=>{let r=e&&e instanceof bb?e._item:e;Ob(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw n_(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Gy(this.doc,n=>{Mb(n,this,e,t)})}toArray(){return Sb(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Db(this,e)}slice(e=0,t=this.length){return xb(this,e,t)}forEach(e){wb(this,e)}_write(e){e.writeTypeRef(xre)}};const ere=e=>new nx;var rx=class e extends nx{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return F_(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof bb?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Gy(this.doc,t=>{Nb(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Gy(this.doc,n=>{Pb(n,this,e,t)})}getAttribute(e){return Fb(this,e)}hasAttribute(e){return Lb(this,e)}getAttributes(e){return e?Rb(this,e):Ib(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return wb(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(bre),e.writeKey(this.nodeName)}};const tre=e=>new rx(e.readKey());var nre=class extends lb{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},rre=class e extends Vb{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Sre),e.writeKey(this.hookName)}};const ire=e=>new rre(e.readKey());var ix=class e extends ex{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Cre)}};const are=e=>new ix;var ax=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw r_()}mergeWith(e){return!1}write(e,t,n){throw r_()}integrate(e,t){throw r_()}},ox=class extends ax{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Ay(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},sx=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw r_()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const ore=e=>new sx(e.readBuf());var cx=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Av(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const sre=e=>new cx(e.readLen()),lx=(e,t)=>new Rv({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var ux=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(lx(this.doc.guid,this.opts))}splice(e){throw r_()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const cre=e=>new ux(lx(e.readString(),e.readAny()));var dx=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw r_()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const lre=e=>new dx(e.readJSON());var fx=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw r_()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const ure=e=>new fx(e.readKey(),e.readJSON());var dre=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const fre=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new dre(n)},pre=Q_(`node_env`)===`development`;var px=class e{constructor(e){this.arr=e,pre&&H_(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const mre=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new px(n)};var mx=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const hre=e=>new mx(e.readString()),gre=[Kne,Jne,$ne,tre,ere,ire,are],_re=0,vre=1,yre=2,bre=3,xre=4,Sre=5,Cre=6;var hx=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw r_()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const wre=e=>new hx(gre[e.readTypeRef()](e)),Tre=(e,t)=>{let n=t,r=0,i;do r>0&&(n=_y(n.client,n.clock+r)),i=My(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof bx);return{item:i,diff:r}},gx=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},_x=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new bx(_y(r,i+n),t,_y(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=_y(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},vx=(e,t)=>cg(e,e=>Dv(e.deletions,t)),yx=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Py(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||yx(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Py(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Py(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Py(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||Dv(r,d.right.id)||vx(a.undoStack,d.right.id)||vx(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Py(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=_y(c,ky(s,c)),h=new bx(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,gx(h,!0),h.integrate(e,0),h};var bx=class e extends ax{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=ky(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ky(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===hy&&this.id.client!==this.parent.client&&this.parent.clock>=ky(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Fy(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Py(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===ox||this.right&&this.right.constructor===ox)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===hy){let e=My(n,this.parent);e.constructor===ox?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Fy(e,e.doc.store,_y(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),gy(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(gy(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(My(e.doc.store,n.origin)))r.has(My(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Ay(e.doc.store,this),this.content.integrate(e,this),By(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new ox(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:_y(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&gy(e.origin,this.lastId)&&this.right===e&&gy(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),Av(e.deleteSet,this.id.client,this.id.clock,this.length),By(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw i_();this.content.gc(e),t?Iy(e,this,new ox(this.id,this.length)):this.content=new cx(this.length)}write(e,t){let n=t>0?_y(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=vy(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===hy?(e.writeParentInfo(!1),e.writeLeftID(t)):i_();i!==null&&e.writeString(i)}this.content.write(e,t)}};const xx=(e,t)=>Ere[t&31](e),Ere=[()=>{i_()},sre,fre,ore,hre,lre,ure,wre,mre,cre,()=>{i_()}];var Sx=class extends ax{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){i_()}write(e,t){e.writeInfo(10),Ig(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const Cx=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},wx=`__ $YJS$ __`;Cx[wx]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),Cx[wx]=!0;const Dre=/[\uD800-\uDBFF]/,Ore=/[\uDC00-\uDFFF]/,kre=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&Dre.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&Ore.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Are=e=>{let t=Du(`sha256`);return t.update(e),t.digest()},jre=new ho(`y-sync`);new ho(`y-undo`),new ho(`yjs-cursor`);const Mre=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Nre=e=>nv(Mre(Are(iv(e)))),Pre=()=>({mapping:new Map,isOMark:new Map}),Tx=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!Dv(t.ds,e.id),Fre=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof rx)return Ex(e,t,n,r,i,a);throw r_()}return o},Ex=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof rx){let s=Fre(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof ex&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=Ire(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):Cb(e,new by(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(Tx(e._item,r)?Tx(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=Nx(s),l=Rx(c.marks,t),u=t.node(e.nodeName,c.plain,o,l.length?l:void 0);return n.mapping.set(e,u),u}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},Ire=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Rx(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},Lre=(e,t)=>{let n=new ix,r=e.map(e=>({insert:e.text,attributes:zx(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Rre=(e,t)=>{let n=new rx(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=zx(e.marks||[],t);for(let e in r)n.setAttribute(Mx+e,{...r[e]});return n.insert(0,Ax(e).map(e=>Dx(e,t))),t.mapping.set(n,e),n},Dx=(e,t)=>e instanceof Array?Lre(e,t):Rre(e,t),Ox=e=>typeof e==`object`&&!!e,kx=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||Ox(o)&&Ox(s)&&kx(o,s)}return r},Ax=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},jx=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&P_(e.attributes||{}).length===t[n].marks.length&&R_(e.attributes,(e,r)=>{let i=Lx(r),a=t[n].marks;return a.find(e=>e.type.name===i)?kx(e,a.find(e=>e.type.name===i)?.attrs):!1}))},Mx=`ymark:`,Nx=e=>{let t={},n={};for(let r in e)r.startsWith(Mx)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},zre=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=Lx(n),i=t.find(e=>e.type.name===r);return i?kx(e[n],i.attrs):!1}):!1},Px=(e,t)=>{if(e instanceof rx&&!(t instanceof Array)&&Vx(e,t)){let n=Ax(t),r=Nx(e.getAttributes());return e._length===n.length&&zre(r.marks,t.marks)&&kx(r.plain,t.attrs)&&e.toArray().every((e,t)=>Px(e,n[t]))}return e instanceof ix&&t instanceof Array&&jx(e,t)},Fx=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),Ix=(e,t,n)=>{let r=e.toArray(),i=Ax(t),a=i.length,o=r.length,s=pg(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Fx(n.mapping.get(e),t))u=!0;else if(!Px(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Fx(n.mapping.get(e),t))u=!0;else if(!Px(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Bre=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof mx?t+=n.content.str:n.content instanceof fx&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},Vre=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Bre(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,zx(e.marks,n))})),{insert:o,remove:s,index:c}=kre(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},Hre=/(.*)(--[a-zA-Z0-9+/=]{8})$/,Lx=e=>Hre.exec(e)?.[1]??e,Rx=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(Lx(r),e[r]));return n},zx=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=ng(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Nre(e.toJSON())}`:e.type.name]=e.attrs}}),n},Bx=(e,t,n,r)=>{if(t instanceof rx&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof rx){let e=t.getAttributes(),i=n.attrs;for(let n in i)i[n]===null?t.removeAttribute(n):e[n]!==i[n]&&n!==`ychange`&&t.setAttribute(n,i[n]);for(let n in e)i[n]===void 0&&!n.startsWith(Mx)&&t.removeAttribute(n);let a=zx(n.marks||[],r);for(let n in a){let r=e[Mx+n];(r===void 0||!kx(r,a[n]))&&t.setAttribute(Mx+n,{...a[n]})}for(let n in e)n.startsWith(Mx)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=Ax(n),a=i.length,o=t.toArray(),s=o.length,c=pg(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Fx(r.mapping.get(e),t))if(Px(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!Fx(r.mapping.get(e),t))if(Px(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof ix&&c instanceof Array)jx(n,c)||Vre(n,c,r),l+=1;else{let i=n instanceof rx&&Vx(n,c),a=d instanceof rx&&Vx(d,f);if(i&&a){let e=Ix(n,c,r),t=Ix(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Bx(e,n,c,r),l+=1):a?(Bx(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[Dx(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof ix?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(Dx(i[t],r));t.insert(l,e)}},jre)},Vx=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,Ure=(e,t)=>{let n=e.toArray().map(e=>Ex(e,t,Pre())).filter(e=>e!==null);return Lr.fromArray(n)},Hx=(e,t)=>t.topNodeType.create(null,Ure(e,t));function Ux(e,t,n,r){let{body:i}=bi(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Po(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Ao.parseWithFallback(i,Wx(n)))}function Wx(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Gx(e){return Ao.serialize(Hx(e,ko).toJSON())}function Kx(e,t,n,r,i,a){let o=Gx(r),s=Ao.serialize(n),{body:c}=bi(e.baselineFullMd),l=Ao.serialize(Ao.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:Ue(i,t).md})}function qx(e,t,n,r,i,a){Po(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=Ux(e,t,r,i),l=ko.nodeFromJSON(c),u=a?Gx(n):void 0;if(s!==t&&$t(o,s,t),Bx(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=bi(a.baselineFullMd);Kx(a,u,c,n,e,Wx(r))}})}function Jx(e,t,n,r,i){Po(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=Ux(e,t,n,r),c=ko.nodeFromJSON(s),l=i?Gx(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Bx(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=bi(i.baselineFullMd);Kx(i,l,s,a,e,Wx(n))}})}function Wre(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=bi(e.getText(`source`).toString()),o=Wx(t),s=Ao.parseWithFallback(a,o),c=ko.nodeFromJSON(s),l=n?Ao.serialize(Hx(r,ko).toJSON()):void 0;if(Bx(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Ao.serialize(Hx(r,ko).toJSON()),t=Ao.serialize(s),{body:a}=bi(n.baselineFullMd),c=Ao.serialize(Ao.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:Ue(i,l).md})}}const Gre=L(`loss-capture`),Yx=`detector-trip`,Xx=`backstop-trip`,Zx=`checkpoint-write`;M({ts:N(),schemaVersion:N(),seq:N(),event:F(),docName:F(),writerId:F().nullable(),site:F().optional(),direction:F().optional(),lostLen:N().optional(),digest:F().optional(),checkpointSha:F().optional()});const Qx=[`.ok`,`local`,`loss-capture`];function Kre(e){return z(e,...Qx,`loss-current.jsonl`)}function qre(e){return z(e,...Qx,`loss-prev.jsonl`)}var Jre=class{#e;#t;#n=new Map;constructor(e){this.#e=new vs({currentPath:Kre(e.projectDir),previousPath:qre(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{Gre.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const $x=L(`checkpoint-chain`);async function eS(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw $x.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
@@ -24,7 +24,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D
24
24
  `))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())}),i.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`)}),i.on(`exit`,(t,n)=>{if(e.child=null,e.terminals?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;let r=e.stderrTail.slice(-10).join(`
25
25
  `);this.emitStatus(e,e.info.status===`error`?`error`:`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),i.stdin===null||i.stdout===null)throw new fD(`spawn-failed`,`agent process has no stdio`);let a=Hne(Tu.toWeb(i.stdin),Cu.toWeb(i.stdout)),o=new Soe({defaultCwd:e.cwd,emit:t=>this.appendEvent(e,t),log:this.opts.log});e.terminals=o;let s=Wh({name:`open-knowledge`}).onRequest(ch.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(ch.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(ch.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(ch.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),o.create(t.params))).onRequest(ch.client.terminal.output,e=>o.output(e.params.terminalId)).onRequest(ch.client.terminal.waitForExit,e=>o.waitForExit(e.params.terminalId)).onRequest(ch.client.terminal.kill,async e=>(await o.kill(e.params.terminalId),{})).onRequest(ch.client.terminal.release,async e=>(await o.release(e.params.terminalId),{})).onNotification(ch.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(a);e.conn=s,s.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let c;try{c=await s.agent.request(ch.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(e){throw new fD(`spawn-failed`,`initialize failed: ${gD(e)}`)}return e.closed?null:{conn:s,init:c,launch:n}}async ensureLaunchable(e,t){try{return await CE(t),t}catch(n){if(!(n instanceof fE)||n.code!==`command-not-found`||t.kind!==`npx`&&t.kind!==`uvx`)throw n;let r=VE(t.kind);if(!XE(r))throw n;let i=await this.provideManagedRuntime(e,r);if(i===null)return null;let a=yE(t,i);return await CE(a),a}}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root,r=await $E(t,n).catch(()=>null);if(r!==null)return r;let i=(await nD(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new fE(`command-not-found`,Moe(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=HE(t).displayName;throw new fE(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=HE(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:n,runtime:t,displayName:r.displayName,provides:r.provides,version:r.version,approxSizeMB:r.approxSizeMB,sourceHost:r.sourceHost,agentName:e.info.agent.name,ts:Date.now()}),new Promise(r=>{let i=setTimeout(()=>{e.pendingRuntimeConsent.delete(n),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:n,decision:`timeout`,ts:Date.now()}),r(`timeout`)},3e5);i.unref?.(),e.pendingRuntimeConsent.set(n,{runtime:t,resolve:r,timer:i})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;n.remember===!0&&boe(i.runtime,a,this.opts.log,this.opts.runtimeInstall?.consentHome),this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return yoe(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[{name:XT,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Wi,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=jd[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof fE||t instanceof fD?t.message:String(t);this.emitStatus(e,`error`,n);return}if(r===null)return;let{conn:i,init:a,launch:o}=r,s=await this.buildMcpServers(e,a);try{let t=await i.agent.request(ch.agent.session.new,{cwd:e.cwd,mcpServers:s});e.sessionId=t.sessionId,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),t.modes!==void 0&&t.modes!==null&&(e.info.modes=t.modes,this.emitInfo(e)),t.configOptions!==void 0&&t.configOptions!==null&&(e.info.configOptions=t.configOptions,this.emitInfo(e))}catch(t){let n=(a.authMethods??[]).map(e=>typeof e==`object`&&e?e.name:null).filter(e=>typeof e==`string`);n.length>0?this.emitStatus(e,`auth_required`,`sign in first (${n.join(` / `)}), then start a new thread — ${gD(t)}`):this.emitStatus(e,`error`,`session setup failed: ${gD(t)}`);return}e.closed||t.settings?.config!==void 0&&(await this.applyInitialConfig(e,i,t.settings.config),e.closed)||t.settings?.modeId!==void 0&&(await this.applyInitialMode(e,i,t.settings.modeId),e.closed)||(this.setPresence(e,`idle`),this.emitStatus(e,`ready`),this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),t.prompt!==void 0&&t.prompt!==``&&this.sendPrompt(e.info.threadId,t.prompt))}async resumeThread(e,t){if(this.destroyed)throw new fD(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new fD(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new fD(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new fD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.resumeInFlight=!0;let r=Date.now();try{await this.ensureLogResolved(n);let i=n.sessionId,{info:a,custom:o}=await this.resolveAgentInfo(n.agentRef);if(this.destroyed)throw new fD(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new fD(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.stderrTail=[],n.midTurnOnDisk&&(n.midTurnOnDisk=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),t!==void 0&&t!==``&&(this.echoUserMessage(n,t),this.flushBroadcast(n)),this.emitStatus(n,`installing`);try{if(i===null)throw new fD(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new fD(`not-ready`,`thread closed during resume`);let{conn:s,init:c}=a,l=await this.buildMcpServers(n,c),u=c.agentCapabilities,d=u?.sessionCapabilities?.resume!=null,f;if(d)f=await s.agent.request(ch.agent.session.resume,{sessionId:i,cwd:n.cwd,mcpServers:l});else if(u?.loadSession===!0){n.suppressUpdates=!0,n.lastSuppressedAt=Date.now();try{f=await s.agent.request(ch.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new fD(`resume-unsupported`,`${n.info.agent.name} doesn't support resuming previous sessions`);n.sessionId=i;let p=f.modes;p!=null&&(n.info.modes=p);let m=f.configOptions;return m!=null&&(n.info.configOptions=m),this.setPresence(n,`idle`),this.emitStatus(n,`ready`),this.opts.log.info({threadId:e,agentId:n.info.agent.id,method:d?`session/resume`:`session/load`,msToResumed:Date.now()-r},`[acp-threads] thread resumed`),t!==void 0&&t!==``&&this.dispatchPrompt(n,t,{echo:!1}),{...n.info}}catch(e){throw await this.abortResume(n),e instanceof fD?e:e instanceof fE?new fD(e.code===`install-failed`?`install-failed`:`spawn-failed`,e.message):new fD(`resume-unsupported`,`couldn't resume the previous session: ${gD(e)}`)}}finally{n.resumeInFlight=!1}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await FE(t,{graceMs:dD}),e.child=null,e.conn=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(Xh(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new fD(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new fD(`not-ready`,`the thread is still resuming`);if(n.sessionId===null||n.conn===null)throw new fD(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new fD(`not-ready`,`20 messages are already waiting — let the agent catch up`);n.info.queue=[...e,{id:crypto.randomUUID(),content:t,ts:Date.now()}],n.info.lastActivityAt=Date.now(),this.emitInfo(n);return}this.dispatchPrompt(n,t,{echo:!0})}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];i.some(e=>e.id===t)&&(r.info.queue=i.map(e=>e.id===t?{...e,content:n}:e),this.emitInfo(r))}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);i.length!==r.length&&(n.info.queue=i.length>0?i:void 0,this.emitInfo(n))}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let[n,...r]=t;return e.info.queue=r.length>0?r:void 0,n??null}echoUserMessage(e,t){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=Ooe(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}this.appendEvent(e,{kind:`user_message`,content:t,ts:Date.now()})}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new fD(`not-ready`,`the thread is closing`);let r=lD(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n){if(e.sessionId===null||e.conn===null)throw new fD(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`),this.setPresence(e,`writing`);let r=e.sessionId;e.conn.agent.request(ch.agent.session.prompt,{sessionId:r,prompt:[{type:`text`,text:t}]}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeNextQueued(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}this.emitStatus(e,`ready`),this.setPresence(e,`idle`)}}).catch(t=>{e.turnActive=!1,!e.closed&&(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.cancelRequested?this.emitStatus(e,`ready`):this.emitStatus(e,`error`,`prompt failed: ${gD(t)}`),this.setPresence(e,`idle`))})}cancel(e){let t=this.mustGet(e);t.info.queue!==void 0&&(t.info.queue=void 0,this.emitInfo(t)),!(t.conn===null||t.sessionId===null)&&(t.turnActive&&(t.cancelRequested=!0),this.failPendingPermissions(t),this.restoreRunningAfterPermission(t),t.conn.agent.notify(ch.agent.session.cancel,{sessionId:t.sessionId}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new fD(`not-ready`,`thread has no live agent session`);n.conn.agent.request(ch.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new fD(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(ch.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!hD(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(ch.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(ch.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&hD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(ch.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;if(r!==null&&(await FE(r,{graceMs:t?.killGraceMs??5e3})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(Xh(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)}),!n.hadUserMessage){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new fD(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new fD(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:dD})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:eE(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await vu(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await vu(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
26
26
  `),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
27
- `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=IT(t.dc.document);FT(t.dc.document,n,`replace`,i,void 0,NT(t));let a=Qa(r,IT(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,`writing`,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-C9U9YUGm.mjs`);await e(R(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return Aoe(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new fD(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&aE(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>uD){let t=e.events.length-uD;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n){(t===`exited`||t===`error`)&&(e.info.queue=void 0),e.info.status=t,e.info.lastActivityAt=Date.now(),this.appendEvent(e,{kind:`status`,status:t,detail:n,ts:Date.now()}),this.emitInfo(e)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,...n}=e.info;return{version:1,info:n,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t,n){let r=this.opts.agentPresenceBroadcaster;if(r!=null)try{let i=Jr(e.info.agent.id),a=Br[i]??ea(e.agentSessionId);r.setPresence(Xh(e.agentSessionId),{displayName:e.info.agent.name,icon:i,color:a,currentDoc:n??e.docName??`(agent thread)`,mode:t,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function Aoe(e,t,n){let r=await bu(e),i=Nl(Ml(t)?t:V(r,t)),a=i,o=``;for(;;)try{let e=await bu(a),i=o===``?e:z(e,o),s=B(r,i);if(s===``||s.startsWith(`..`)||Ml(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Fl).join(`/`),t=s.split(Fl).join(`/`);!lC(e)&&!uC(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Fl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=R(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):z(a.slice(t.length+1),o),a=t}}function joe(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function hD(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function Moe(e){let t=HE(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function gD(e){if(e instanceof Error){let t=e.data;if(t!=null)try{return`${e.message} (${JSON.stringify(t).slice(0,300)})`}catch{return e.message}return e.message}return String(e)}const Noe=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`queue_edit`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`delete`,`list`]);function Poe(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!Noe.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function _D(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Foe(e,t,n));e.on(`message`,e=>{let s=Poe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`queue_edit`:t.editQueued(s.threadId,s.id,s.content);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof fD?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof fD)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Foe(e,t,n){return{op:`error`,code:e,message:t,...n}}var vD=class{hocuspocus;log=L(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){Zh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){Zh(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Ioe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Ioe(e){return e?.awareness??null}var yD=class{hocuspocus;log=L(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!Zh(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!Zh(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!Zh(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!Zh(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return fae(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Loe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Loe(e){return e?.awareness??null}var bD=class extends Error{};const Roe=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],xD=1024*1024;async function SD(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new bD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new bD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new bD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new bD(`Website skill fetch exceeded 5 redirects: ${t}`)}function CD(e){let t;try{t=new URL(e)}catch{throw new bD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new bD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new bD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function wD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function zoe(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!wD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&wD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function Boe(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function TD(e,t,n){let r=[];for(let i of Roe){let a=new URL(i,e).href;try{let o=await SD(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>xD){r.push(`${i}: index exceeds ${xD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=zoe(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new bD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function Voe(e,t={}){let{skills:n}=t.index??await ED(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function ED(e,t={}){let n=CD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new bD(`No fetch implementation available.`);return TD(n,r,t.timeoutMs??15e3)}async function Hoe(e,t={}){if(!wD(e.skill)||e.skill.includes(`/`))throw new bD(`Invalid website skill name: ${e.skill}`);let n=CD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new bD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await TD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new bD(`Website skill index does not contain ${e.skill}`);let c=Yl(z(pu(),`ok-skill-site-`)),l=z(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await SD(r,Boe(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new bD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new bD(`Website skill file exceeds ${Bi} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new bD(`Website skill file exceeds ${Bi} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new bD(`Website skill bundle exceeds ${Zt} bytes.`);let d=z(l,...e.split(`/`));Jl(R(d),{recursive:!0}),ou(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>nu(c,{recursive:!0,force:!0})}}catch(t){throw nu(c,{recursive:!0,force:!0}),t instanceof bD?t:new bD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const Uoe=zu(wl),Woe=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,DD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function OD(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return DD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=Woe.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function kD(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function AD(e,t={}){if(e.kind===`well-known`)return Hoe(e,t);if(e.kind===`local`){let t=V(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!H(t))throw new bD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!DD.some(t=>t.test(e.url)))throw new bD(`Unsupported git transport: ${e.url}`);let n=Yl(z(pu(),`ok-skill-import-`));try{await Uoe(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){nu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new bD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Tl(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?V(n,e.subpath):n,a=B(n,i);if(a.startsWith(`..`)||Ml(a))throw nu(n,{recursive:!0,force:!0}),new bD(`subpath escapes the clone: ${e.subpath}`);if(!H(i))throw nu(n,{recursive:!0,force:!0}),new bD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>nu(n,{recursive:!0,force:!0})}}const jD=[`.ok`,`skills-lock.json`],Goe=ue({source:F(),pluginProvider:F().optional(),skill:F().optional(),ref:F().optional(),contentHash:F(),files:j(F()).optional(),localHash:F().optional(),baselineRef:F().optional(),publisher:F().optional(),importedAt:i(),autoUpdate:D().optional()}),Koe=ue({schema:k(1),skills:E(F(),Goe).default({})});function MD(){return{schema:1,skills:{}}}function ND(e){let t;try{t=JSON.parse(e)}catch{return null}let n=Koe.safeParse(t);return n.success?n.data:null}function PD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}function qoe(e,t,n){return e.startsWith(`open-knowledge-pack-`)?{source:Fn,skill:e,contentHash:t,importedAt:n}:null}function Joe(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function FD(e,t){let n=t,r=``,{frontmatter:i}=bi(e);if(i!==``){let{map:e}=lt(Sr(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const ID=new Set([`.git`,`node_modules`]),Yoe=new Set([...ID,`scripts`,`references`]);function Xoe(e){let t=[],n=r=>{for(let i of $l(r,{withFileTypes:!0})){let a=z(r,i.name);if(i.isDirectory()){ID.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=B(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=U(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function LD(e){let t=z(e,`SKILL.md`);return H(t)?FD(U(t,`utf-8`),kl(e)):null}function RD(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=H(z(e,`SKILL.md`))?iu(z(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${Bi}.`;if(n>67108864)return`Skill exceeds ${Zt} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=$l(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=z(o,c.name);if(c.isDirectory()){ID.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=B(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=iu(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${Bi}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${Zt} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function zD(e){let t=z(e,`SKILL.md`);if(!H(t))return null;let n=U(t,`utf-8`),{name:r,description:i}=FD(n,kl(e)),a=Xoe(e),o=Du(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
27
+ `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=IT(t.dc.document);FT(t.dc.document,n,`replace`,i,void 0,NT(t));let a=Qa(r,IT(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,`writing`,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-WMTb98_i.mjs`);await e(R(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return Aoe(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new fD(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&aE(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>uD){let t=e.events.length-uD;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n){(t===`exited`||t===`error`)&&(e.info.queue=void 0),e.info.status=t,e.info.lastActivityAt=Date.now(),this.appendEvent(e,{kind:`status`,status:t,detail:n,ts:Date.now()}),this.emitInfo(e)}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,...n}=e.info;return{version:1,info:n,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t,n){let r=this.opts.agentPresenceBroadcaster;if(r!=null)try{let i=Jr(e.info.agent.id),a=Br[i]??ea(e.agentSessionId);r.setPresence(Xh(e.agentSessionId),{displayName:e.info.agent.name,icon:i,color:a,currentDoc:n??e.docName??`(agent thread)`,mode:t,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function Aoe(e,t,n){let r=await bu(e),i=Nl(Ml(t)?t:V(r,t)),a=i,o=``;for(;;)try{let e=await bu(a),i=o===``?e:z(e,o),s=B(r,i);if(s===``||s.startsWith(`..`)||Ml(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Fl).join(`/`),t=s.split(Fl).join(`/`);!lC(e)&&!uC(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Fl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=R(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):z(a.slice(t.length+1),o),a=t}}function joe(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function hD(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function Moe(e){let t=HE(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function gD(e){if(e instanceof Error){let t=e.data;if(t!=null)try{return`${e.message} (${JSON.stringify(t).slice(0,300)})`}catch{return e.message}return e.message}return String(e)}const Noe=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`queue_edit`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`delete`,`list`]);function Poe(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!Noe.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function _D(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Foe(e,t,n));e.on(`message`,e=>{let s=Poe(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`queue_edit`:t.editQueued(s.threadId,s.id,s.content);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof fD?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof fD)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Foe(e,t,n){return{op:`error`,code:e,message:t,...n}}var vD=class{hocuspocus;log=L(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){Zh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){Zh(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Ioe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Ioe(e){return e?.awareness??null}var yD=class{hocuspocus;log=L(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!Zh(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!Zh(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!Zh(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!Zh(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return fae(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(za);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Loe(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Loe(e){return e?.awareness??null}var bD=class extends Error{};const Roe=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],xD=1024*1024;async function SD(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new bD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new bD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new bD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new bD(`Website skill fetch exceeded 5 redirects: ${t}`)}function CD(e){let t;try{t=new URL(e)}catch{throw new bD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new bD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new bD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function wD(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function zoe(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!wD(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&wD(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function Boe(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function TD(e,t,n){let r=[];for(let i of Roe){let a=new URL(i,e).href;try{let o=await SD(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>xD){r.push(`${i}: index exceeds ${xD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=zoe(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new bD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function Voe(e,t={}){let{skills:n}=t.index??await ED(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function ED(e,t={}){let n=CD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new bD(`No fetch implementation available.`);return TD(n,r,t.timeoutMs??15e3)}async function Hoe(e,t={}){if(!wD(e.skill)||e.skill.includes(`/`))throw new bD(`Invalid website skill name: ${e.skill}`);let n=CD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new bD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await TD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new bD(`Website skill index does not contain ${e.skill}`);let c=Yl(z(pu(),`ok-skill-site-`)),l=z(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await SD(r,Boe(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new bD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new bD(`Website skill file exceeds ${Bi} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new bD(`Website skill file exceeds ${Bi} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new bD(`Website skill bundle exceeds ${Zt} bytes.`);let d=z(l,...e.split(`/`));Jl(R(d),{recursive:!0}),ou(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>nu(c,{recursive:!0,force:!0})}}catch(t){throw nu(c,{recursive:!0,force:!0}),t instanceof bD?t:new bD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const Uoe=zu(wl),Woe=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,DD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function OD(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return DD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=Woe.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function kD(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function AD(e,t={}){if(e.kind===`well-known`)return Hoe(e,t);if(e.kind===`local`){let t=V(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!H(t))throw new bD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!DD.some(t=>t.test(e.url)))throw new bD(`Unsupported git transport: ${e.url}`);let n=Yl(z(pu(),`ok-skill-import-`));try{await Uoe(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){nu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new bD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Tl(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?V(n,e.subpath):n,a=B(n,i);if(a.startsWith(`..`)||Ml(a))throw nu(n,{recursive:!0,force:!0}),new bD(`subpath escapes the clone: ${e.subpath}`);if(!H(i))throw nu(n,{recursive:!0,force:!0}),new bD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>nu(n,{recursive:!0,force:!0})}}const jD=[`.ok`,`skills-lock.json`],Goe=ue({source:F(),pluginProvider:F().optional(),skill:F().optional(),ref:F().optional(),contentHash:F(),files:j(F()).optional(),localHash:F().optional(),baselineRef:F().optional(),publisher:F().optional(),importedAt:i(),autoUpdate:D().optional()}),Koe=ue({schema:k(1),skills:E(F(),Goe).default({})});function MD(){return{schema:1,skills:{}}}function ND(e){let t;try{t=JSON.parse(e)}catch{return null}let n=Koe.safeParse(t);return n.success?n.data:null}function PD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}function qoe(e,t,n){return e.startsWith(`open-knowledge-pack-`)?{source:Fn,skill:e,contentHash:t,importedAt:n}:null}function Joe(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function FD(e,t){let n=t,r=``,{frontmatter:i}=bi(e);if(i!==``){let{map:e}=lt(Sr(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const ID=new Set([`.git`,`node_modules`]),Yoe=new Set([...ID,`scripts`,`references`]);function Xoe(e){let t=[],n=r=>{for(let i of $l(r,{withFileTypes:!0})){let a=z(r,i.name);if(i.isDirectory()){ID.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=B(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=U(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function LD(e){let t=z(e,`SKILL.md`);return H(t)?FD(U(t,`utf-8`),kl(e)):null}function RD(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=H(z(e,`SKILL.md`))?iu(z(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${Bi}.`;if(n>67108864)return`Skill exceeds ${Zt} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=$l(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=z(o,c.name);if(c.isDirectory()){ID.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=B(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=iu(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${Bi}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${Zt} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function zD(e){let t=z(e,`SKILL.md`);if(!H(t))return null;let n=U(t,`utf-8`),{name:r,description:i}=FD(n,kl(e)),a=Xoe(e),o=Du(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
28
28
  `);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function BD(e){if(H(z(e,`SKILL.md`)))return[{name:kl(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(H(z(e,`SKILL.md`))){t.push({name:kl(e),dir:e});return}let a;try{a=$l(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!Yoe.has(t.name)&&r(z(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function VD(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;!i||!r||n.push({id:i,name:typeof t.name==`string`&&t.name?t.name:Mn(i),source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:uo(r)})}return n}const Zoe={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&#x27;":`'`,"&apos;":`'`};function Qoe(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>Zoe[e]??e)}function $oe(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=Qoe(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function ese(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:Mn(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:uo(r)})}return n}function HD(e){return e.trim().toLowerCase()}function tse(e){return e.split(`/`).filter(Boolean).pop()??e}function UD(e){let t=Nr(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=kD(e);if(!n)return null;let r=Nr(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function WD(e,t,n={}){let r=UD(e);if(r){let e=t??r.skill;if(!e)throw new bD(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=kD(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new bD(`No fetch implementation available.`);let o=t??i.skill,s=HD(o),c=HD(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new bD(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof bD?e:new bD(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=VD(l).find(e=>{if((e.publisher?HD(e.publisher):``)!==c)return!1;let t=HD(e.name),n=HD(tse(e.id));return t===s||n===s});if(!u)throw new bD(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=Nr(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:OD(u.source);if(!f||f.kind===`local`)throw new bD(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const GD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function KD(e){let t=GD.indexOf(e);return t===-1?GD.length:t}function qD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=KD(e.editor)-KD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function JD(e){if(!H(e))return[];try{return $l(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>z(e.parentPath,e.name)).sort()}catch{return[]}}function YD(e,t,n,r){let i=z(e,`SKILL.md`);if(!H(i))return null;let a=kl(e),o=a,s=``;try{({name:o,description:s}=FD(U(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:JD(z(e,`scripts`)),references:JD(z(e,`references`)),provenance:n,inert:r}}function XD(e){if(!H(e))return[];try{return $l(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function nse(e){let t=e=>{try{return iu(e).isDirectory()}catch{return!1}};return{commands:t(z(e,`commands`)),hooks:t(z(e,`hooks`)),mcp:H(z(e,`.mcp.json`))}}const rse={commands:!1,hooks:!1,mcp:!1};function ZD(e,t){let n=[];for(let r of XD(e)){let i=YD(z(e,r),t,{},rse);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function QD(e){try{return $l(e).length>0}catch{return!1}}function ise(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=$l(e,{withFileTypes:!0})}catch{return}if(H(z(e,`SKILL.md`))||H(z(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(z(e,t.name),r+1)};return n(z(e,`skills`),0),[...t].sort()}function ase(e){return{commands:QD(z(e,`commands`)),hooks:QD(z(e,`hooks`))||H(z(e,`hooks.json`)),mcp:H(z(e,`.mcp.json`)),agents:QD(z(e,`agents`))}}function ose(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function sse(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!H(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function cse(e){let t=z(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(U(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function lse(e,t){let n=z(e,`installed_plugins.json`);if(!H(n))return[];let r;try{r=JSON.parse(U(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=ose(e);for(let e of sse(n)){let n=e.installPath,o=nse(n),s=cse(n),c=z(n,`skills`),l=[];for(let n of XD(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=YD(z(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const $D=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,use=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,dse=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function eO(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function fse(e){let t=use.exec(eO(e));if(!t)return null;try{let e=U(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function tO(e,t){let n=V(e);try{iu(n).isDirectory()||(n=R(n))}catch{return null}let r=V(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(U(z(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=R(n)}return null}function pse(e){let t=eO(e),n=$D.exec(t);if(n){let t=tO(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=dse.exec(t);if(!r)return null;let i=tO(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function mse(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function hse(e){let t=eO(e),n=$D.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=$l(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=mse(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return H(c)?c:e}function nO(e,t){for(let n of t)try{let t=JSON.parse(U(z(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function gse(e){let t=nO(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(U(z(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const _se={id:`claude`,homes:e=>[{harness:`claude`,dir:z(e,`.claude`,`plugins`)}],enumerate:lse,inspectSource:pse,repositoryUrl:fse,resolveUpdateSource:hse,detectDir:gse};function rO(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=nO(e,t);return n?{...n,setupSupported:!1}:null}}}function vse(e,t){try{return JSON.parse(U(z(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const iO=[_se,rO(`codex`,[`.codex-plugin/plugin.json`]),rO(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=nO(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!vse(e,`plugin.json`))return null;let n=nO(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function aO(e){return iO.find(t=>t.id===e)}function oO(e){if(e===void 0)return iO;let t=aO(e);return t?[t]:[]}function yse(e){return iO.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function sO(e,t,n=e){let r=aO(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function cO(e,t){for(let n of oO(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function lO(e){for(let t of iO){let n=t.detectDir(e);if(!n)continue;let r=ise(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:ase(e),setupSupported:n.setupSupported}}return null}function uO(e,t){for(let n of oO(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function dO(e,t){for(let n of oO(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function fO(e=uu()){let t=xo.flatMap(t=>{let n=Jn[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:z(e,...n.split(`/`))}]});return[...yse(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:z(e,`.agents`,`skills`)}]}function pO(e){return xo.flatMap(t=>{let n=Dt[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:z(e,...n.split(`/`))}]})}function mO(e){return Object.keys(e.provenance).length>0}function hO(e){return e.provenance.plugin!==void 0}function gO(e,t){if(hO(e)!==hO(t))return hO(e)?e:t;if(mO(e)!==mO(t))return mO(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function _O(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function vO(e){try{return zD(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function yO(e){let t=new Map;for(let n of e){let e=Xe(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${vO(n)}`,i=t.get(r);i?(i.winner=gO(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>_O(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||Xe(e.provenance.scope).localeCompare(Xe(t.provenance.scope))||e.home.localeCompare(t.home))}function bO(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function xO(e={}){let t=[];for(let n of fO(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...sO(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...ZD(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...SO(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>eo(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:yO(n.flatMap(e=>e.skills)),packs:bO(n)}}function SO(e){let t=TO(V(e,`.ok`,`skills`)),n=[];for(let r of pO(e))try{for(let i of ZD(r.dir,r.harness)){let r=i.skills.filter(e=>!wO(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>CO(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function CO(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function wO(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=TO(e.home);return n===t||n.startsWith(t+Fl)}function TO(e){try{return W(e)}catch{return V(e)}}function EO(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const DO=[`skillId`,`source`,`installs`];function OO(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*kO(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!DO.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield OO(r)}}}}function AO(e){let t=EO(e),n=[];for(let e of kO(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function jO(e){let t=new Map;for(let n of AO(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:uo(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function MO(e,t){return`${e}/${t}`}function NO(e){if(e.preferredSource===!0)return-1;let t=GD.indexOf(e.editor);return t===-1?GD.length:t}function PO(e){let t=qD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=MO(e.scope,e.name),o=NO(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var FO=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),IO=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),LO=n(((t,n)=>{let{Readable:r,Writable:i}=e(`stream`),a=IO(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=FO(),d=Buffer.from(`\r
29
29
  `),f=Buffer.from(`\r`),p=Buffer.from(`-`);function m(){}let h=16*1024;var g=class{constructor(e){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0,this.cb=e}reset(){this.header=Object.create(null),this.pairCount=0,this.byteCount=0,this.state=0,this.name=``,this.value=``,this.crlf=0}push(e,t,n){let r=t;for(;t<n;)switch(this.state){case 0:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(w[n]!==1){if(n!==58||(this.name+=e.latin1Slice(r,t),this.name.length===0))return-1;++t,i=!0,this.state=1;break}}if(!i){this.name+=e.latin1Slice(r,t);break}}case 1:{let i=!1;for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(n!==32&&n!==9){r=t,i=!0,this.state=2;break}}if(!i)break}case 2:switch(this.crlf){case 0:for(;t<n;++t){if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];if(T[n]!==1){if(n!==13)return-1;++this.crlf;break}}this.value+=e.latin1Slice(r,t++);break;case 1:if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;++this.crlf;break;case 2:{if(this.byteCount===h)return-1;++this.byteCount;let n=e[t];n===32||n===9?(r=t,this.crlf=0):(++this.pairCount<2e3&&(this.name=this.name.toLowerCase(),this.header[this.name]===void 0?this.header[this.name]=[this.value]:this.header[this.name].push(this.value)),n===13?(++this.crlf,++t):(r=t,this.crlf=0,this.state=0,this.name=``,this.value=``));break}case 3:{if(this.byteCount===h||(++this.byteCount,e[t++]!==10))return-1;let n=this.header;return this.reset(),this.cb(n),t}}break}return t}},_=class extends r{constructor(e,t){super(e),this.truncated=!1,this._readcb=null,this.once(`end`,()=>{if(this._read(),--t._fileEndsLeft===0&&t._finalcb){let e=t._finalcb;t._finalcb=null,process.nextTick(e)}})}_read(e){let t=this._readcb;t&&(this._readcb=null,t())}};let v={push:(e,t)=>{},destroy:()=>{}};function y(e,t){let n=e._writecb;e._writecb=null,t?e.destroy(t):n&&n()}function b(e,t){return e}var x=class extends i{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};if(super(t),!e.conType.params||typeof e.conType.params.boundary!=`string`)throw Error(`Multipart: Boundary not found`);let n=e.conType.params.boundary,r=typeof e.defParamCharset==`string`&&e.defParamCharset?c(e.defParamCharset):b,i=e.defCharset||`utf8`,h=e.preservePath,y={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.fileHwm==`number`?e.fileHwm:void 0},x=e.limits,S=x&&typeof x.fieldSize==`number`?x.fieldSize:1*1024*1024,C=x&&typeof x.fileSize==`number`?x.fileSize:1/0,w=x&&typeof x.files==`number`?x.files:1/0,T=x&&typeof x.fields==`number`?x.fields:1/0,ee=x&&typeof x.parts==`number`?x.parts:1/0,te=-1,ne=0,re=0,ie=!1;this._fileEndsLeft=0,this._fileStream=void 0,this._complete=!1;let E=0,D,ae=0,O,oe,se,k,ce=!1,le=!1,ue=!1;this._hparser=null;let de=new g(e=>{this._hparser=null,ie=!1,se=`text/plain`,O=i,oe=`7bit`,k=void 0,ce=!1;let t;if(!e[`content-disposition`]){ie=!0;return}let n=u(e[`content-disposition`][0],r);if(!n||n.type!==`form-data`){ie=!0;return}if(n.params&&(n.params.name&&(k=n.params.name),n.params[`filename*`]?t=n.params[`filename*`]:n.params.filename&&(t=n.params.filename),t!==void 0&&!h&&(t=o(t))),e[`content-type`]){let t=l(e[`content-type`][0]);t&&(se=`${t.type}/${t.subtype}`,t.params&&typeof t.params.charset==`string`&&(O=t.params.charset.toLowerCase()))}if(e[`content-transfer-encoding`]&&(oe=e[`content-transfer-encoding`][0].toLowerCase()),se===`application/octet-stream`||t!==void 0){if(re===w){le||(le=!0,this.emit(`filesLimit`)),ie=!0;return}if(++re,this.listenerCount(`file`)===0){ie=!0;return}E=0,this._fileStream=new _(y,this),++this._fileEndsLeft,this.emit(`file`,k,this._fileStream,{filename:t,encoding:oe,mimeType:se})}else{if(ne===T){ue||(ue=!0,this.emit(`fieldsLimit`)),ie=!0;return}if(++ne,this.listenerCount(`field`)===0){ie=!0;return}D=[],ae=0}}),fe=0,A=(e,t,n,r,i)=>{retrydata:for(;t;){if(this._hparser!==null){let e=this._hparser.push(t,n,r);if(e===-1){this._hparser=null,de.reset(),this.emit(`error`,Error(`Malformed part header`));break}n=e}if(n===r)break;if(fe!==0){if(fe===1){switch(t[n]){case 45:fe=2,++n;break;case 13:fe=3,++n;break;default:fe=0}if(n===r)return}if(fe===2){if(fe=0,t[n]===45){this._complete=!0,this._bparser=v;return}let e=this._writecb;this._writecb=m,A(!1,p,0,1,!1),this._writecb=e}else if(fe===3)if(fe=0,t[n]===10){if(++n,te>=ee||(this._hparser=de,n===r))break;continue retrydata}else{let e=this._writecb;this._writecb=m,A(!1,f,0,1,!1),this._writecb=e}}if(!ie){if(this._fileStream){let e,a=Math.min(r-n,C-E);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),E+=e.length,E===C?(e.length>0&&this._fileStream.push(e),this._fileStream.emit(`limit`),this._fileStream.truncated=!0,ie=!0):this._fileStream.push(e)||(this._writecb&&(this._fileStream._readcb=this._writecb),this._writecb=null)}else if(D!==void 0){let e,a=Math.min(r-n,S-ae);i?e=t.slice(n,n+a):(e=Buffer.allocUnsafe(a),t.copy(e,0,n,n+a)),ae+=a,D.push(e),ae===S&&(ie=!0,ce=!0)}}break}if(e){if(fe=1,this._fileStream)this._fileStream.push(null),this._fileStream=null;else if(D!==void 0){let e;switch(D.length){case 0:e=``;break;case 1:e=s(D[0],O,0);break;default:e=s(Buffer.concat(D,ae),O,0)}D=void 0,ae=0,this.emit(`field`,k,e,{nameTruncated:!1,valueTruncated:ce,encoding:oe,mimeType:se})}++te===ee&&this.emit(`partsLimit`)}};this._bparser=new a(`\r\n--${n}`,A),this._writecb=null,this._finalcb=null,this.write(d)}static detect(e){return e.type===`multipart`&&e.subtype===`form-data`}_write(e,t,n){this._writecb=n,this._bparser.push(e,0),this._writecb&&y(this)}_destroy(e,t){this._hparser=null,this._bparser=v,e||=C(this);let n=this._fileStream;n&&(this._fileStream=null,n.destroy(e)),t(e)}_final(e){if(this._bparser.destroy(),!this._complete)return e(Error(`Unexpected end of form`));this._fileEndsLeft?this._finalcb=S.bind(null,this,e):S(this,e)}};function S(e,t,n){if(n)return t(n);n=C(e),t(n)}function C(e){if(e._hparser)return Error(`Malformed part header`);let t=e._fileStream;if(t&&(e._fileStream=null,t.destroy(Error(`Unexpected end of file`))),!e._complete)return Error(`Unexpected end of form`)}let w=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],T=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];n.exports=x})),RO=n(((t,n)=>{let{Writable:r}=e(`stream`),{getDecoder:i}=FO();var a=class extends r{constructor(e){let t={autoDestroy:!0,emitClose:!0,highWaterMark:typeof e.highWaterMark==`number`?e.highWaterMark:void 0};super(t);let n=e.defCharset||`utf8`;e.conType.params&&typeof e.conType.params.charset==`string`&&(n=e.conType.params.charset),this.charset=n;let r=e.limits;this.fieldSizeLimit=r&&typeof r.fieldSize==`number`?r.fieldSize:1*1024*1024,this.fieldsLimit=r&&typeof r.fields==`number`?r.fields:1/0,this.fieldNameSizeLimit=r&&typeof r.fieldNameSize==`number`?r.fieldNameSize:100,this._inKey=!0,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,this._fields=0,this._key=``,this._val=``,this._byte=-2,this._lastPos=0,this._encode=0,this._decoder=i(n)}static detect(e){return e.type===`application`&&e.subtype===`x-www-form-urlencoded`}_write(e,t,n){if(this._fields>=this.fieldsLimit)return n();let r=0,i=e.length;if(this._lastPos=0,this._byte!==-2){if(r=o(this,e,r,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();this._inKey?++this._bytesKey:++this._bytesVal}main:for(;r<i;)if(this._inKey){for(r=s(this,e,r,i);r<i;){switch(e[r]){case 61:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._inKey=!1;continue main;case 38:if(this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._key=this._decoder(this._key,this._encode),this._encode=0,this._bytesKey>0&&this.emit(`field`,this._key,``,{nameTruncated:this._keyTrunc,valueTruncated:!1,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue;case 43:this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._key+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesKey,r=s(this,e,r,i);continue}++r,++this._bytesKey,r=s(this,e,r,i)}this._lastPos<r&&(this._key+=e.latin1Slice(this._lastPos,r))}else{for(r=c(this,e,r,i);r<i;){switch(e[r]){case 38:if(this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=++r,this._inKey=!0,this._val=this._decoder(this._val,this._encode),this._encode=0,(this._bytesKey>0||this._bytesVal>0)&&this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`}),this._key=``,this._val=``,this._keyTrunc=!1,this._valTrunc=!1,this._bytesKey=0,this._bytesVal=0,++this._fields>=this.fieldsLimit)return this.emit(`fieldsLimit`),n();continue main;case 43:this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._val+=` `,this._lastPos=r+1;break;case 37:if(this._encode===0&&(this._encode=1),this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r)),this._lastPos=r+1,this._byte=-1,r=o(this,e,r+1,i),r===-1)return n(Error(`Malformed urlencoded form`));if(r>=i)return n();++this._bytesVal,r=c(this,e,r,i);continue}++r,++this._bytesVal,r=c(this,e,r,i)}this._lastPos<r&&(this._val+=e.latin1Slice(this._lastPos,r))}n()}_final(e){if(this._byte!==-2)return e(Error(`Malformed urlencoded form`));(!this._inKey||this._bytesKey>0||this._bytesVal>0)&&(this._inKey?this._key=this._decoder(this._key,this._encode):this._val=this._decoder(this._val,this._encode),this.emit(`field`,this._key,this._val,{nameTruncated:this._keyTrunc,valueTruncated:this._valTrunc,encoding:this.charset,mimeType:`text/plain`})),e()}};function o(e,t,n,r){if(n>=r)return r;if(e._byte===-1){let i=l[t[n++]];if(i===-1)return-1;if(i>=8&&(e._encode=2),n<r){let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((i<<4)+r):e._val+=String.fromCharCode((i<<4)+r),e._byte=-2,e._lastPos=n}else e._byte=i}else{let r=l[t[n++]];if(r===-1)return-1;e._inKey?e._key+=String.fromCharCode((e._byte<<4)+r):e._val+=String.fromCharCode((e._byte<<4)+r),e._byte=-2,e._lastPos=n}return n}function s(e,t,n,r){if(e._bytesKey>e.fieldNameSizeLimit){for(e._keyTrunc||e._lastPos<n&&(e._key+=t.latin1Slice(e._lastPos,n-1)),e._keyTrunc=!0;n<r;++n){let r=t[n];if(r===61||r===38)break;++e._bytesKey}e._lastPos=n}return n}function c(e,t,n,r){if(e._bytesVal>e.fieldSizeLimit){for(e._valTrunc||e._lastPos<n&&(e._val+=t.latin1Slice(e._lastPos,n-1)),e._valTrunc=!0;n<r&&t[n]!==38;++n)++e._bytesVal;e._lastPos=n}return n}let l=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];n.exports=a})),zO=t(n(((e,t)=>{let{parseContentType:n}=FO();function r(e){let t=e.headers,r=n(t[`content-type`]);if(!r)throw Error(`Malformed content type`);for(let n of i){if(!n.detect(r))continue;let i={limits:e.limits,headers:t,conType:r,highWaterMark:void 0,fileHwm:void 0,defCharset:void 0,defParamCharset:void 0,preservePath:!1};return e.highWaterMark&&(i.highWaterMark=e.highWaterMark),e.fileHwm&&(i.fileHwm=e.fileHwm),i.defCharset=e.defCharset,i.defParamCharset=e.defParamCharset,i.preservePath=e.preservePath,new n(i)}throw Error(`Unsupported content type: ${t[`content-type`]}`)}let i=[LO(),RO()].filter(function(e){return typeof e.detect==`function`});t.exports=e=>{if((typeof e!=`object`||!e)&&(e={}),typeof e.headers!=`object`||e.headers===null||typeof e.headers[`content-type`]!=`string`)throw Error(`Missing Content-Type`);return r(e)}}))(),1);const BO={128:`€`,130:`‚`,131:`ƒ`,132:`„`,133:`…`,134:`†`,135:`‡`,136:`ˆ`,137:`‰`,138:`Š`,139:`‹`,140:`Œ`,142:`Ž`,145:`‘`,146:`’`,147:`“`,148:`”`,149:`•`,150:`–`,151:`—`,152:`˜`,153:`™`,154:`š`,155:`›`,156:`œ`,158:`ž`,159:`Ÿ`},VO={};for(let[e,t]of Object.entries(BO))VO[t]=Number.parseInt(e,10);let HO;function UO(){if(globalThis.TextDecoder!==void 0)return HO??=new globalThis.TextDecoder(`utf-8`)}const WO=32*1024,GO=65533;function KO(e,t=`utf-8`){switch(t.toLowerCase()){case`utf-8`:case`utf8`:{let t=UO();return t?t.decode(e):XO(e)}case`utf-16le`:return ZO(e);case`us-ascii`:case`ascii`:return QO(e);case`latin1`:case`iso-8859-1`:return $O(e);case`windows-1252`:return ek(e);default:throw RangeError(`Encoding '${t}' not supported`)}}function qO(e,t){t.length!==0&&(e.push(String.fromCharCode.apply(null,t)),t.length=0)}function JO(e,t,n){t.push(n),t.length>=WO&&qO(e,t)}function YO(e,t,n){if(n<=65535){JO(e,t,n);return}n-=65536,JO(e,t,55296+(n>>10)),JO(e,t,56320+(n&1023))}function XO(e){let t=[],n=[],r=0;for(e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191&&(r=3);r<e.length;){let i=e[r];if(i<=127){JO(t,n,i),r++;continue}if(i<194||i>244){JO(t,n,GO),r++;continue}if(i<=223){if(r+1>=e.length){JO(t,n,GO),r++;continue}let a=e[r+1];if((a&192)!=128){JO(t,n,GO),r++;continue}JO(t,n,(i&31)<<6|a&63),r+=2;continue}if(i<=239){if(r+2>=e.length){JO(t,n,GO),r++;continue}let a=e[r+1],o=e[r+2];if(!((a&192)==128&&(o&192)==128&&!(i===224&&a<160)&&!(i===237&&a>=160))){JO(t,n,GO),r++;continue}JO(t,n,(i&15)<<12|(a&63)<<6|o&63),r+=3;continue}if(r+3>=e.length){JO(t,n,GO),r++;continue}let a=e[r+1],o=e[r+2],s=e[r+3];if(!((a&192)==128&&(o&192)==128&&(s&192)==128&&!(i===240&&a<144)&&!(i===244&&a>143))){JO(t,n,GO),r++;continue}YO(t,n,(i&7)<<18|(a&63)<<12|(o&63)<<6|s&63),r+=4}return qO(t,n),t.join(``)}function ZO(e){let t=[],n=[],r=e.length,i=0;for(;i+1<r;){let a=e[i]|e[i+1]<<8;if(i+=2,a>=55296&&a<=56319){if(i+1<r){let r=e[i]|e[i+1]<<8;r>=56320&&r<=57343?(JO(t,n,a),JO(t,n,r),i+=2):JO(t,n,GO)}else JO(t,n,GO);continue}if(a>=56320&&a<=57343){JO(t,n,GO);continue}JO(t,n,a)}return i<r&&JO(t,n,GO),qO(t,n),t.join(``)}function QO(e){let t=[];for(let n=0;n<e.length;n+=WO){let r=Math.min(e.length,n+WO),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t]&127;t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function $O(e){let t=[];for(let n=0;n<e.length;n+=WO){let r=Math.min(e.length,n+WO),i=Array(r-n);for(let t=n,a=0;t<r;t++,a++)i[a]=e[t];t.push(String.fromCharCode.apply(null,i))}return t.join(``)}function ek(e){let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=i>=128&&i<=159?BO[i]:void 0;n+=a??String.fromCharCode(i),n.length>=WO&&(t.push(n),n=``)}return n&&t.push(n),t.join(``)}function tk(e){return new DataView(e.buffer,e.byteOffset)}const nk={len:1,get(e,t){return tk(e).getUint8(t)},put(e,t,n){return tk(e).setUint8(t,n),t+1}},rk={len:2,get(e,t){return tk(e).getUint16(t,!0)},put(e,t,n){return tk(e).setUint16(t,n,!0),t+2}},ik={len:2,get(e,t){return tk(e).getUint16(t)},put(e,t,n){return tk(e).setUint16(t,n),t+2}},ak={len:4,get(e,t){return tk(e).getUint32(t,!0)},put(e,t,n){return tk(e).setUint32(t,n,!0),t+4}},ok={len:4,get(e,t){return tk(e).getUint32(t)},put(e,t,n){return tk(e).setUint32(t,n),t+4}},sk={len:4,get(e,t){return tk(e).getInt32(t)},put(e,t,n){return tk(e).setInt32(t,n),t+4}},ck={len:8,get(e,t){return tk(e).getBigUint64(t,!0)},put(e,t,n){return tk(e).setBigUint64(t,n,!0),t+8}};var lk=class{constructor(e,t){this.len=e,this.encoding=t}get(e,t=0){return KO(e.subarray(t,t+this.len),this.encoding)}},uk=class extends Error{constructor(){super(`End-Of-Stream`),this.name=`EndOfStreamError`}},dk=class extends Error{constructor(e=`The operation was aborted`){super(e),this.name=`AbortError`}},fk=class{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){let n=await this.read(e,t);return this.peekQueue.push(e.subarray(0,n)),n}async read(e,t=!1){if(e.length===0)return 0;let n=this.readFromPeekBuffer(e);if(this.endOfStream||(n+=await this.readRemainderFromStream(e.subarray(n),t)),n===0&&!t)throw new uk;return n}readFromPeekBuffer(e){let t=e.length,n=0;for(;this.peekQueue.length>0&&t>0;){let r=this.peekQueue.pop();if(!r)throw Error(`peekData should be defined`);let i=Math.min(r.length,t);e.set(r.subarray(0,i),n),n+=i,t-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t){let n=0;for(;n<e.length&&!this.endOfStream;){if(this.interrupted)throw new dk;let r=await this.readFromStream(e.subarray(n),t);if(r===0)break;n+=r}if(!t&&n<e.length)throw new uk;return n}},pk=class extends fk{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}},mk=class extends pk{async readFromStream(e,t){if(e.length===0)return 0;let n=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return n.done&&(this.endOfStream=n.done),n.value?(e.set(n.value),n.value.length):0}},hk=class extends fk{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){let n=Math.min(t.length,e.length);return e.set(t.subarray(0,n)),n<t.length?this.buffer=t.subarray(n):this.buffer=null,n}async readFromStream(e,t){if(e.length===0)return 0;let n=0;for(this.buffer&&(n+=this.writeChunk(e,this.buffer));n<e.length&&!this.endOfStream;){let t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(n+=this.writeChunk(e.subarray(n),t.value))}if(!t&&n===0&&this.endOfStream)throw new uk;return n}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}};function gk(e){try{let t=e.getReader({mode:`byob`});return t instanceof ReadableStreamDefaultReader?new hk(t):new mk(t)}catch(t){if(t instanceof TypeError)return new hk(e.getReader());throw t}}var _k=class{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=e?.onClose,e?.abortSignal&&e.abortSignal.addEventListener(`abort`,()=>{this.abort()})}async readToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.readBuffer(n,{position:t})<e.len)throw new uk;return e.get(n,0)}async peekToken(e,t=this.position){let n=new Uint8Array(e.len);if(await this.peekBuffer(n,{position:t})<e.len)throw new uk;return e.get(n,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new uk;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new uk;return e.get(this.numBuffer,0)}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);if(this.fileInfo.size!==void 0){let t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){await this.abort(),await this.onClose?.()}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&t.position!==void 0&&t.position<this.position)throw Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}},vk=class extends _k{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=t?.fileInfo??{}}async readBuffer(e,t){let n=this.normalizeOptions(e,t),r=n.position-this.position;if(r>0)return await this.ignore(r),this.readBuffer(e,t);if(r<0)throw Error("`options.position` must be equal or greater than `tokenizer.position`");if(n.length===0)return 0;let i=await this.streamReader.read(e.subarray(0,n.length),n.mayBeLess);if(this.position+=i,(!t||!t.mayBeLess)&&i<n.length)throw new uk;return i}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=0;if(n.position){let t=n.position-this.position;if(t>0){let i=new Uint8Array(n.length+t);return r=await this.peekBuffer(i,{mayBeLess:n.mayBeLess}),e.set(i.subarray(t)),r-t}if(t<0)throw Error(`Cannot peek from a negative offset in a stream`)}if(n.length>0){try{r=await this.streamReader.peek(e.subarray(0,n.length),n.mayBeLess)}catch(e){if(t?.mayBeLess&&e instanceof uk)return 0;throw e}if(!n.mayBeLess&&r<n.length)throw new uk}return r}async ignore(e){if(e<0)throw RangeError(`ignore length must be ≥ 0 bytes`);let t=Math.min(256e3,e),n=new Uint8Array(t),r=0;for(;r<e;){let i=e-r,a=await this.readBuffer(n,{length:Math.min(t,i)});if(a<0)return a;r+=a}return r}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}},yk=class extends _k{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...t?.fileInfo??{},size:e.length}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.uint8Array.length-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new uk;return e.set(this.uint8Array.subarray(n.position,n.position+r)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}},bk=class extends _k{constructor(e,t){super(t),this.blob=e,this.fileInfo={...t?.fileInfo??{},size:e.size,mimeType:e.type}}async readBuffer(e,t){t?.position&&(this.position=t.position);let n=await this.peekBuffer(e,t);return this.position+=n,n}async peekBuffer(e,t){let n=this.normalizeOptions(e,t),r=Math.min(this.blob.size-n.position,n.length);if(!n.mayBeLess&&r<n.length)throw new uk;let i=await this.blob.slice(n.position,n.position+r).arrayBuffer();return e.set(new Uint8Array(i)),r}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}};function xk(e,t){let n=gk(e),r=t??{},i=r.onClose;return r.onClose=async()=>{if(await n.close(),i)return i()},new vk(n,r)}function Sk(e,t){return new yk(e,t)}function Ck(e,t){return new bk(e,t)}var wk=t(Ts(),1);const Tk={LocalFileHeader:67324752,DataDescriptor:134695760,CentralFileHeader:33639248,EndOfCentralDirectory:101010256},Ek={get(e){return{signature:ak.get(e,0),compressedSize:ak.get(e,8),uncompressedSize:ak.get(e,12)}},len:16},Dk={get(e){let t=rk.get(e,6);return{signature:ak.get(e,0),minVersion:rk.get(e,4),dataDescriptor:!!(t&8),compressedMethod:rk.get(e,8),compressedSize:ak.get(e,18),uncompressedSize:ak.get(e,22),filenameLength:rk.get(e,26),extraFieldLength:rk.get(e,28),filename:null}},len:30},Ok={get(e){return{signature:ak.get(e,0),nrOfThisDisk:rk.get(e,4),nrOfThisDiskWithTheStart:rk.get(e,6),nrOfEntriesOnThisDisk:rk.get(e,8),nrOfEntriesOfSize:rk.get(e,10),sizeOfCd:ak.get(e,12),offsetOfStartOfCd:ak.get(e,16),zipFileCommentLength:rk.get(e,20)}},len:22},kk={get(e){let t=rk.get(e,8);return{signature:ak.get(e,0),minVersion:rk.get(e,6),dataDescriptor:!!(t&8),compressedMethod:rk.get(e,10),compressedSize:ak.get(e,20),uncompressedSize:ak.get(e,24),filenameLength:rk.get(e,28),extraFieldLength:rk.get(e,30),fileCommentLength:rk.get(e,32),relativeOffsetOfLocalHeader:ak.get(e,42),filename:null}},len:46};function Ak(e){let t=new Uint8Array(ak.len);return ak.put(t,0,e),t}const jk=(0,wk.default)(`tokenizer:inflate`),Mk=256*1024,Nk=Ak(Tk.DataDescriptor),Pk=Ak(Tk.EndOfCentralDirectory);var Fk=class e{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Mk)}async isZip(){return await this.peekSignature()===Tk.LocalFileHeader}peekSignature(){return this.tokenizer.peekToken(ak)}async findEndOfCentralDirectoryLocator(){let e=this.tokenizer,t=Math.min(16*1024,e.fileInfo.size),n=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(n,{position:e.fileInfo.size-t});for(let r=n.length-4;r>=0;r--)if(n[r]===Pk[0]&&n[r+1]===Pk[1]&&n[r+2]===Pk[2]&&n[r+3]===Pk[3])return e.fileInfo.size-t+r;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess()){jk(`Cannot reading central-directory without random-read support`);return}jk(`Reading central-directory...`);let e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){jk(`Central-directory 32-bit signature found`);let n=await this.tokenizer.readToken(Ok,t),r=[];this.tokenizer.setPosition(n.offsetOfStartOfCd);for(let e=0;e<n.nrOfEntriesOfSize;++e){let t=await this.tokenizer.readToken(kk);if(t.signature!==Tk.CentralFileHeader)throw Error(`Expected Central-File-Header signature`);t.filename=await this.tokenizer.readToken(new lk(t.filenameLength,`utf-8`)),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),r.push(t),jk(`Add central-directory file-entry: n=${e+1}/${r.length}: filename=${r[e].filename}`)}return this.tokenizer.setPosition(e),r}this.tokenizer.setPosition(e)}async unzip(e){let t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let n=!1;do{let t=await this.readLocalFileHeader();if(!t)break;let r=e(t);n=!!r.stop;let i;if(await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&t.compressedSize===0){let e=[],n=Mk;jk(`Compressed-file-size unknown, scanning for next data-descriptor-signature....`);let i=-1;for(;i<0&&n===Mk;){n=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),i=Ik(this.syncBuffer.subarray(0,n),Nk);let t=i>=0?i:n;if(r.handler){let n=new Uint8Array(t);await this.tokenizer.readBuffer(n),e.push(n)}else await this.tokenizer.ignore(t)}jk(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),r.handler&&await this.inflate(t,Lk(e),r.handler)}else r.handler?(jk(`Reading compressed-file-data: ${t.compressedSize} bytes`),i=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(i),await this.inflate(t,i,r.handler)):(jk(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(jk(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor&&(await this.tokenizer.readToken(Ek)).signature!==134695760)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-Ek.len}`)}while(!n)}async iterateOverCentralDirectory(e,t){for(let n of e){let e=t(n);if(e.handler){this.tokenizer.setPosition(n.relativeOffsetOfLocalHeader);let t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);let r=new Uint8Array(n.compressedSize);await this.tokenizer.readBuffer(r),await this.inflate(t,r,e.handler)}}if(e.stop)break}}async inflate(t,n,r){if(t.compressedMethod===0)return r(n);if(t.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${t.compressedMethod}`);return jk(`Decompress filename=${t.filename}, compressed-size=${n.length}`),r(await e.decompressDeflateRaw(n))}static async decompressDeflateRaw(e){let t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=new DecompressionStream(`deflate-raw`),r=t.pipeThrough(n);try{let e=await new Response(r).arrayBuffer();return new Uint8Array(e)}catch(e){let t=e instanceof Error?`Failed to deflate ZIP entry: ${e.message}`:`Unknown decompression error in ZIP entry`;throw TypeError(t)}}async readLocalFileHeader(){let e=await this.tokenizer.peekToken(ak);if(e===Tk.LocalFileHeader){let e=await this.tokenizer.readToken(Dk);return e.filename=await this.tokenizer.readToken(new lk(e.filenameLength,`utf-8`)),e}if(e===Tk.CentralFileHeader)return!1;throw Error(e===3759263696?`Encrypted ZIP`:`Unexpected signature`)}};function Ik(e,t){let n=e.length,r=t.length;if(r>n)return-1;for(let i=0;i<=n-r;i++){let n=!0;for(let a=0;a<r;a++)if(e[i+a]!==t[a]){n=!1;break}if(n)return i}return-1}function Lk(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var Rk=class{constructor(e){this.tokenizer=e}inflate(){let e=this.tokenizer;return new ReadableStream({async pull(t){let n=new Uint8Array(1024),r=await e.readBuffer(n,{mayBeLess:!0});if(r===0){t.close();return}t.enqueue(n.subarray(0,r))}}).pipeThrough(new DecompressionStream(`gzip`))}};const zk=Object.prototype.toString;function Bk(e,t,n){return e?e.constructor===t?!0:zk.call(e)===n:!1}function Vk(e){return Bk(e,Uint8Array,`[object Uint8Array]`)}function Hk(e){if(!Vk(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function Uk(e,t){if(e.length===0)return new Uint8Array;t??=e.reduce((e,t)=>e+t.length,0);let n=new Uint8Array(t),r=0;for(let t of e)Hk(t),n.set(t,r),r+=t.length;return n}new globalThis.TextDecoder(`utf8`),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function Wk(e){let{byteLength:t}=e;if(t===6)return e.getUint16(0)*2**32+e.getUint32(2);if(t===5)return e.getUint8(0)*2**32+e.getUint32(1);if(t===4)return e.getUint32(0);if(t===3)return e.getUint8(0)*2**16+e.getUint16(1);if(t===2)return e.getUint16(0);if(t===1)return e.getUint8(0)}function Gk(e,t){if(t===`utf-16le`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r&255,r>>8&255)}return t}if(t===`utf-16be`){let t=[];for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);t.push(r>>8&255,r&255)}return t}return[...e].map(e=>e.charCodeAt(0))}function Kk(e,t=0){let n=Number.parseInt(new lk(6).get(e,148).replace(/\0.*$/v,``).trim(),8);if(Number.isNaN(n))return!1;let r=256;for(let n=t;n<t+148;n++)r+=e[n];for(let n=t+156;n<t+512;n++)r+=e[n];return n===r}const qk={get:(e,t)=>e[t+3]&127|(e[t+2]&127)<<7|(e[t+1]&127)<<14|(e[t]&127)<<21,len:4},Jk=`jpg,png,apng,gif,webp,flif,xcf,cr2,cr3,orf,arw,dng,nef,rw2,raf,tif,bmp,icns,jxr,psd,indd,zip,tar,rar,gz,bz2,7z,dmg,mp4,mid,mkv,webm,mov,avi,mpg,mp2,mp3,m4a,oga,ogg,ogv,opus,flac,wav,spx,amr,pdf,epub,elf,macho,exe,swf,rtf,wasm,woff,woff2,eot,ttf,otf,ttc,ico,flv,ps,xz,sqlite,nes,crx,xpi,cab,deb,ar,rpm,Z,lz,cfb,mxf,mts,blend,bpg,docx,pptx,xlsx,3gp,3g2,j2c,jp2,jpm,jpx,mj2,aif,qcp,odt,ods,odp,xml,mobi,heic,cur,ktx,ape,wv,dcm,ics,glb,pcap,dsf,lnk,alias,voc,ac3,m4v,m4p,m4b,f4v,f4p,f4b,f4a,mie,asf,ogm,ogx,mpc,arrow,shp,aac,mp1,it,s3m,xm,skp,avif,eps,lzh,pgp,asar,stl,chm,3mf,zst,jxl,vcf,jls,pst,dwg,parquet,class,arj,cpio,ace,avro,icc,fbx,vsdx,vtt,apk,drc,lz4,potx,xltx,dotx,xltm,ott,ots,otp,odg,otg,xlsm,docm,dotm,potm,pptm,jar,jmp,rm,sav,ppsm,ppsx,tar.gz,reg,dat,key,numbers,pages`.split(`,`),Yk=`image/jpeg,image/png,image/gif,image/webp,image/flif,image/x-xcf,image/x-canon-cr2,image/x-canon-cr3,image/tiff,image/bmp,image/vnd.ms-photo,image/vnd.adobe.photoshop,application/x-indesign,application/epub+zip,application/x-xpinstall,application/vnd.ms-powerpoint.slideshow.macroenabled.12,application/vnd.oasis.opendocument.text,application/vnd.oasis.opendocument.spreadsheet,application/vnd.oasis.opendocument.presentation,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/zip,application/x-tar,application/x-rar-compressed,application/gzip,application/x-bzip2,application/x-7z-compressed,application/x-apple-diskimage,application/vnd.apache.arrow.file,video/mp4,audio/midi,video/matroska,video/webm,video/quicktime,video/vnd.avi,audio/wav,audio/qcelp,audio/x-ms-asf,video/x-ms-asf,application/vnd.ms-asf,video/mpeg,video/3gpp,audio/mpeg,audio/mp4,video/ogg,audio/ogg,audio/ogg; codecs=opus,application/ogg,audio/flac,audio/ape,audio/wavpack,audio/amr,application/pdf,application/x-elf,application/x-mach-binary,application/x-msdownload,application/x-shockwave-flash,application/rtf,application/wasm,font/woff,font/woff2,application/vnd.ms-fontobject,font/ttf,font/otf,font/collection,image/x-icon,video/x-flv,application/postscript,application/eps,application/x-xz,application/x-sqlite3,application/x-nintendo-nes-rom,application/x-google-chrome-extension,application/vnd.ms-cab-compressed,application/x-deb,application/x-unix-archive,application/x-rpm,application/x-compress,application/lzip,application/x-cfb,application/x-mie,application/mxf,video/mp2t,application/x-blender,image/bpg,image/j2c,image/jp2,image/jpx,image/jpm,image/mj2,audio/aiff,application/xml,application/x-mobipocket-ebook,image/heif,image/heif-sequence,image/heic,image/heic-sequence,image/icns,image/ktx,application/dicom,audio/x-musepack,text/calendar,text/vcard,text/vtt,model/gltf-binary,application/vnd.tcpdump.pcap,audio/x-dsf,application/x-ms-shortcut,application/x-ft-apple.alias,audio/x-voc,audio/vnd.dolby.dd-raw,audio/x-m4a,image/apng,image/x-olympus-orf,image/x-sony-arw,image/x-adobe-dng,image/x-nikon-nef,image/x-panasonic-rw2,image/x-fujifilm-raf,video/x-m4v,video/3gpp2,application/x-esri-shape,audio/aac,audio/x-it,audio/x-s3m,audio/x-xm,video/MP1S,video/MP2P,application/vnd.sketchup.skp,image/avif,application/x-lzh-compressed,application/pgp-encrypted,application/x-asar,model/stl,application/vnd.ms-htmlhelp,model/3mf,image/jxl,application/zstd,image/jls,application/vnd.ms-outlook,image/vnd.dwg,application/vnd.apache.parquet,application/java-vm,application/x-arj,application/x-cpio,application/x-ace-compressed,application/avro,application/vnd.iccprofile,application/x-ft-fbx,application/vnd.visio,application/vnd.android.package-archive,application/x-ft-draco,application/x-lz4,application/vnd.openxmlformats-officedocument.presentationml.template,application/vnd.openxmlformats-officedocument.spreadsheetml.template,application/vnd.openxmlformats-officedocument.wordprocessingml.template,application/vnd.ms-excel.template.macroenabled.12,application/vnd.oasis.opendocument.text-template,application/vnd.oasis.opendocument.spreadsheet-template,application/vnd.oasis.opendocument.presentation-template,application/vnd.oasis.opendocument.graphics,application/vnd.oasis.opendocument.graphics-template,application/vnd.ms-excel.sheet.macroenabled.12,application/vnd.ms-word.document.macroenabled.12,application/vnd.ms-word.template.macroenabled.12,application/vnd.ms-powerpoint.template.macroenabled.12,application/vnd.ms-powerpoint.presentation.macroenabled.12,application/java-archive,application/vnd.rn-realmedia,application/x-spss-sav,application/x-ms-regedit,application/x-ft-windows-registry-hive,application/x-jmp-data,application/vnd.apple.keynote,application/vnd.apple.numbers,application/vnd.apple.pages`.split(`,`),Xk=16*1024*1024;var Zk=class extends Error{};function Qk(e,t,n){if(!Number.isFinite(e)||e<0||e>t)throw new Zk(`${n} has invalid size ${e} (maximum ${t} bytes)`);return e}async function $k(e,t,{maximumLength:n=Xk,reason:r=`skip`}={}){let i=Qk(t,n,r);await e.ignore(i)}async function eA(e,t,n,{maximumLength:r=t.length,reason:i=`read`}={}){let a=Qk(n?.length??t.length,r,i);return e.readBuffer(t,{...n,length:a})}function tA(e,t,n){n={offset:0,...n};for(let[r,i]of t.entries())if(n.mask){if(i!==(n.mask[r]&e[r+n.offset]))return!1}else if(i!==e[r+n.offset])return!1;return!0}function nA(e){let t=e.fileInfo.size;return!Number.isFinite(t)||t===2**53-1}function rA(e,t,n){return nA(e)&&e.position-t>n}const iA=1024*1024,aA=1024,oA=2**31-1,sA=iA,cA=new Set([`Unexpected signature`,`Encrypted ZIP`,`Expected Central-File-Header signature`]),lA=[`ZIP entry count exceeds `,`Unsupported ZIP compression method:`,`ZIP entry compressed data exceeds `,`ZIP entry decompressed data exceeds `,`Expected data-descriptor-signature at position `],uA=new Set([`Z_BUF_ERROR`,`Z_DATA_ERROR`,`ERR_INVALID_STATE`]);async function dA(e,{maximumLength:t=iA}={}){let n=new ReadableStream({start(t){t.enqueue(e),t.close()}}).pipeThrough(new DecompressionStream(`deflate-raw`)).getReader(),r=[],i=0;try{for(;;){let{done:e,value:a}=await n.read();if(e)break;if(i+=a.length,i>t)throw await n.cancel(),Error(`ZIP entry decompressed data exceeds ${t} bytes`);r.push(a)}}finally{n.releaseLock()}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.length;return a}function fA(e,t){let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function pA(e){let t=e.fileInfo.size,n=Number.isFinite(t)?Math.max(0,t-e.position):2**53-1;return Math.min(n,oA)}function mA(e){if(e instanceof uk||e instanceof Zk)return!0;if(!(e instanceof Error))return!1;if(cA.has(e.message)||uA.has(e.code))return!0;for(let t of lA)if(e.message.startsWith(t))return!0;return!1}function hA(e,t=iA){let n=[e.compressedSize,e.uncompressedSize];for(let e of n)if(!Number.isFinite(e)||e<0||e>t)return!1;return!0}function gA(){return{hasDocumentEntry:!1,hasMasterSlideEntry:!1,hasTablesEntry:!1,hasCalculationEngineEntry:!1}}function _A(e,t){t===`Index/Document.iwa`&&(e.hasDocumentEntry=!0),t.startsWith(`Index/MasterSlide`)&&(e.hasMasterSlideEntry=!0),t.startsWith(`Index/Tables/`)&&(e.hasTablesEntry=!0),t===`Index/CalculationEngine.iwa`&&(e.hasCalculationEngineEntry=!0)}function vA(e){if(e.hasDocumentEntry)return e.hasMasterSlideEntry?{ext:`key`,mime:`application/vnd.apple.keynote`}:e.hasTablesEntry?{ext:`numbers`,mime:`application/vnd.apple.numbers`}:{ext:`pages`,mime:`application/vnd.apple.pages`}}function yA(e){switch(e=e.toLowerCase(),e){case`application/epub+zip`:return{ext:`epub`,mime:e};case`application/vnd.oasis.opendocument.text`:return{ext:`odt`,mime:e};case`application/vnd.oasis.opendocument.text-template`:return{ext:`ott`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet`:return{ext:`ods`,mime:e};case`application/vnd.oasis.opendocument.spreadsheet-template`:return{ext:`ots`,mime:e};case`application/vnd.oasis.opendocument.presentation`:return{ext:`odp`,mime:e};case`application/vnd.oasis.opendocument.presentation-template`:return{ext:`otp`,mime:e};case`application/vnd.oasis.opendocument.graphics`:return{ext:`odg`,mime:e};case`application/vnd.oasis.opendocument.graphics-template`:return{ext:`otg`,mime:e};case`application/vnd.openxmlformats-officedocument.presentationml.slideshow`:return{ext:`ppsx`,mime:e};case`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`:return{ext:`xlsx`,mime:e};case`application/vnd.ms-excel.sheet.macroenabled`:return{ext:`xlsm`,mime:`application/vnd.ms-excel.sheet.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.spreadsheetml.template`:return{ext:`xltx`,mime:e};case`application/vnd.ms-excel.template.macroenabled`:return{ext:`xltm`,mime:`application/vnd.ms-excel.template.macroenabled.12`};case`application/vnd.ms-powerpoint.slideshow.macroenabled`:return{ext:`ppsm`,mime:`application/vnd.ms-powerpoint.slideshow.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.document`:return{ext:`docx`,mime:e};case`application/vnd.ms-word.document.macroenabled`:return{ext:`docm`,mime:`application/vnd.ms-word.document.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.wordprocessingml.template`:return{ext:`dotx`,mime:e};case`application/vnd.ms-word.template.macroenabledtemplate`:return{ext:`dotm`,mime:`application/vnd.ms-word.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.template`:return{ext:`potx`,mime:e};case`application/vnd.ms-powerpoint.template.macroenabled`:return{ext:`potm`,mime:`application/vnd.ms-powerpoint.template.macroenabled.12`};case`application/vnd.openxmlformats-officedocument.presentationml.presentation`:return{ext:`pptx`,mime:e};case`application/vnd.ms-powerpoint.presentation.macroenabled`:return{ext:`pptm`,mime:`application/vnd.ms-powerpoint.presentation.macroenabled.12`};case`application/vnd.ms-visio.drawing`:return{ext:`vsdx`,mime:`application/vnd.visio`};case`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`:return{ext:`3mf`,mime:`model/3mf`};default:}}function bA(){return{hasContentTypesEntry:!1,hasParsedContentTypesEntry:!1,isParsingContentTypes:!1,hasUnparseableContentTypes:!1,hasWordDirectory:!1,hasPresentationDirectory:!1,hasSpreadsheetDirectory:!1,hasThreeDimensionalModelEntry:!1}}function xA(e,t){t.startsWith(`word/`)&&(e.hasWordDirectory=!0),t.startsWith(`ppt/`)&&(e.hasPresentationDirectory=!0),t.startsWith(`xl/`)&&(e.hasSpreadsheetDirectory=!0),t.startsWith(`3D/`)&&t.endsWith(`.model`)&&(e.hasThreeDimensionalModelEntry=!0)}function SA(e){if(e.hasWordDirectory)return{ext:`docx`,mime:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`};if(e.hasPresentationDirectory)return{ext:`pptx`,mime:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};if(e.hasSpreadsheetDirectory)return{ext:`xlsx`,mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`};if(e.hasThreeDimensionalModelEntry)return{ext:`3mf`,mime:`model/3mf`}}function CA(e){if(!(!e.hasContentTypesEntry||e.hasUnparseableContentTypes||e.isParsingContentTypes||e.hasParsedContentTypesEntry))return SA(e)}function wA(e){let t=e.indexOf(`.main+xml"`);if(t===-1){let t=`application/vnd.ms-package.3dmanufacturing-3dmodel+xml`;return e.includes(`ContentType="${t}"`)?t:void 0}let n=e.slice(0,t),r=n.lastIndexOf(`"`);return n.slice(r+1)}const TA=134695760;function EA(e,t){if(e.length<16)return-1;let n=e.length-16;for(let r=0;r<=n;r++)if(ak.get(e,r)===TA&&ak.get(e,r+8)===t+r)return r;return-1}async function DA(e,{shouldBuffer:t,maximumLength:n=iA}={}){let{syncBuffer:r}=e,{length:i}=r,a=[],o=0;for(;;){let s=await e.tokenizer.peekBuffer(r,{mayBeLess:!0}),c=EA(r.subarray(0,s),o),l=c>=0?0:s===i?Math.min(15,s-1):0,u=c>=0?c:s-l;if(u===0)break;if(o+=u,o>n)throw Error(`ZIP entry compressed data exceeds ${n} bytes`);if(t){let t=new Uint8Array(u);await e.tokenizer.readBuffer(t),a.push(t)}else await e.tokenizer.ignore(u);if(c>=0)break}if(nA(e.tokenizer)||(e.knownSizeDescriptorScannedBytes+=o),t)return fA(a,o)}function OA(e,t){return nA(e.tokenizer)?Math.max(0,Xk-(e.tokenizer.position-t)):Math.max(0,iA-e.knownSizeDescriptorScannedBytes)}async function kA(e,t,{shouldBuffer:n,maximumDescriptorLength:r=iA}={}){if(t.dataDescriptor&&t.compressedSize===0)return DA(e,{shouldBuffer:n,maximumLength:r});if(!n){await $k(e.tokenizer,t.compressedSize,{maximumLength:nA(e.tokenizer)?iA:e.tokenizer.fileInfo.size,reason:`ZIP entry compressed data`});return}let i=pA(e.tokenizer);if(!Number.isFinite(t.compressedSize)||t.compressedSize<0||t.compressedSize>i)throw Error(`ZIP entry compressed data exceeds ${i} bytes`);let a=new Uint8Array(t.compressedSize);return await e.tokenizer.readBuffer(a),a}Fk.prototype.inflate=async function(e,t,n){if(e.compressedMethod===0)return n(t);if(e.compressedMethod!==8)throw Error(`Unsupported ZIP compression method: ${e.compressedMethod}`);return n(await dA(t,{maximumLength:iA}))},Fk.prototype.unzip=async function(e){let t=!1,n=0,r=this.tokenizer.position;this.knownSizeDescriptorScannedBytes=0;do{if(rA(this.tokenizer,r,16777216))throw new Zk(`ZIP stream probing exceeds ${Xk} bytes`);let i=await this.readLocalFileHeader();if(!i)break;if(n++,n>aA)throw Error(`ZIP entry count exceeds ${aA}`);let a=e(i);t=!!a.stop,await this.tokenizer.ignore(i.extraFieldLength);let o=await kA(this,i,{shouldBuffer:!!a.handler,maximumDescriptorLength:Math.min(iA,OA(this,r))});if(a.handler&&await this.inflate(i,o,a.handler),i.dataDescriptor){let e=new Uint8Array(16);if(await this.tokenizer.readBuffer(e),ak.get(e,0)!==TA)throw Error(`Expected data-descriptor-signature at position ${this.tokenizer.position-e.length}`)}if(rA(this.tokenizer,r,16777216))throw new Zk(`ZIP stream probing exceeds ${Xk} bytes`)}while(!t)};async function AA(e){let t,n=bA(),r=gA();try{await new Fk(e).unzip(e=>{if(xA(n,e.filename),_A(r,e.filename),r.hasDocumentEntry&&(r.hasMasterSlideEntry||r.hasTablesEntry))return t=vA(r),{stop:!0};let i=e.filename===`[Content_Types].xml`,a=CA(n);if(!i&&a)return t=a,{stop:!0};switch(e.filename){case`META-INF/mozilla.rsa`:return t={ext:`xpi`,mime:`application/x-xpinstall`},{stop:!0};case`META-INF/MANIFEST.MF`:return t={ext:`jar`,mime:`application/java-archive`},{stop:!0};case`mimetype`:return hA(e,sA)?{async handler(e){t=yA(new TextDecoder(`utf-8`).decode(e).trim())},stop:!0}:{};case`[Content_Types].xml`:return n.hasContentTypesEntry=!0,hA(e,sA)?(n.isParsingContentTypes=!0,{async handler(e){let r=wA(new TextDecoder(`utf-8`).decode(e));r&&(t=yA(r)),n.hasParsedContentTypesEntry=!0,n.isParsingContentTypes=!1},stop:!0}):(n.hasUnparseableContentTypes=!0,{});default:return/classes\d*\.dex/v.test(e.filename)?(t={ext:`apk`,mime:`application/vnd.android.package-archive`},{stop:!0}):{}}})}catch(e){if(!mA(e))throw e;n.isParsingContentTypes&&(n.isParsingContentTypes=!1,n.hasUnparseableContentTypes=!0),!t&&e instanceof uk&&!n.hasContentTypesEntry&&(t=SA(n))}let i=nA(e)&&r.hasDocumentEntry&&!r.hasMasterSlideEntry&&!r.hasTablesEntry&&!r.hasCalculationEngineEntry?void 0:vA(r);return t??CA(n)??i??{ext:`zip`,mime:`application/zip`}}const jA=1024*1024;async function MA(e){async function t(){let t=await e.peekNumber(nk),n=128,r=0;for(;(t&n)===0&&n!==0;)++r,n>>=1;let i=new Uint8Array(r+1);return await eA(e,i,void 0,{maximumLength:i.length,reason:`EBML field`}),i}async function n(){let e=await t(),n=await t();n[0]^=128>>n.length-1;let r=Math.min(6,n.length),i=new DataView(e.buffer),a=new DataView(n.buffer,n.length-r,r);return{id:Wk(i),len:Wk(a)}}async function r(t){let r=0;for(;t>0;){if(r++,r>256||rA(e,a,16777216))return;let i=e.position,o=await n();if(o.id===17026){if(o.len>64)return;let t=Qk(o.len,64,`EBML DocType`);return(await e.readToken(new lk(t))).replaceAll(/\0.*$/gv,``)}if(nA(e)&&(!Number.isFinite(o.len)||o.len<0||o.len>jA)||(await $k(e,o.len,{maximumLength:nA(e)?jA:e.fileInfo.size,reason:`EBML payload`}),--t,e.position<=i))return}}let i=await n(),a=e.position;switch(await r(i.len)){case`webm`:return{ext:`webm`,mime:`video/webm`};case`matroska`:return{ext:`mkv`,mime:`video/matroska`};default:}}const NA=1024*1024;function PA(e){return(e.codePointAt(0)&32)!=0}async function FA(e){let t={ext:`png`,mime:`image/png`},n={ext:`apng`,mime:`image/apng`};await e.ignore(8);async function r(){return{length:await e.readToken(sk),type:await e.readToken(new lk(4,`latin1`))}}let i=nA(e),a=e.position,o=0,s=!1;do{if(o++,o>512||rA(e,a,16777216))break;let c=e.position,l=await r();if(l.length<0)return;if(l.type===`IHDR`){if(l.length!==13)return;s=!0}switch(l.type){case`IDAT`:return t;case`acTL`:return n;default:if(!s&&l.type!==`CgBI`)return;if(i&&l.length>NA)return s&&PA(l.type)?t:void 0;try{await $k(e,l.length+4,{maximumLength:i?NA+4:e.fileInfo.size,reason:`PNG chunk payload`})}catch(e){if(!i&&(e instanceof Zk||e instanceof uk))return t;throw e}}if(e.position<=c)break}while(e.position+8<e.fileInfo.size);return t}const IA=1024*1024;async function LA(e){let t=!1;try{async function n(){let t=new Uint8Array(16);return await eA(e,t,void 0,{maximumLength:t.length,reason:`ASF header GUID`}),{id:t,size:Number(await e.readToken(ck))}}await $k(e,30,{maximumLength:30,reason:`ASF header prelude`});let r=nA(e),i=e.position,a=0;for(;e.position+24<e.fileInfo.size&&(a++,!(a>512||rA(e,i,16777216)));){let i=e.position,a=await n(),o=a.size-24;if(!Number.isFinite(o)||o<0){t=!0;break}if(tA(a.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){let t=new Uint8Array(16);if(o-=await eA(e,t,void 0,{maximumLength:t.length,reason:`ASF stream type GUID`}),tA(t,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`audio/x-ms-asf`};if(tA(t,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:`asf`,mime:`video/x-ms-asf`};break}if(r&&o>IA){t=!0;break}if(await $k(e,o,{maximumLength:r?IA:e.fileInfo.size,reason:`ASF header payload`}),e.position<=i){t=!0;break}}}catch(n){if(n instanceof uk||n instanceof Zk)nA(e)&&(t=!0);else throw n}if(!t)return{ext:`asf`,mime:`application/vnd.ms-asf`}}const RA=4100;RA-2;const zA=Xk,BA=Xk;function VA(e){return Number.isFinite(e)?Math.max(1,Math.trunc(e)):RA}function HA(e){return Number.isFinite(e)?Math.max(0,Math.min(4098,Math.trunc(e))):0}function UA(e){return Number.isFinite(e)?Math.max(0,e):2**53-1}function WA(e){return import(e)}function GA(e){return e.pipeThrough(new TransformStream)}function KA(e,t){return t===void 0?e.read():(t.throwIfAborted(),Promise.race([e.read(),new Promise((n,r)=>{t.addEventListener(`abort`,()=>{r(t.reason),e.cancel(t.reason).catch(()=>{})},{once:!0})})]))}function qA(e,t){let n=e.getReader(),r=0,i=!1,a=!1,o=async e=>{i||a||(a=!0,await n.cancel(e))};return new ReadableStream({async pull(e){if(r>=t){e.close(),await o();return}let{done:a,value:s}=await n.read();if(a||!s){i=!0,e.close();return}let c=t-r;if(s.length>c){e.enqueue(s.subarray(0,c)),r+=c,e.close(),await o();return}e.enqueue(s),r+=s.length},async cancel(e){await o(e)}})}async function JA(e,t){return new YA(t).fromBuffer(e)}var YA=class e{constructor(e){let t=HA(e?.mpegOffsetTolerance);this.options={...e,mpegOffsetTolerance:t},this.detectors=[...this.options.customDetectors??[],{id:`core`,detect:this.detectConfident},{id:`core.imprecise`,detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:this.options.signal},this.gzipProbeDepth=0}getTokenizerOptions(){return{...this.tokenizerOptions}}createTokenizerFromWebStream(e){return xk(GA(e),this.getTokenizerOptions())}async parseTokenizer(e,t=0){this.detectionReentryCount=t;let n=e.position;for(let t of this.detectors){let r;try{r=await t.detect(e)}catch(e){if(e instanceof uk||e instanceof Zk)return;throw e}if(r)return r;if(n!==e.position)return}}async fromTokenizer(e){try{return await this.parseTokenizer(e)}finally{await e.close()}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);let t=e instanceof Uint8Array?e:new Uint8Array(e);if(t?.length>1)return this.fromTokenizer(Sk(t,this.getTokenizerOptions()))}async fromBlob(e){this.options.signal?.throwIfAborted();let t=Ck(e,this.getTokenizerOptions());return this.fromTokenizer(t)}async fromStream(e){this.options.signal?.throwIfAborted();let t=this.createTokenizerFromWebStream(e);return this.fromTokenizer(t)}async fromFile(e){this.options.signal?.throwIfAborted();let[{default:t},{FileTokenizer:n}]=await Promise.all([WA(`node:fs/promises`),WA(`strtok3`)]),r=await t.open(e,t.constants.O_RDONLY|t.constants.O_NONBLOCK),i=await r.stat();if(!i.isFile()){await r.close();return}let a=new n(r,{...this.getTokenizerOptions(),fileInfo:{path:e,size:i.size}});return this.fromTokenizer(a)}async toDetectionStream(e,t){this.options.signal?.throwIfAborted();let n=VA(t?.sampleSize??4100),r,i=!1,a=e.getReader(),o=[],s=0;try{for(;s<n;){let{value:e,done:t}=await KA(a,this.options.signal);if(t||!e){i=!0;break}o.push(e),s+=e.length}if(!i&&s===n){let{value:e,done:t}=await KA(a,this.options.signal);t||!e?i=!0:(o.push(e),s+=e.length)}}finally{a.releaseLock()}if(s>0){let e=o.length===1?o[0]:Uk(o);try{r=await this.fromBuffer(e.subarray(0,n))}catch(e){if(!(e instanceof uk))throw e;r=void 0}!i&&r?.ext===`pages`&&(r={ext:`zip`,mime:`application/zip`})}let c=new TransformStream({start(e){for(let t of o)e.enqueue(t)},transform(e,t){t.enqueue(e)}}),l=e.pipeThrough(c);return l.fileType=r,l}async detectGzip(t){if(this.gzipProbeDepth>=1)return{ext:`gz`,mime:`application/gzip`};let n=qA(new Rk(t).inflate(),16777216),r=nA(t),i,a,o,s;if(r){let t=new AbortController;i=setTimeout(()=>{t.abort(new DOMException(`Operation timed out after 100 ms`,`TimeoutError`))},100),a=this.options.signal===void 0?t.signal:AbortSignal.any([this.options.signal,t.signal]),o=new e({...this.options,signal:a}),o.gzipProbeDepth=this.gzipProbeDepth+1}else this.gzipProbeDepth++;try{s=await(o??this).fromStream(n)}catch(e){if(e?.name===`AbortError`&&a?.reason?.name!==`TimeoutError`)throw e}finally{clearTimeout(i),r||this.gzipProbeDepth--}return s?.ext===`tar`?{ext:`tar.gz`,mime:`application/gzip`}:{ext:`gz`,mime:`application/gzip`}}check(e,t){return tA(this.buffer,e,t)}checkString(e,t){return this.check(Gk(e,t?.encoding),t)}detectConfident=async e=>{if(this.buffer=new Uint8Array(RA),e.fileInfo.size===void 0&&(e.fileInfo.size=2**53-1),this.tokenizer=e,nA(e)&&(await e.peekBuffer(this.buffer,{length:3,mayBeLess:!0}),this.check([31,139,8])))return this.detectGzip(e);if(await e.peekBuffer(this.buffer,{length:32,mayBeLess:!0}),this.check([66,77]))return{ext:`bmp`,mime:`image/bmp`};if(this.check([11,119]))return{ext:`ac3`,mime:`audio/vnd.dolby.dd-raw`};if(this.check([120,1]))return{ext:`dmg`,mime:`application/x-apple-diskimage`};if(this.check([77,90]))return{ext:`exe`,mime:`application/x-msdownload`};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString(`PS-Adobe-`,{offset:2})&&this.checkString(` EPSF-`,{offset:14})?{ext:`eps`,mime:`application/eps`}:{ext:`ps`,mime:`application/postscript`};if(this.check([31,160])||this.check([31,157]))return{ext:`Z`,mime:`application/x-compress`};if(this.check([199,113]))return{ext:`cpio`,mime:`application/x-cpio`};if(this.check([96,234]))return{ext:`arj`,mime:`application/x-arj`};if(this.check([239,187,191]))return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,await this.tokenizer.ignore(3),this.detectConfident(e));if(this.check([71,73,70]))return{ext:`gif`,mime:`image/gif`};if(this.check([73,73,188]))return{ext:`jxr`,mime:`image/vnd.ms-photo`};if(this.check([31,139,8]))return this.detectGzip(e);if(this.check([66,90,104]))return{ext:`bz2`,mime:`application/x-bzip2`};if(this.checkString(`ID3`)){await $k(e,6,{maximumLength:6,reason:`ID3 header prefix`});let t=await e.readToken(qk),n=nA(e);if(!Number.isFinite(t)||t<0||n&&(t>zA||e.position+t>zA))return;if(e.position+t>e.fileInfo.size)return n?void 0:{ext:`mp3`,mime:`audio/mpeg`};try{await $k(e,t,{maximumLength:n?zA:e.fileInfo.size,reason:`ID3 payload`})}catch(e){if(e instanceof uk)return;throw e}return this.detectionReentryCount>=256?void 0:(this.detectionReentryCount++,this.parseTokenizer(e,this.detectionReentryCount))}if(this.checkString(`MP+`))return{ext:`mpc`,mime:`audio/x-musepack`};if((this.buffer[0]===67||this.buffer[0]===70)&&this.check([87,83],{offset:1}))return{ext:`swf`,mime:`application/x-shockwave-flash`};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:`jls`,mime:`image/jls`}:{ext:`jpg`,mime:`image/jpeg`};if(this.check([79,98,106,1]))return{ext:`avro`,mime:`application/avro`};if(this.checkString(`FLIF`))return{ext:`flif`,mime:`image/flif`};if(this.checkString(`8BPS`))return{ext:`psd`,mime:`image/vnd.adobe.photoshop`};if(this.checkString(`MPCK`))return{ext:`mpc`,mime:`audio/x-musepack`};if(this.checkString(`FORM`))return{ext:`aif`,mime:`audio/aiff`};if(this.checkString(`icns`,{offset:0}))return{ext:`icns`,mime:`image/icns`};if(this.check([80,75,3,4]))return AA(e);if(this.checkString(`OggS`)){await e.ignore(28);let t=new Uint8Array(8);return await e.readBuffer(t),tA(t,[79,112,117,115,72,101,97,100])?{ext:`opus`,mime:`audio/ogg; codecs=opus`}:tA(t,[128,116,104,101,111,114,97])?{ext:`ogv`,mime:`video/ogg`}:tA(t,[1,118,105,100,101,111,0])?{ext:`ogm`,mime:`video/ogg`}:tA(t,[127,70,76,65,67])?{ext:`oga`,mime:`audio/ogg`}:tA(t,[83,112,101,101,120,32,32])?{ext:`spx`,mime:`audio/ogg`}:tA(t,[1,118,111,114,98,105,115])?{ext:`ogg`,mime:`audio/ogg`}:{ext:`ogx`,mime:`application/ogg`}}if(this.check([80,75])&&(this.buffer[2]===3||this.buffer[2]===5||this.buffer[2]===7)&&(this.buffer[3]===4||this.buffer[3]===6||this.buffer[3]===8))return{ext:`zip`,mime:`application/zip`};if(this.checkString(`MThd`))return{ext:`mid`,mime:`audio/midi`};if(this.checkString(`wOFF`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff`,mime:`font/woff`};if(this.checkString(`wOF2`)&&(this.check([0,1,0,0],{offset:4})||this.checkString(`OTTO`,{offset:4})))return{ext:`woff2`,mime:`font/woff2`};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:`pcap`,mime:`application/vnd.tcpdump.pcap`};if(this.checkString(`DSD `))return{ext:`dsf`,mime:`audio/x-dsf`};if(this.checkString(`LZIP`))return{ext:`lz`,mime:`application/lzip`};if(this.checkString(`fLaC`))return{ext:`flac`,mime:`audio/flac`};if(this.check([66,80,71,251]))return{ext:`bpg`,mime:`image/bpg`};if(this.checkString(`wvpk`))return{ext:`wv`,mime:`audio/wavpack`};if(this.checkString(`%PDF`))return{ext:`pdf`,mime:`application/pdf`};if(this.check([0,97,115,109]))return{ext:`wasm`,mime:`application/wasm`};if(this.check([73,73])){let e=await this.readTiffHeader(!1);if(e)return e}if(this.check([77,77])){let e=await this.readTiffHeader(!0);if(e)return e}if(this.checkString(`MAC `))return{ext:`ape`,mime:`audio/ape`};if(this.check([26,69,223,163]))return MA(e);if(this.checkString(`SQLi`))return{ext:`sqlite`,mime:`application/x-sqlite3`};if(this.check([78,69,83,26]))return{ext:`nes`,mime:`application/x-nintendo-nes-rom`};if(this.checkString(`Cr24`))return{ext:`crx`,mime:`application/x-google-chrome-extension`};if(this.checkString(`MSCF`)||this.checkString(`ISc(`))return{ext:`cab`,mime:`application/vnd.ms-cab-compressed`};if(this.check([237,171,238,219]))return{ext:`rpm`,mime:`application/x-rpm`};if(this.check([197,208,211,198]))return{ext:`eps`,mime:`application/eps`};if(this.check([40,181,47,253]))return{ext:`zst`,mime:`application/zstd`};if(this.check([127,69,76,70]))return{ext:`elf`,mime:`application/x-elf`};if(this.check([33,66,68,78]))return{ext:`pst`,mime:`application/vnd.ms-outlook`};if(this.checkString(`PAR1`)||this.checkString(`PARE`))return{ext:`parquet`,mime:`application/vnd.apache.parquet`};if(this.checkString(`ttcf`))return{ext:`ttc`,mime:`font/collection`};if(this.check([254,237,250,206])||this.check([254,237,250,207])||this.check([206,250,237,254])||this.check([207,250,237,254]))return{ext:`macho`,mime:`application/x-mach-binary`};if(this.check([4,34,77,24]))return{ext:`lz4`,mime:`application/x-lz4`};if(this.checkString(`regf`))return{ext:`dat`,mime:`application/x-ft-windows-registry-hive`};if(this.checkString(`$FL2`)||this.checkString(`$FL3`))return{ext:`sav`,mime:`application/x-spss-sav`};if(this.check([79,84,84,79,0]))return{ext:`otf`,mime:`font/otf`};if(this.checkString(`#!AMR`))return{ext:`amr`,mime:`audio/amr`};if(this.checkString(String.raw`{\rtf`))return{ext:`rtf`,mime:`application/rtf`};if(this.check([70,76,86,1]))return{ext:`flv`,mime:`video/x-flv`};if(this.checkString(`IMPM`))return{ext:`it`,mime:`audio/x-it`};if(this.checkString(`-lh0-`,{offset:2})||this.checkString(`-lh1-`,{offset:2})||this.checkString(`-lh2-`,{offset:2})||this.checkString(`-lh3-`,{offset:2})||this.checkString(`-lh4-`,{offset:2})||this.checkString(`-lh5-`,{offset:2})||this.checkString(`-lh6-`,{offset:2})||this.checkString(`-lh7-`,{offset:2})||this.checkString(`-lzs-`,{offset:2})||this.checkString(`-lz4-`,{offset:2})||this.checkString(`-lz5-`,{offset:2})||this.checkString(`-lhd-`,{offset:2}))return{ext:`lzh`,mime:`application/x-lzh-compressed`};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:`mpg`,mime:`video/MP1S`};if(this.check([68],{offset:4,mask:[196]}))return{ext:`mpg`,mime:`video/MP2P`}}if(this.checkString(`ITSF`))return{ext:`chm`,mime:`application/vnd.ms-htmlhelp`};if(this.check([202,254,186,190])){let e=ok.get(this.buffer,4),t=ik.get(this.buffer,6);if(e>0&&e<=30)return{ext:`macho`,mime:`application/x-mach-binary`};if(t>30)return{ext:`class`,mime:`application/java-vm`}}if(this.checkString(`.RMF`))return{ext:`rm`,mime:`application/vnd.rn-realmedia`};if(this.checkString(`DRACO`))return{ext:`drc`,mime:`application/x-ft-draco`};if(this.check([253,55,122,88,90,0]))return{ext:`xz`,mime:`application/x-xz`};if(this.checkString(`<?xml `))return{ext:`xml`,mime:`application/xml`};if(this.check([55,122,188,175,39,28]))return{ext:`7z`,mime:`application/x-7z-compressed`};if(this.check([82,97,114,33,26,7])&&(this.buffer[6]===0||this.buffer[6]===1))return{ext:`rar`,mime:`application/x-rar-compressed`};if(this.checkString(`solid `))return{ext:`stl`,mime:`model/stl`};if(this.checkString(`AC`)){let e=new lk(4,`latin1`).get(this.buffer,2);if(/^\d+$/v.test(e)&&e>=1e3&&e<=1050)return{ext:`dwg`,mime:`image/vnd.dwg`}}if(this.checkString(`070707`))return{ext:`cpio`,mime:`application/x-cpio`};if(this.checkString(`BLENDER`))return{ext:`blend`,mime:`application/x-blender`};if(this.checkString(`!<arch>`))return await e.ignore(8),await e.readToken(new lk(13,`ascii`))===`debian-binary`?{ext:`deb`,mime:`application/x-deb`}:{ext:`ar`,mime:`application/x-unix-archive`};if(this.checkString(`WEBVTT`)&&[`
30
30
  `,`\r`,` `,` `,`\0`].some(e=>this.checkString(e,{offset:6})))return{ext:`vtt`,mime:`text/vtt`};if(this.check([137,80,78,71,13,10,26,10]))return FA(e);if(this.check([65,82,82,79,87,49,0,0]))return{ext:`arrow`,mime:`application/vnd.apache.arrow.file`};if(this.check([103,108,84,70,2,0,0,0]))return{ext:`glb`,mime:`model/gltf-binary`};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:`mov`,mime:`video/quicktime`};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:`orf`,mime:`image/x-olympus-orf`};if(this.checkString(`gimp xcf `))return{ext:`xcf`,mime:`image/x-xcf`};if(this.checkString(`ftyp`,{offset:4})&&this.buffer[8]&96){let e=new lk(4,`latin1`).get(this.buffer,8).replace(`\0`,` `).trim();switch(e){case`avif`:case`avis`:return{ext:`avif`,mime:`image/avif`};case`mif1`:return{ext:`heic`,mime:`image/heif`};case`msf1`:return{ext:`heic`,mime:`image/heif-sequence`};case`heic`:case`heix`:return{ext:`heic`,mime:`image/heic`};case`hevc`:case`hevx`:return{ext:`heic`,mime:`image/heic-sequence`};case`qt`:return{ext:`mov`,mime:`video/quicktime`};case`M4V`:case`M4VH`:case`M4VP`:return{ext:`m4v`,mime:`video/x-m4v`};case`M4P`:return{ext:`m4p`,mime:`video/mp4`};case`M4B`:return{ext:`m4b`,mime:`audio/mp4`};case`M4A`:return{ext:`m4a`,mime:`audio/x-m4a`};case`F4V`:return{ext:`f4v`,mime:`video/mp4`};case`F4P`:return{ext:`f4p`,mime:`video/mp4`};case`F4A`:return{ext:`f4a`,mime:`audio/mp4`};case`F4B`:return{ext:`f4b`,mime:`audio/mp4`};case`crx`:return{ext:`cr3`,mime:`image/x-canon-cr3`};default:return e.startsWith(`3g`)?e.startsWith(`3g2`)?{ext:`3g2`,mime:`video/3gpp2`}:{ext:`3gp`,mime:`video/3gpp`}:{ext:`mp4`,mime:`video/mp4`}}}if(this.checkString(`REGEDIT4\r
@@ -57,7 +57,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D
57
57
  `,1)[0]??``}function LL(e,t){try{if(t.endsWith(`.yaml`)||t.endsWith(`.yml`))return{value:(0,ej.parse)(e)};let n=[],r=kL(e.replace(/^\uFEFF/,``),n,{allowTrailingComma:!0}),i=n[0];return i?{error:`${rue(i.error)} at offset ${i.offset}`}:{value:r}}catch(e){return{error:IL(e)}}}function RL(e,t,n){let r=NL(t?z(e,R(t)):e,e);if(r&&n)for(let e of r.problems)n(`[${r.file}] ${e}`);return r}function zL(e,t){let n=t?.rules??e.plugins.markdownlint.rules;return{...e,plugins:{...e.plugins,markdownlint:{...e.plugins.markdownlint,rules:n}}}}function BL(e,t,n){let r=t.plugins.frontmatter;if(!r.enabled||r.schemas.length===0||r.schemas.every(e=>e.key!==void 0))return t;let{entries:i,problems:a}=Vle(e,r.schemas);if(n)for(let e of a)n(e);return{...t,plugins:{...t.plugins,frontmatter:{...r,schemas:i}}}}function VL(e,t,n={}){let r=zL(t,RL(e,n.docName,n.onProblem));return BL(n.projectDir??e,r,n.onProblem)}var HL=class extends Error{constructor(e=`the lint configuration or branch changed during the audit walk`){super(e),this.name=`AuditSupersededError`}};async function UL(e){let{projectDir:t,contentDir:n,baseConfig:r,docRelPath:i,onConfigProblem:a,liveSourceFor:o,cache:s}=e,c=o?.(i)??null,l=VL(n,r,{docName:i,projectDir:t,onProblem:a});if(c!==null)return{file:i,diagnostics:await ni(c,l,i)};let u=qL(z(n,i),n),d=null;if(s!==void 0){try{let e=iu(u);d=lL.key({contentDir:n,docRelPath:i,mtimeMs:e.mtimeMs,size:e.size,configFingerprint:lL.fingerprintConfig(l)})}catch{d=null}if(d!==null){let e=s.get(d);if(e!==null)return{file:i,diagnostics:e}}}let f=await ni(U(u,`utf-8`),l,i);return d!==null&&s?.set(d,f),{file:i,diagnostics:f}}async function WL(e){let{projectDir:t,contentDir:n,baseConfig:r,docRelPath:i,source:a,onConfigProblem:o}=e,s=VL(n,r,{docName:i,projectDir:t,onProblem:o});return{cfg:s,before:await ni(a,s,i),fixed:Me(a,s)}}function GL(e){let{projectDir:t,contentDir:n,scopeDir:r,onWarning:i}=e,a=rL({projectDir:t,contentDir:n}),o=[];function s(e){let t;try{t=$l(e,{withFileTypes:!0})}catch(t){i?.(`could not read ${B(n,e)||`.`}: ${XL(t)}`);return}for(let r of t){if(r.name.startsWith(`.`))continue;let t=z(e,r.name),i=B(n,t);if(r.isDirectory()){if(a.isDirExcluded(i))continue;s(t)}else if(r.isFile()){if(!YL(r.name)||a.isExcluded(i))continue;o.push(i)}}}return s(r??n),o}async function KL(e){let{projectDir:t,contentDir:n,baseConfig:r,targetPath:i,auditGeneration:a}=e,o=[],s=a?.(),c=[],l=JL(i,n),u=B(n,l.path);if(u.startsWith(`..`)||Ml(u))return o.push(`refusing audit scope outside the content directory: ${i??``}`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o};if(u.split(`/`).some(e=>e.startsWith(`.`)))return o.push(`refusing audit scope under a hidden path segment: ${i??``}`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o};try{if(!Ej(W(l.path),W(n)))return o.push(`symlink-escape: audit scope resolves outside the content directory`),{files:[],fileCount:0,errorCount:0,warningCount:0,warnings:o}}catch{}l.kind===`file`?c.push(B(n,l.path)):c.push(...GL({projectDir:t,contentDir:n,scopeDir:l.path,onWarning:e=>o.push(e)})),c.sort();let d=[],f=0,p=0,m=new Set,h=e=>{m.has(e)||(m.add(e),o.push(e))},g=BL(t,r,h),_=g.plugins.frontmatter;if((i===void 0||i===``)&&_.enabled)for(let e of pL(_.schemas,c))h(e);let v=performance.now();for(let r of c){if(performance.now()-v>=8){if(await Lu(),a!==void 0&&a()!==s)throw new HL;v=performance.now()}let i;try{i=await UL({projectDir:t,contentDir:n,baseConfig:g,docRelPath:r,onConfigProblem:h,liveSourceFor:e.liveSourceFor,cache:e.cache})}catch(e){o.push(`could not lint ${r}: ${XL(e)}`);continue}for(let e of i.diagnostics)e.severity===`error`?f++:p++;i.diagnostics.length>0&&d.push(i)}return{files:d,fileCount:c.length,errorCount:f,warningCount:p,warnings:o}}function qL(e,t){let n=W(t),r;try{r=W(e)}catch(e){throw e.code===`ELOOP`?new PI(`symlink cycle in path`):e}if(!Ej(r,n))throw new PI(`path resolves outside content directory`);return r}function JL(e,t){if(e===void 0||e===``)return{kind:`dir`,path:t};let n=Ml(e)?e:V(t,e);try{if(iu(n).isFile())return{kind:`file`,path:n}}catch{}return{kind:`dir`,path:n}}function YL(e){let t=e.toLowerCase();return or.some(e=>t.endsWith(e))}function XL(e){return e instanceof Error?e.message:String(e)}function ZL(e,t){return{refusal:{action:`refused`,file:e,reason:t}}}function QL(e,t,n){let r=V(e,t);if(!uL(r,V(e)))return ZL(t,`path resolves outside the project`);if(H(r)){let n;try{n=W(r)}catch(e){return ZL(t,`cannot read (${e instanceof Error?e.message:String(e)})`)}return uL(n,W(e))?{target:n,exists:!0,currentText:U(n,`utf-8`)}:ZL(t,`path resolves outside the project`)}if(n===`require-existing`)return ZL(t,`file does not exist`);Jl(R(r),{recursive:!0});let i=W(R(r));return uL(i,W(e))?{target:V(i,kl(r)),exists:!1,currentText:``}:ZL(t,`path resolves outside the project`)}function $L(e,t,n,r,i=[]){let a=QL(e,t,`create-missing`);if(`refusal`in a)return a.refusal;let o;try{o=Dr(a.currentText,n,r,i)}catch(e){if(e instanceof Ni)return{action:`refused`,file:t,reason:e.message};throw e}return o===a.currentText?{action:`written`,file:t}:(dL(a.target,o),{action:a.exists?`written`:`created`,file:t})}function eR(e,t){let n=QL(e,t,`create-missing`);return`refusal`in n?n.refusal:n.exists?{action:`written`,file:t}:(dL(n.target,ba()),{action:`created`,file:t})}function tR(e,t,n){let r=QL(e,t,`require-existing`);if(`refusal`in r)return r.refusal;let i;try{i=n(r.currentText)}catch(e){if(e instanceof Ni)return{action:`refused`,file:t,reason:e.message};throw e}return i!==r.currentText&&dL(r.target,i),{action:`written`,file:t}}function nR(e,t,n,r=[]){return tR(e,t,e=>Vr(e,n,r))}function rR(e,t,n,r,i=[]){return tR(e,t,e=>ta(e,n,r,i))}function iR(e,t){if(!La(t))return{action:`refused`,file:t,reason:`only *.schema.json files (or .ok/schemas/*.json) can be deleted`};let n=V(e,t);if(!uL(n,V(e)))return{action:`refused`,file:t,reason:`path resolves outside the project`};let r;try{r=W(R(n))}catch(e){let n=e.code;return n===`ENOENT`||n===`ENOTDIR`?{action:`deleted`,file:t}:{action:`refused`,file:t,reason:`cannot read (${e instanceof Error?e.message:String(e)})`}}if(!uL(r,W(e)))return{action:`refused`,file:t,reason:`path resolves outside the project`};try{Ko(V(r,kl(n)))}catch(e){if(e.code===`ENOENT`)return{action:`deleted`,file:t};throw e}return{action:`deleted`,file:t}}function aR(e,t){return e.endsWith(`.yaml`)||e.endsWith(`.yml`)?(0,ej.stringify)(t):`${JSON.stringify(t,null,2)}\n`}function oR(e,t){return Na(e,t)?.key??ga(t)??t}function sR(e,t){let n=ga(t);return n===null?t in e?[t]:[]:Object.keys(e).filter(e=>ga(e)===n)}const cR={insertSpaces:!0,tabSize:2,eol:`
58
58
  `};function lR(e,t,n,r){let i=e;if(r===null){for(let e of sR(t,n))i=jL(i,AL(i,[e],void 0,{formattingOptions:cR}));return i}let a=oR(t,n);return jL(i,AL(i,[a],r,{formattingOptions:cR}))}function uR(e,t,n){let r=ML(e),i=r?.name??`.markdownlint.json`,a=r?.path??z(e,i);if(r&&/\.(cjs|mjs|js)$/.test(r.path))return{action:`declined-executable`,file:r.name};if(!r&&n===null)return{action:`noop`,file:i};let o=r?PL(e):null,s=i.endsWith(`.yaml`)||i.endsWith(`.yml`);if(r&&o&&!s){let e=lR(o.raw,o.rules,t,n),r=kL(e.replace(/^\uFEFF/,``),[],{allowTrailingComma:!0});return(!r||typeof r!=`object`||Object.keys(r).length===0)&&tue(e)===e?(Ko(a),{action:`deleted`,file:i}):(dL(a,e),{action:`written`,file:i})}let c=o?{...o.rules}:r?{}:{...Vi};if(n===null)for(let e of sR(c,t))delete c[e];else c[oR(c,t)]=n;return Object.keys(c).length===0?r?(Ko(a),{action:`deleted`,file:i}):{action:`noop`,file:i}:(dL(a,aR(i,c)),{action:`written`,file:i})}function dR(e){return{files:e.files.map(e=>({file:e.file,...Ha(e.diagnostics)})),fileCount:e.fileCount,errorCount:e.errorCount,warningCount:e.warningCount,warnings:e.warnings}}function fR(e){return[hR(e),gR(e)]}async function pR(e,t={}){let n=await Promise.all(e.map(async e=>{try{return await e.run(t)}catch(t){if(t instanceof HL)throw t;L(`validation-audit`).error({err:t,validatorId:e.id},`[audit] validator threw; degrading to a plane warning`);let n=t instanceof Error?t.message:String(t);return{files:[],fileCount:0,warnings:[`validator "${e.id}" failed: ${n}`]}}})),r=new Map,i=[],a=0;for(let e of n){i.push(...e.warnings),a=Math.max(a,e.fileCount);for(let t of e.files){let e=r.get(t.file);e?e.push(...t.diagnostics):r.set(t.file,[...t.diagnostics])}}let o=[...r.entries()].map(([e,t])=>({file:e,diagnostics:t.sort(mR)})).sort((e,t)=>e.file.localeCompare(t.file)),s=0,c=0;for(let e of o)for(let t of e.diagnostics)t.severity===`error`?s++:c++;return{files:o,fileCount:a,errorCount:s,warningCount:c,warnings:i}}function mR(e,t){return e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character||e.source.localeCompare(t.source)||e.code.localeCompare(t.code)}function hR(e){return{id:`lint`,async run(t){let n=await KL({projectDir:e.projectDir,contentDir:e.contentDir,baseConfig:e.baseConfig,targetPath:t.targetPath,liveSourceFor:e.liveSourceFor,cache:e.cache,auditGeneration:e.auditGeneration});return{files:n.files,fileCount:n.fileCount,warnings:n.warnings}}}}function gR(e){let t=e.linksValidation??`warning`;return{id:`links`,async run(n){if(t===`off`)return{files:[],fileCount:0,warnings:[]};let r=t===`error`?`error`:`warning`;if(!e.derivedDocumentIndex)return{files:[],fileCount:0,warnings:[`links validation unavailable: backlink index is not configured`]};let i=[...await e.admittedDocNames()],a=_R(i,n.targetPath);if(a!==void 0&&a.length===0)return{files:[],fileCount:0,warnings:[]};let o=await e.derivedDocumentIndex.getDeadLinks(i,a),s=new Map;for(let{target:t,sources:n}of o)for(let i of n){let n=e.docFilePathFor(i.source)??`${i.source}.md`,a=i.line??0,o=i.column??0,c=s.get(n)??[];c.push({range:{start:{line:a,character:o},end:{line:a,character:o}},severity:r,source:`links`,code:`dead-link`,message:`Link target "${t}" does not resolve to an existing document.`,linkTarget:t}),s.set(n,c)}return{files:[...s.entries()].map(([e,t])=>({file:e,diagnostics:t})),fileCount:0,warnings:[]}}}}function _R(e,t){if(t===void 0||t===``)return;let n=t.toLowerCase();if(or.some(e=>n.endsWith(e))){let n=t.slice(0,t.lastIndexOf(`.`));return e.filter(e=>e===n)}let r=`${t.replace(/\/+$/,``)}/`;return e.filter(e=>e.startsWith(r))}const vR=L(`mermaid-validator`);let yR=null;function bR(e){let t=[],n=e.split(`
59
59
  `),r=e=>e.endsWith(`\r`)?e.slice(0,-1):e,i=0;for(;i<n.length;){let e=r(n[i]??``),a=e.match(/^ {0,3}(`{3,}|~{3,})[ \t]*([^\s`]*)/);if(!a){i++;continue}let o=a[1]??``,s=o[0]??"`";if(s==="`"&&e.slice(e.indexOf(o)+o.length).includes("`")){i++;continue}let c=a[2]??``,l=RegExp(`^ {0,3}\\${s}{${o.length},}[ \t]*$`),u=[],d=i+1;for(;d<n.length&&!l.test(r(n[d]??``));)u.push(n[d]??``),d++;if(c===`mermaid`){let e=u.join(`
60
- `),n=(u.find(e=>e.trim().length>0)?.trim()??``).slice(0,200);t.push({firstLine:n,body:e})}i=d+1}return t}async function xR(){let{Window:e}=await import(`./lib-BS_oZ9bm.mjs`),t=new e({url:`http://localhost/`}),n={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},r=new Map;try{for(let[e,t]of Object.entries(n))r.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-CZm3qvuv.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
60
+ `),n=(u.find(e=>e.trim().length>0)?.trim()??``).slice(0,200);t.push({firstLine:n,body:e})}i=d+1}return t}async function xR(){let{Window:e}=await import(`./lib-TLTWf9qr.mjs`),t=new e({url:`http://localhost/`}),n={window:t,document:t.document,navigator:t.navigator,location:t.location,DOMParser:t.DOMParser,Element:t.Element,Node:t.Node,SVGElement:t.SVGElement,HTMLElement:t.HTMLElement,MutationObserver:t.MutationObserver},r=new Map;try{for(let[e,t]of Object.entries(n))r.set(e,Object.getOwnPropertyDescriptor(globalThis,e)),Object.defineProperty(globalThis,e,{value:t,configurable:!0,writable:!0});let e=(await import(`./mermaid.core-CB8v9A8r.mjs`)).default;return e.initialize({startOnLoad:!1,securityLevel:`strict`,suppressErrorRendering:!0}),await e.parse(`graph LR
61
61
  A-->B`),e}finally{for(let[e,t]of r)t?Object.defineProperty(globalThis,e,t):delete globalThis[e]}}function SR(e){return yR??=xR().catch(t=>(vR.warn({err:t,"doc.name":e},`mermaid validator unavailable — render validation disabled for this process`),null)),yR}function CR(e){let t=e.match(/Parse error on line (\d+)/);if(!t?.[1])return;let n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:void 0}async function wR(e,t){try{if(!e.includes(`mermaid`))return;let{body:n}=Wn(e),r=bR(n);if(r.length===0)return;let i=performance.now(),a=await SR(t);if(a===null)return;let o=performance.now(),s=[],c=0;for(let e=0;e<r.length&&s.length<10&&!(c>=20);e++){if(performance.now()-o>2e3){vR.debug({"doc.name":t,skippedFrom:e+1,fences:r.length},`mermaid validation budget exceeded — remaining fences skipped`);break}let n=r[e];if(n!==void 0){if(n.body.length>1e5||n.body.split(`
62
62
  `).length>2e3){vR.debug({"doc.name":t,fenceIndex:e+1},`mermaid fence over validation caps — skipped`);continue}try{c++,await a.parse(n.body)}catch(r){if(r instanceof TypeError){vR.debug({err:r,"doc.name":t,fenceIndex:e+1},`mermaid validation skipped fence — environment failure`);continue}let i=r instanceof Error?r.message:String(r),a=i.slice(0,500),o=CR(i);s.push({kind:`mermaid-parse-error`,fenceIndex:e+1,fenceFirstLine:n.firstLine,message:a,...o===void 0?{}:{line:o}})}}}let l=Math.round(performance.now()-i);if(s.length===0){l>250&&vR.debug({"doc.name":t,durationMs:l,fences:r.length},`mermaid validation slow (no warnings)`);return}return vR.debug({"doc.name":t,count:s.length,durationMs:l},`mermaid render warnings emitted`),s}catch(e){vR.warn({err:e,"doc.name":t},`mermaid validation errored unexpectedly — skipped`);return}}const TR=`share-construct-url`;function ER(e,t){if(e===``)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t===`..`||t===`.git`||t.length===0)return!1;return!0}function DR(e,t,n,r,i){return`https://${e}/${t}/${n}/blob/${encodeURIComponent(r)}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function OR(e,t,n,r,i){let a=`https://${e}/${t}/${n}/tree/${encodeURIComponent(r)}`;return i===``?a:`${a}/${i.split(`/`).map(encodeURIComponent).join(`/`)}`}function kR(e,t){let n=t?.branchExists,r=t?.kind,i=t?.freshness;L(`share`).info({action:`construct-url`,result:e,...n===void 0?{}:{branchExists:n},...r===void 0?{}:{kind:r},...i===void 0?{}:{freshness:i}},`share action`)}function AR(e){let t=e instanceof Error?e.message:String(e);return t.length>500?`${t.slice(0,500)}…`:t}async function jR(e,t,n,r){try{let{git:i}=ws(e,{timeoutMs:5e3}),a=`refs/remotes/origin/${t}`;await i.raw([`rev-parse`,`--verify`,a]);let o=n===``?`.`:n,[s,c,l]=await Promise.all([i.raw([`cat-file`,`-e`,`${a}:${n}`]).then(()=>!0).catch(()=>!1),i.raw([`diff`,`--name-only`,a,`--`,o]),i.raw([`status`,`--porcelain`,`--untracked-files=all`,`--`,o])]);return s?c.trim()!==``||l.trim()!==``?`stale`:`current`:r===`folder`&&c.trim()===``&&l.trim()===``?`empty`:`absent`}catch(e){let t=AR(e);L(`share`).warn({action:`freshness-probe-failed`,kind:r,error:t},`[share] freshness probe failed; omitting freshness`);return}}const MR=L(`git-context`);function NR(e){let t=qu(e);return t.kind===`repository`?t.repository:null}function PR(e){let t=NR(e)?.readHead();return t?.kind===`branch`?t.branch:null}function FR(e){let t=e.toLowerCase().replace(/:\d+$/,``);return t===`www.github.com`?`github.com`:t}function IR(e){let t=e.trim();if(!t)return null;let n=(e,t,n,r)=>{let i=FR(e);return Mt.has(i)?null:{host:i,owner:t,repo:n,transport:r}},r=/^https?:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t);return r?n(r[1],r[2],r[3],`https`):(r=/^ssh:\/\/(?:[\w.-]+@)?([\w.-]+)(?::\d+)?\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r||(r=/^[\w.-]+@([\w.-]+):([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?$/.exec(t),r)?n(r[1],r[2],r[3],`ssh`):(r=/^git:\/\/([\w.-]+(?::\d+)?)\/([\w.\-~%]+)\/([\w.\-~%]+?)(?:\.git)?\/?$/.exec(t),r?n(r[1],r[2],r[3],`git`):null))}function LR(e){let t=NR(e)?.readRemoteUrl(`origin`);if(t?.kind!==`configured`)return null;let n=t.url;return{originUrl:n,github:IR(n)}}function RR(e){let t=LR(e);if(!t)return{kind:`no-remote`};if(t.github){let{host:e,owner:n,repo:r,transport:i}=t.github;return{kind:`ok`,host:e,owner:n,repo:r,transport:i}}return{kind:`non-github`}}function zR(e){let t=RR(e);return t.kind===`ok`?t.host:(MR.debug({kind:t.kind},`[git-context] origin is not a GitHub host — falling back to github.com`),`github.com`)}function BR(e){let t=LR(e);if(!t)return null;if(t.github){let{host:e,owner:n,repo:r}=t.github;return{label:e===`github.com`?`${n}/${r}`:`${e}/${n}/${r}`,webUrl:`https://${e}/${n}/${r}`}}return{label:VR(t.originUrl),webUrl:null}}function VR(e){let t=e.trim().replace(/\.git$/,``),n=/^[\w.-]+@([^:/]+):(.+)$/.exec(t);if(n)return`${n[1]}/${n[2]}`;let r=/^[a-z][a-z0-9+.-]*:\/\/(?:[^@/]+@)*(.+)$/i.exec(t);return r?r[1]:t}function HR(e,t){return NR(e)?.readRef(`refs/remotes/origin/${t}`).kind===`present`}const UR=`share-publish-owners`,WR=`share-publish-name-check`,GR=`share-publish`,KR=3e4;function qR(e){return e.length===0||e.length>100||e.startsWith(`.`)||e.startsWith(`-`)||/^-+$/.test(e)?!1:/^[A-Za-z0-9._-]+$/.test(e)}function JR(e){return e.length===0||e.length>39||e.startsWith(`-`)||e.endsWith(`-`)?!1:/^[A-Za-z0-9-]+$/.test(e)}function YR(e){let t=e.split(`
63
63
  `).map(e=>e.trim()).filter(Boolean);for(let e=t.length-1;e>=0;e--)try{let n=JSON.parse(t[e]);if(n&&typeof n==`object`&&!Array.isArray(n))return n}catch{}return null}function XR(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`owners`&&Array.isArray(e.owners)){let t=[];for(let n of e.owners){if(!n||typeof n!=`object`)continue;let e=n,r=typeof e.login==`string`?e.login:null,i=e.kind===`user`||e.kind===`org`?e.kind:null;if(r===null||i===null)continue;let a=typeof e.avatarUrl==`string`?e.avatarUrl:void 0;t.push({login:r,kind:i,...a?{avatarUrl:a}:{}})}return{ok:!0,owners:t}}return e.type===`error`?{ok:!1,error:ZR(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function ZR(e){return e===`auth-required`||e===`network`}function QR(e){return e===null?{ok:!1,error:`network`}:e.type===`name-check`&&typeof e.available==`boolean`?{ok:!0,available:e.available}:e.type===`error`?{ok:!1,error:ZR(e.code)?e.code:`network`}:{ok:!1,error:`network`}}const $R=new Set([`name-conflict`,`saml-sso`,`auth-required`,`push-failed`,`init-failed`,`network`,`no-project`]);function ez(e){return typeof e==`string`&&$R.has(e)}function tz(e){if(e===null)return{ok:!1,error:`network`};if(e.type===`publish`){let t=typeof e.ownerLogin==`string`?e.ownerLogin:null,n=typeof e.repoName==`string`?e.repoName:null,r=typeof e.cloneUrl==`string`?e.cloneUrl:null,i=typeof e.defaultBranch==`string`?e.defaultBranch:null;return t!==null&&n!==null&&r!==null&&i!==null?{ok:!0,ownerLogin:t,repoName:n,cloneUrl:r,defaultBranch:i}:{ok:!1,error:`network`}}return e.type===`error`?{ok:!1,error:ez(e.code)?e.code:`network`}:{ok:!1,error:`network`}}function nz(e,t,n){L(`share`).info({action:e,result:t,...n?.count===void 0?{}:{count:n.count},...n?.available===void 0?{}:{available:n.available}},`share action`)}function rz(e){return e.replace(/(https?:\/\/)([^:@\s/]+):([^@\s/]+)@/g,`$1$2:***@`)}const iz=`share-target-status`;function az(e,t){for(let n of e)if(n.from===t){if(n.status.startsWith(`R`))return{verdict:`renamed`,renamedTo:n.to};if(n.status===`D`)return{verdict:`deleted`}}return{verdict:`deleted`}}function oz(e,t){let n=t.endsWith(`/`)?t:`${t}/`,r=new Set;for(let t of e){if(!t.from.startsWith(n)||!t.status.startsWith(`R`))continue;let e=t.from.slice(n.length);t.to.endsWith(`/${e}`)?r.add(t.to.slice(0,t.to.length-e.length-1)):r.add(`\0ambiguous`)}let i=r.size===1?[...r][0]:void 0;return i!==void 0&&i!==`\0ambiguous`?{verdict:`renamed`,renamedTo:i}:{verdict:`deleted`}}async function sz(e,t,n,r,i={}){let a=L(`share`),o=e=>(a.info({action:`target-status`,verdict:e.verdict,kind:r},`target-status verdict`),e),{git:s}=ws(e,i.skipFetch?{}:{timeoutMs:i.fetchTimeoutMs??15e3});if(!i.skipFetch)try{await s.raw([`fetch`,`origin`,t])}catch(e){return a.warn({action:`target-status`,kind:r,error:AR(e)},`target-status fetch failed`),o({verdict:`unknown`})}let c=`origin/${t}`;try{if(await s.raw([`cat-file`,`-e`,`${c}:${n}`]).then(()=>!0).catch(()=>!1)){let t=await s.raw([`cat-file`,`-e`,`HEAD:${n}`]).then(()=>!0).catch(()=>!1),r=H(z(e,n));return o(t&&!r?{verdict:`changed-locally`}:{verdict:`on-origin`})}let t=(await s.raw([`log`,`-1`,`--format=%H`,c,`--`,n])).trim();if(t===``)return o({verdict:`never-on-branch`});let i=await eie(s,[`diff-tree`,`-M`,`-r`,`--no-commit-id`,`--name-status`,`${t}^1`,t]),a=r===`folder`?oz(i,n):az(i,n);return a.verdict===`renamed`&&!await s.raw([`cat-file`,`-e`,`${c}:${a.renamedTo}`]).then(()=>!0).catch(()=>!1)?o({verdict:`deleted`}):o(a)}catch(e){return a.warn({action:`target-status`,kind:r,error:AR(e)},`target-status detection failed`),o({verdict:`unknown`})}}const cz={discovery:`open-knowledge-discovery`,project:`open-knowledge`,"write-skill":`open-knowledge-write-skill`},lz=new Set(Object.values(cz));function uz(e){return lz.has(e)}const dz=Object.keys(cz),fz={discovery:`user`,project:`project`,"write-skill":`user`},pz=dz.filter(e=>fz[e]===`user`);function mz(e){return`packages/server/assets/skills/${e}/SKILL.md`}var hz=t(Gs(),1);const gz=102400,_z=`OpenKnowledge.app/Contents/Resources/cli/dist/assets/skills`;function vz(e,t={}){let n=t.platform??process.platform,r=t.checkDesktop??!1,i=t.home??uu(),a=[];r&&n===`darwin`&&(a.push(z(`/Applications`,_z,e)),a.push(z(i,`Applications`,_z,e))),a.push(Rl(new URL(`../dist/assets/skills/${e}`,import.meta.url))),a.push(Rl(new URL(`../assets/skills/${e}`,import.meta.url))),a.push(Rl(new URL(`./assets/skills/${e}`,import.meta.url)));for(let e of a)if(H(e))return e;throw Error(`Bundled skill asset directory not found for bundle '${e}'. Tried: ${a.join(`, `)}. This usually means the CLI build did not copy packages/server/assets into dist/assets. Run \`cd packages/cli && bun run build\` before publishing.`)}async function*yz(e,t=e){let n=await yu(e,{withFileTypes:!0});for(let r of n){let n=z(e,r.name);r.isDirectory()?yield*yz(n,t):r.isFile()&&(yield B(t,n))}}function bz(e,t=kl){return t(e)||`open-knowledge`}function xz(e,t=Fl){return t===`/`?e:e.split(t).join(`/`)}async function Sz(e,t,n=bz(e)){let r=new hz.ZipFile;r.addEmptyDirectory(`${n}/`);let i=[];for await(let t of yz(e))i.push(t);i.sort();for(let t of i){let i=z(e,t),a=`${n}/${xz(t)}`;r.addFile(i,a)}r.end(),await new Promise((e,n)=>{let i=Kl(t);r.outputStream.pipe(i),i.on(`close`,()=>e()),i.on(`error`,n),r.outputStream.on(`error`,n)})}async function Cz(e){return new Promise((t,n)=>{let r=Du(`sha256`),i=Gl(e);i.on(`data`,e=>r.update(e)),i.on(`end`,()=>t(r.digest(`hex`))),i.on(`error`,n)})}async function wz(e,t={}){let n=t.bundle??`project`,r=iu(e).size;if(r>gz)throw Error(`Built ${e} is ${r} bytes, exceeds ${gz}-byte ceiling`);let i=await Cz(e),a=await vu(z(t.sourceDir??vz(n,{checkDesktop:!1}),`SKILL.md`),`utf-8`),o=cz[n];if(!RegExp(`^name:\\s+${o}$`,`m`).test(a.slice(0,1500)))throw Error(`SKILL.md frontmatter \`name:\` does not match '${o}'. Check packages/server/assets/skills/${n}/SKILL.md frontmatter.`);return{size:r,sha256:i}}async function Tz(e={}){let t=e.bundle??`project`,n=e.sourceDir??vz(t,{checkDesktop:e.checkDesktop??!1}),r=e.outputPath??z(process.cwd(),`openknowledge.skill`);await Sz(n,r,cz[t]);let{size:i,sha256:a}=await wz(r,{bundle:t,sourceDir:n});return{outputPath:r,size:i,sha256:a}}const Ez=[`.ok`,`skill-install-events.jsonl`];async function Dz(e,t){let n=t?.homedir??(()=>process.env.HOME??``),r=t?.warn??((e,t)=>{L(`skills`).warn(e,t)}),i=n();if(!i){r({event:`skill-install-events.no-home`},`[skill-install-events] HOME not resolvable; telemetry skipped`);return}let a=z(i,...Ez),o=`${JSON.stringify(e)}\n`;try{await Uo(R(a),{recursive:!0})}catch(e){r({event:`skill-install-events.mkdir-failed`,err:e},`[skill-install-events] mkdir failed; telemetry skipped`);return}try{await Bo(a,o,{flag:`a`,encoding:`utf-8`})}catch(e){r({event:`skill-install-events.append-failed`,err:e},`[skill-install-events] append failed; telemetry skipped`)}}function Oz(e){let t=e??uu(),n;try{n=Lo(`user`,t,t)}catch(e){return L(`skills`).warn({err:e},`could not resolve the user config path; not reporting`),{enabled:!1,home:t}}if(!H(n))return{enabled:!0,home:t};try{let e=(0,ej.parse)(U(n,`utf-8`))?.telemetry?.skillInstallReports?.enabled;return{enabled:typeof e==`boolean`?e:!0,home:t}}catch(e){return L(`skills`).warn({err:e,path:n},`user config exists but could not be read; not reporting skill installs`),{enabled:!1,home:t}}}const kz=zu(Zl);function Az(e){return z(e,...en)}async function jz(e,t){let n=Az(e);await Uo(R(n),{recursive:!0});try{return await Yo(`${n}.lock`,t)}catch(e){if(e.code===`LOCK_TIMEOUT`)return t();throw e}}const Mz={warn:(e,t)=>L(`skills`).warn(e,t)};async function Nz(e,t=Mz){let n=Az(e),r;try{r=await kz(n,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}let i=(0,ej.parseDocument)(r);if(i.errors.length>0)return t.warn({event:`skill-state.yaml-parse-error`,path:n,errors:i.errors.map(e=>e.message)},`skill-state.yml parse failed; treating as fresh install`),null;let a=kt.safeParse(i.toJSON());if(!a.success){let e=a.error.issues.find(e=>e.path.length===1&&e.path[0]===`schema`);return e?t.warn({event:`skill-state.invalid-schema-version`,path:n,issue:e.message},`skill-state.yml has unknown schema version; treating as fresh install`):t.warn({event:`skill-state.schema-violation`,path:n,issues:a.error.issues.map(e=>({path:e.path,message:e.message}))},`skill-state.yml failed schema validation; treating as fresh install`),null}return a.data}async function Pz(e,t){let n=kt.safeParse(t);if(!n.success)throw Error(`Refusing to write invalid skill-state: ${n.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`);let r=Az(e);await Uo(R(r),{recursive:!0});let i=(0,ej.parseDocument)(``);i.contents=i.createNode(n.data),await Io(r,i.toString(),{fs:Vo})}async function Fz(e,t,n){let r=await Nz(e,n);return r===null?null:r.targets[t]?.version??null}async function Iz(e,t,n){let r=await Nz(e,n);return r===null?null:r.targets[t]?.recordedAt??null}async function Lz(e,t,n,r,i){if(!gt.test(n))throw Error(`Refusing to write invalid version string: ${n}`);await jz(e,async()=>{let a=await Nz(e,i)??Yt(),o=new Date().toISOString(),s=a.targets[t],c=r===void 0?s?.surface??void 0:r,l=c===void 0?{version:n,recordedAt:o}:{version:n,recordedAt:o,surface:c};await Pz(e,{...a,targets:{...a.targets,[t]:l}})})}async function Rz(e,t,n){let r=(await Nz(e,n))?.bundles?.[t];return typeof r?.enabled==`boolean`?r.enabled:null}async function zz(e,t,n,r){await jz(e,async()=>{let i=await Nz(e,r)??Yt();await Pz(e,{...i,bundles:{...i.bundles,[t]:{enabled:n,decidedAt:new Date().toISOString()}}})})}async function Bz(e,t){let n=await Nz(e,t).catch(()=>null);return new Set(n?.installsReported??[])}async function Vz(e,t,n){t.length!==0&&await jz(e,async()=>{let r=await Nz(e,n)??Yt(),i=new Set([...r.installsReported??[],...t]);await Pz(e,{...r,installsReported:[...i].sort()})})}async function Hz(){let e=await kz(Rl(new URL(`../package.json`,import.meta.url)),`utf-8`),t=JSON.parse(e);if(typeof t.version!=`string`||t.version.length===0)throw Error(`@inkeep/open-knowledge-server/package.json missing version field`);return t.version}async function Uz(e,t){let[n,r]=await Promise.all([Hz(),Wz(e,t)]);return{currentVersion:n,targets:r}}async function Wz(e,t=Mz){let n=null;try{n=await Nz(e,t)}catch(r){t.warn({event:`skill-state.read-error`,path:Az(e),err:r},`non-ENOENT error reading skill-state.yml; treating as absent`),n=null}let r=mn.map(e=>{let t=n?.targets[e];return t?[e,{version:t.version,recordedAt:t.recordedAt}]:[e,null]});return Object.fromEntries(r)}const Gz=[`.local`,`.internal`,`.intranet`,`.corp`,`.home`,`.home.arpa`,`.lan`,`.private`,`.test`,`.invalid`,`.localhost`,`.localdomain`];function Kz(e){let t=e.split(`/`);return t.length===1?/^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/i.test(e)?!Gz.some(t=>e.toLowerCase().endsWith(t)):!1:t.length===2?t.every(e=>/^[\w.-]+$/.test(e)&&e!==`.`&&e!==`..`):!1}function qz(e){return!!(e.DISABLE_TELEMETRY||e.DO_NOT_TRACK)}async function Jz(e,t){let n=t.env??process.env;if(!t.enabled||qz(n)||!Kz(e.source.trim()))return[];let r=await Bz(t.home).catch(t=>(L(`skills`).warn({err:t,source:e.source},`could not read the install-report ledger; a duplicate report is possible`),new Set)),i=e.skills.filter(t=>!r.has(`${e.source}#${t}`));if(i.length===0)return[];let a=new URLSearchParams({event:`install`,source:e.source,skills:i.join(`,`)});e.agents&&e.agents.length>0&&a.set(`agents`,e.agents.join(`,`)),e.global&&a.set(`global`,`1`),e.version&&a.set(`v`,e.version);let o=t.fetchImpl??globalThis.fetch;if(!o)return[];try{await Vz(t.home,i.map(t=>`${e.source}#${t}`))}catch(t){return L(`skills`).warn({err:t,source:e.source,skills:i},`skill install report ledger write failed; not reporting this install`),[]}try{await o(`https://add-skill.vercel.sh/t?${a.toString()}`,{signal:AbortSignal.timeout(3e3)})}catch(t){L(`skills`).warn({err:t,source:e.source,skills:i},`skill install report could not be delivered; this install is not counted`)}return i}const Yz=`.agents`;function Xz(e,t){return z(e,Yz,`skills`,t)}function Zz(e){return er.filter(t=>H(z(e,t.hostDir)))}async function Qz(e,t){try{return(await xu(Xz(e,t))).isDirectory()}catch{return!1}}function $z(e,t,n){let r=[...t.map(e=>e.hostDir),Yz];for(let t of r){let r=z(e,t,`skills`,`open-knowledge`);if(H(r))try{ts(r,{recursive:!0,force:!0}),n.info?.({event:`skill-install.legacy-removed`,path:r},"Removed pre-split `open-knowledge` user-global skill dir.")}catch(e){n.warn({event:`skill-install.legacy-remove-failed`,path:r,err:e},"Legacy `open-knowledge` skill removal failed; continuing with install.")}}}function eB(e,t){ts(t,{recursive:!0,force:!0}),Zo(R(t),{recursive:!0}),es(e,t,{recursive:!0})}function tB(e,t,n,r){let i=[],a=Xz(e,t),o=[a,...r.map(n=>z(e,n.hostDir,`skills`,t)).filter(e=>e!==a)];for(let e of o)try{eB(n,e),i.push({path:e,status:`written`})}catch(t){i.push({path:e,status:`failed`,error:t instanceof Error?t.message:String(t)})}return i}async function nB(e={}){let t=e.home??uu(),n=e.logger??{warn:(e,t)=>L(`skills`).warn(e,t),info:(e,t)=>L(`skills`).info(e,t)},r=e.surface??`cli-npx-skills-add`,i=e.bundleId??`discovery`,a=cz[i];if(!Ml(t))return n.warn({event:`skill-install.failed`,reason:`home-not-absolute`,home:t},`Skill install aborted — $HOME is not an absolute path.`),`failed`;let o=async(e,a,o)=>{await Dz({ts:new Date().toISOString(),surface:r,target:`cli-hosts`,bundle:i,outcome:e,...a===void 0?{}:{version:a},...o===void 0?{}:{reason:o}},{homedir:()=>t,warn:n.warn})},s;try{s=await Rz(t,a,n)}catch(e){return n.warn({event:`skill-install.gate.decision-read-failed`,bundle:i,err:e},`Could not read the opt-out decision; skipping the install rather than risk reversing it.`),await o(`skip-current`,void 0,`decision-read-failed`),`skip-current`}if(s===!1)return n.info?.({event:`skill-install.declined`,bundle:i},`Bundle is opted out; skipping user-global skill install.`),await o(`skip-current`,void 0,`declined`),`skip-current`;let c;try{c=await Hz()}catch(e){return n.warn({event:`skill-install.failed`,reason:`version-read-failed`,err:e},`Skill install aborted — could not read @inkeep/open-knowledge-server version.`),await o(`failed`,void 0,`version-read-failed`),`failed`}let l=await Fz(t,`cli-hosts`,n).catch(e=>(n.warn({event:`skill-install.gate.read-failed`,err:e},`Could not read cli-hosts install-state; proceeding with fresh install.`),null));if(!e.force&&l!==null&&l===c){if(await Qz(t,a))return n.info?.({event:`skill-install.skip-current`,version:c},`OpenKnowledge skill already installed at current version; skipping.`),await o(`skip-current`,c),`skip-current`;n.info?.({event:`skill-install.reinstall-missing`,version:c,path:Xz(t,a)},`Sidecar matches current version but skill files are missing; reinstalling.`)}let u;try{u=vz(i,{checkDesktop:!1})}catch(e){return n.warn({event:`skill-install.failed`,reason:`bundled-asset-missing`,err:e},`Skill install aborted — bundled SKILL.md asset not found.`),await o(`failed`,c,`bundled-asset-missing`),`failed`}let d=Zz(t);if(d.length===0)return n.info?.({event:`skill-install.no-hosts`,version:c},`No supported agent host detected; skipping user-global skill install.`),await o(`skip-current`,c,`no-hosts`),`no-hosts`;$z(t,d,n);let f=tB(t,a,u,d),p=f.filter(e=>e.status===`written`),m=f.filter(e=>e.status===`failed`);if(p.length===0)return n.warn({event:`skill-install.failed`,reason:`write-failed`,entries:m},`Skill install failed — every destination write errored.`),await o(`failed`,c,`write-failed`),`failed`;try{await Lz(t,`cli-hosts`,c,r,n)}catch(e){return n.warn({event:`skill-install.failed`,reason:`sidecar-write-failed`,err:e},`Skill install succeeded but sidecar write failed.`),await o(`failed`,c,`sidecar-write-failed`),`failed`}return m.length>0&&n.warn({event:`skill-install.partial`,version:c,entries:m},`Some agent hosts could not be written; the remaining copies are installed.`),n.info?.({event:`skill-install.installed`,version:c,hosts:d.map(e=>e.editorId),paths:p.map(e=>e.path)},`OpenKnowledge skill installed to ${p.length} location(s): ${p.map(e=>e.path).join(`, `)}`),await o(`installed`,c),Jz({source:Fn,skills:[a],agents:d.map(e=>e.editorId),global:!0,version:c},{home:t,enabled:Oz(t).enabled}),`installed`}function rB(e){return z(e,`Downloads`,`openknowledge.skill`)}function iB(e,t,n){let r=zF({detached:!0,stdio:`ignore`});try{return t===`darwin`?(n(`open`,[e],r).unref(),{ok:!0}):t===`win32`?(n(`cmd`,[`/c`,`start`,`""`,e],r).unref(),{ok:!0}):t===`linux`?(n(`xdg-open`,[e],r).unref(),{ok:!0}):{ok:!1,reason:`unsupported-platform`,message:`Platform '${t}' has no file-association invocation wired.`}}catch(e){return{ok:!1,reason:`spawn-error`,message:e instanceof Error?e.message:String(e)}}}async function aB(e={}){let t=e.home??uu(),n=V(e.out??rB(t)),r=e.platformName??fu(),i=e.spawnFn??El,a=e.logger,o=async(e,n,r)=>{await Dz({ts:new Date().toISOString(),surface:`server-build-and-open`,target:`claude-cowork`,bundle:`project`,outcome:e,...n===void 0?{}:{version:n},...r===void 0?{}:{reason:r}},{homedir:()=>t,warn:a?.warn})};if(!e.force){let e=null;try{e=await Hz()}catch(e){a?.warn?.({event:`skill-install.gate.version-read-failed`,err:e},`Could not read @inkeep/open-knowledge-server version for gate check; rebuilding.`)}if(e!==null){let n=null,r=null;try{[n,r]=await Promise.all([Fz(t,`claude-cowork`,a),Iz(t,`claude-cowork`,a)])}catch(e){a?.warn?.({event:`skill-install.gate.read-failed`,err:e},`Could not read claude-cowork install-state; rebuilding.`)}if(n!==null&&n===e)return a?.info?.({event:`skill-install.skip-current`,target:`claude-cowork`,version:e},`OpenKnowledge skill already delivered at current version; skipping rebuild.`),await o(`skip-current`,e),{status:`skip-current`,skillVersion:e,...r===null?{}:{recordedAt:r}}}}try{await Uo(R(n),{recursive:!0})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`mkdir-failed:${t}`),{status:`failed`,buildError:`could not create output directory: ${t}`}}let s;try{s=await Tz({outputPath:n,bundle:`project`})}catch(e){let t=e instanceof Error?e.message:String(e);return await o(`failed`,void 0,`build-failed:${t}`),{status:`failed`,buildError:t}}let c;try{c=await Hz()}catch{c=void 0}let l={status:`built`,outputPath:s.outputPath,size:s.size,sha256:s.sha256,skillVersion:c};if(c)try{await Lz(t,`claude-cowork`,c,`server-build-and-open`,a)}catch(e){a?.warn?.({event:`skill-install.state-write-failed`,target:`claude-cowork`,version:c,err:e},`Skill bundle built but install-state write failed; gate will re-trigger build on next click.`)}if(e.noOpen)return await o(`built`,c),l;let u=iB(s.outputPath,r,i);return u.ok?(await o(`installed`,c),{...l,status:`installed`}):(await o(`built`,c,`handoff-${u.reason}`),{...l,handoffError:{reason:u.reason,message:u.message}})}function oB(e,t,n){let r;try{r=ql(e)}catch{return{kind:`absent`}}if(r.isSymbolicLink())try{return W(e)===W(t)?{kind:`symlink`,resolution:`target`}:{kind:`symlink`,resolution:`elsewhere`}}catch{return{kind:`symlink`,resolution:`dangling`}}if(!r.isDirectory())return{kind:`other`};try{if(W(e)===W(t))return{kind:`dir`,identity:`is-target`}}catch{return{kind:`dir`,identity:`different`}}return zD(e)?.contentHash===n?{kind:`dir`,identity:`same-content`}:{kind:`dir`,identity:`different`}}function sB(e){let t=St;return e.filter(e=>t.includes(e))}const cB=`open-knowledge`,lB=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,uB=[/^<{7} /m,/^={7}$/m,/^>{7} /m];function dB(e){let t=e.match(lB);if(!t)return null;try{let e=(0,ej.parse)(t[1]??``);return e&&typeof e==`object`&&!Array.isArray(e)?e:null}catch{return null}}function fB(e,t,n){let r=[],i=[],a=z(e,`SKILL.md`),o=H(z(e,`scripts`))&&iu(z(e,`scripts`)).isDirectory(),s=t.startsWith(cB)&&!t.startsWith(`open-knowledge-pack-`);if(!n?.allowReservedName&&s&&r.push(`"${t}" uses the reserved \`${cB}*\` prefix (reserved for OK's shipped skills) — choose another name.`),!H(a))return r.push(`No SKILL.md found at ${e}.`),{ok:r.length===0,errors:r,warnings:i,hasScripts:o};let c;try{c=U(a,`utf-8`)}catch(e){return r.push(`Cannot read SKILL.md: ${e.message}.`),{ok:!1,errors:r,warnings:i,hasScripts:o}}uB.some(e=>e.test(c))&&r.push("SKILL.md contains git conflict markers (`<<<<<<<` / `=======` / `>>>>>>>`). Resolve the conflict before installing.");let l=dB(c);if(l===null)r.push("SKILL.md has no valid `---` frontmatter block (name + description required).");else{let e=l.name,n=l.description;typeof e!=`string`||e.length===0?r.push(`SKILL.md frontmatter.name is missing or empty.`):e!==t&&r.push(`SKILL.md frontmatter.name ("${e}") must equal the skill directory ("${t}").`),(typeof n!=`string`||n.length===0)&&i.push("This skill has no `description`. Add one so agents know when to use it."),(typeof e==`string`&&Ne(e)||typeof n==`string`&&Ne(n))&&r.push("SKILL.md name/description contains XML tags (`<...>`), which break the skill loader.")}return{ok:r.length===0,errors:r,warnings:i,hasScripts:o}}function pB(e){return St.filter(t=>{let n=Zn[t];return n!==null&&H(V(e,n))})}function mB(e,t){if(t&&t.length>0){let e=new Set(St);return t.filter(t=>e.has(t))}return pB(e)}function hB(e){return e===`global`?Jn:Dt}function gB(e,t,n,r=Dt){let i=r[t];return i===null?null:V(e,i,n)}function _B(e,t,n,r=Dt){return t===`agents`?V(e,`.agents/skills`,n):gB(e,t,n,r)}function vB(e,t){if(!H(t))return!1;try{let n=B(W(e),W(t));return n.startsWith(`..`)||Ml(n)}catch{return!0}}function yB(e,t){if(!H(e)||!H(t))return!1;try{return W(e)===W(t)}catch{return!1}}function bB(e,t,n){let r=V(n),i=B(V(e),r);return i!==``&&!i.startsWith(`..`)&&!Ml(i)?B(t,r):r}function xB(e,t,n,r,i=`symlink`,a=Dt){let o=[];for(let s of r){let r=gB(n,s,t,a);if(r===null)continue;let c=R(r);if(vB(n,c))continue;if(yB(c,R(e))){o.push(s);continue}let l=V(r)===V(e);if(!l&&H(r))try{l=W(r)===W(e)}catch{l=!1}if(l){o.push(s);continue}ts(r,{recursive:!0,force:!0}),Zo(c,{recursive:!0}),i===`copy`?es(e,r,{recursive:!0,dereference:!0}):qo(bB(n,c,e),r,`dir`),o.push(s)}return o}function SB(e,t,n){let r=oB(e,t,n);switch(r.kind){case`absent`:return`absent`;case`other`:return`different`;case`symlink`:return r.resolution===`target`?`link-to-canonical`:`link`;case`dir`:return r.identity===`is-target`?`canonical-dir`:r.identity===`same-content`?`same-copy`:`different`}}function CB(e){let{canonicalAbs:t,canonicalHash:n,canonicalRootRel:r,name:i,cwd:a,targets:o}=e,s=e.roots??Dt,c=e.mode??`copy`,l=[],u=[],d=(e,n)=>{ts(e,{recursive:!0,force:!0}),Zo(n,{recursive:!0}),c===`link`?qo(bB(a,n,t),e,`dir`):es(t,e,{recursive:!0,dereference:!0})};for(let f of o){if(f===`agents`?r===`.agents/skills`:s[f]===r){let r=_B(a,f,i,s);if(r!==null&&!vB(a,R(r))){let i=SB(r,t,n);(c===`link`&&i===`same-copy`||c===`copy`&&e.convertLinks===!0&&i===`link-to-canonical`)&&d(r,R(r))}l.push(f);continue}let o=_B(a,f,i,s);if(o===null)continue;let p=R(o);if(!vB(a,p)){try{if(W(p)!==z(W(a),B(a,p)))continue}catch{}switch(SB(o,t,n)){case`canonical-dir`:l.push(f);break;case`link-to-canonical`:c===`copy`&&e.convertLinks===!0&&d(o,p),l.push(f);break;case`same-copy`:c===`link`&&d(o,p),l.push(f);break;case`different`:u.push(f);break;case`link`:case`absent`:d(o,p),l.push(f);break}}}return{hosts:l,conflicted:u}}function wB(e){let{canonicalHash:t,name:n,cwd:r,newTarget:i}=e,a=e.roots??Dt,o;try{o=W(e.canonicalAbs)}catch{return{ok:!1,reason:`target-unusable`}}try{if(ql(o).isSymbolicLink()||!ql(o).isDirectory())return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}let s=e.destDirAbs??_B(r,i,n,a);if(s===null)return{ok:!1,reason:`target-missing`};if(V(s)===o)return{ok:!0,newAbs:s};let c=R(s);if(vB(r,c))return{ok:!1,reason:`target-unusable`};switch(SB(s,o,t)){case`canonical-dir`:return{ok:!0,newAbs:s};case`different`:return{ok:!1,reason:`target-unusable`};case`same-copy`:try{if(ql(s).isSymbolicLink()||!H(z(s,`SKILL.md`)))return{ok:!1,reason:`target-unusable`}}catch{return{ok:!1,reason:`target-unusable`}}ts(o,{recursive:!0,force:!0});break;case`link`:case`link-to-canonical`:ts(s,{recursive:!0,force:!0}),Zo(c,{recursive:!0}),Wo(o,s);break;case`absent`:Zo(c,{recursive:!0}),Wo(o,s);break}return!H(z(s,`SKILL.md`))||ql(s).isSymbolicLink()?{ok:!1,reason:`target-unusable`}:(e.leaveLinkBehind===!0&&!H(o)&&qo(bB(r,R(o),s),o,`dir`),EB({name:n,cwd:r,roots:a,target:s,skip:[s,o],alsoClaim:[o,s]}),{ok:!0,newAbs:s})}const TB=[`agents`,...St];function EB(e){let{name:t,cwd:n,roots:r,target:i}=e,a=new Set((e.skip??[]).map(e=>V(e))),o=new Set((e.alsoClaim??[]).map(e=>V(e)));for(let e of TB){let s=_B(n,e,t,r);if(s===null||a.has(V(s)))continue;try{if(!ql(s).isSymbolicLink())continue}catch{continue}let c=null;try{c=W(s)}catch{c=null}c!==null&&!o.has(c)||(ts(s,{recursive:!0,force:!0}),qo(bB(n,R(s),i),s,`dir`))}}function DB(e){let{canonicalHash:t,name:n,cwd:r,targets:i}=e,a=e.roots??Dt,o;try{o=W(e.canonicalAbs)}catch{return[]}let s=[];for(let e of i){let i=_B(r,e,n,a);if(i!==null&&!vB(r,R(i)))switch(SB(i,o,t)){case`same-copy`:case`link`:case`link-to-canonical`:ts(i,{recursive:!0,force:!0}),s.push(e);break;default:break}}return s.length>0&&EB({name:n,cwd:r,roots:a,target:o}),s}function OB(e,t,n,r=Dt){let i=[];for(let a of n){let n=gB(t,a,e,r);if(n===null)continue;let o=!1;try{ql(n),o=!0}catch{o=!1}o&&(ts(n,{recursive:!0,force:!0}),i.push(a))}return i}function kB(e,t=``){let n=[];for(let r of $l(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...kB(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function AB(e){if(!H(e))return[];let t=[];for(let n of kB(e)){if(n===`SKILL.md`)continue;let r=null;try{let t=U(z(e,n));t.length<=262144&&!t.includes(0)&&(r=t.toString(`utf-8`))}catch(e){if(e?.code!==`ENOENT`)throw e;r=null}t.push({path:n,text:r})}return t}const jB=[`.ok`,`local`,`skill-placements.json`];function MB(e){return z(e,...jB)}function NB(e,t){if(t.length===0||t.includes(`\0`)||Ml(t)||t.split(/[/\\]/).some(e=>e===`..`))return null;let n=V(e),r=V(n,t);if(r===n||!r.startsWith(`${n}${Fl}`))return null;let i;try{i=W(n)}catch{return null}let a=r;for(;!H(a);){let e=R(a);if(e===a)return null;a=e}try{let e=W(a);if(e!==i&&!e.startsWith(`${i}${Fl}`))return null}catch{return null}return r}function PB(){return{schema:1,skills:{}}}function FB(e,t){if(!t||typeof t!=`object`)return!1;let n=t;return typeof n.path==`string`&&NB(e,n.path)!==null&&(n.mode===`copy`||n.mode===`link`)&&(n.hash===void 0||typeof n.hash==`string`)}function IB(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>e[1]===`copy`||e[1]===`link`);return t.length>0?Object.fromEntries(t):void 0}function LB(e){if(!e||typeof e!=`object`)return;let t=Object.entries(e).filter(e=>typeof e[1]==`string`&&e[1]!==``);return t.length>0?Object.fromEntries(t):void 0}function RB(e,t){if(!t||typeof t!=`object`)return;let n=[];for(let[r,i]of Object.entries(t)){if(NB(e,r)===null||!i||typeof i!=`object`)continue;let t=i;t.expect===`own`?n.push([r,{expect:`own`}]):t.expect===`link`&&typeof t.target==`string`&&NB(e,t.target)!==null&&n.push([r,{expect:`link`,target:t.target}])}return n.length>0?Object.fromEntries(n):void 0}function zB(e){let t=MB(e);if(!H(t))return PB();try{let n=JSON.parse(U(t,`utf-8`));if(!n||typeof n!=`object`)return PB();let r={};if(n.skills&&typeof n.skills==`object`)for(let[t,i]of Object.entries(n.skills)){if(!Array.isArray(i))continue;let n=i.filter(t=>FB(e,t));n.length>0&&(r[t]=n)}let i=Array.isArray(n.roots)?n.roots.filter(t=>typeof t==`string`&&NB(e,t)!==null):[],a=IB(n.preferences),o=LB(n.sources),s=RB(e,n.folders);return{schema:1,skills:r,...a?{preferences:a}:{},...o?{sources:o}:{},...i.length>0?{roots:i}:{},...s?{folders:s}:{}}}catch(e){return L(`skill-placements`).warn({err:e,path:t},`skill-placements.json is unreadable; continuing with an empty ledger (recorded placements for this project are lost)`),PB()}}const BB=sI();function VB(e,t){return BB(MB(e),async()=>{let n=zB(e);t(n),await HB(e,n)})}async function HB(e,t){let n=MB(e);await Uo(R(n),{recursive:!0}),await Io(n,`${JSON.stringify(t,null,2)}\n`,{fs:cI})}function UB(e){let t=zB(e),n=new Set(t.roots??[]);for(let r of Object.values(t.skills))for(let t of r){let r=t.path.split(`/`).slice(0,-1).join(`/`);r!==``&&NB(e,r)!==null&&n.add(r)}return[...n].sort()}function WB(e){return zB(e).sources??{}}function GB(e,t){return[...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({editor:e,root:t})),{editor:`agents`,root:t}]}const KB=GB(Dt,`.agents/skills`),qB=GB(Jn,`.agents/skills`);function JB(e,t){let n=ZB(e,t),r={},i;try{i=W(e)}catch{return r}for(let{editor:t,root:a}of n){let n;try{n=W(z(e,a))}catch{continue}n!==z(i,a)&&n.startsWith(`${i}/`)&&(r[t]=n.slice(i.length+1))}return r}function YB(e){return e===`project`?KB:qB}function XB(e){let t=ZB(e,`global`).map(t=>z(e,t.root)),n=z(e,`.ok`,`skills`);return t.includes(n)?t:[...t,n]}function ZB(e,t){let n=YB(t),r=new Set(n.map(e=>e.root));return[...n,...UB(e).filter(e=>!r.has(e)).map(e=>({editor:e,root:e}))]}function QB(e){return new Set((e===`project`?KB:qB).map(e=>e.root))}function $B(e,t){let n=new Map((t===`project`?KB:qB).map(e=>[e.editor,e.root])),r=new Set;for(let t of Object.keys(e)){let e=n.get(t);e===void 0?t.includes(`/`)&&r.add(t):r.add(e)}return r}function eV(e,t){let n=t===`project`?KB:qB;if(H(z(e,`.agents`)))return`.agents/skills`;let r=[...n].filter(e=>e.editor!==`agents`).sort((e,t)=>{let n=GD.indexOf(e.editor),r=GD.indexOf(t.editor);return(n===-1?GD.length:n)-(r===-1?GD.length:r)});for(let{root:t}of r)if(H(z(e,t)))return t;return`.claude/skills`}function tV(e){let t=[],n=(e,r)=>{for(let i of $l(e,{withFileTypes:!0})){let a=z(e,i.name),o=r===``?i.name:`${r}/${i.name}`,s=iu(a);s.isDirectory()?n(a,o):t.push(`${o}:${s.size}:${s.mtimeMs}`)}};try{n(e,``)}catch{return null}return t.sort().join(`|`)}const nV=new Map;function rV(e){let t=tV(e);if(t===null)return null;let n=nV.get(e);if(n!==void 0&&n.stamp===t)return n;let r=zD(e);if(!r)return null;let i={stamp:t,contentHash:r.contentHash,description:r.description};return nV.set(e,i),i}function iV(e,t){let n=[],r=WB(e),i=ZB(e,t),a=null;try{a=W(e)}catch{a=null}for(let{editor:o,root:s}of i){let i=z(e,s),c,l=!1;try{if(!H(i))continue;l=a!==null&&W(i)!==z(a,s),c=$l(i)}catch{continue}for(let e of c){let a=z(i,e);try{if(!iu(a).isDirectory())continue;let i=rV(a);if(!i)continue;n.push({name:e,scope:t,editor:o,contentHash:i.contentHash,dir:`${s}/${e}`,description:i.description,viaLink:l||ql(a).isSymbolicLink(),...l?{aliasRooted:!0}:{},...r[e]===o?{preferredSource:!0}:{}})}catch{}}}let{admittedDirs:o,canonicalDir:s}=PO(n),c=new Set(s.values());return qD(n).filter(e=>o.has(e.canonical.dir)).filter(e=>c.has(e.canonical.dir)||!uz(e.name)).sort((e,t)=>e.name.localeCompare(t.name)||Number(c.has(t.canonical.dir))-Number(c.has(e.canonical.dir))||e.contentHash.localeCompare(t.contentHash)).map(t=>{let r=null;try{r=W(z(e,t.canonical.dir))}catch{r=null}let i=t=>{if(r===null)return!1;try{return W(z(e,t))===r}catch{return!1}},a=t.copies.filter(e=>e.aliasRooted!==!0&&(e.viaLink||!i(e.dir))),o=n.filter(e=>e.name===t.canonical.name&&e.contentHash!==t.contentHash).map(e=>e.editor);return{name:t.canonical.name,description:t.canonical.description,dir:t.canonical.dir,hosts:[t.canonical.editor,...a.map(e=>e.editor)],linkedHosts:[t.canonical,...a].filter(e=>e.viaLink).map(e=>e.editor),conflictHosts:o,copyDirs:a.filter(e=>!e.viaLink).map(e=>e.dir),contentHash:t.contentHash}})}function aV(e){return iV(e,`project`)}function oV(e){return iV(e,`global`)}const sV=[...qB].sort((e,t)=>{let n=GD.indexOf(e.editor),r=GD.indexOf(t.editor);return(n===-1?GD.length:n)-(r===-1?GD.length:r)||e.editor.localeCompare(t.editor)});function cV(e,t){for(let{root:n}of sV){let r=z(e,n,t);try{if(H(z(r,`SKILL.md`)))return r}catch{}}return null}function lV(e){return new Set(aV(e).map(e=>e.dir))}function uV(e){let t=[];H(V(e,`SKILL.md`))&&t.push(`SKILL.md`);let n=V(e,`references`);if(!H(n))return t;let r=(e,n)=>{let i;try{i=$l(e,{withFileTypes:!0})}catch{return}for(let a of i){let i=n?`${n}/${a.name}`:a.name;a.isDirectory()?r(V(e,a.name),i):a.isFile()&&a.name.toLowerCase().endsWith(`.md`)&&t.push(`references/${i}`)}};return r(n,``),t}function dV(e){let{base:t,scope:n,fromName:r,toName:i}=e;if(r===i)return[];let a=L(`skill-ref-rename`),o;try{o=n===`project`?aV(t):oV(t)}catch(e){return a.warn({err:e,scope:n},`skill scan failed; refs to the old name are left as authored`),[]}let s=[];for(let e of o){let n=V(t,e.dir);for(let t of uV(n)){let o=V(n,t),c;try{c=U(o,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`unreadable skill markdown; skipped`);continue}let l=Un(c,r,i);if(l!==c){try{os(o,l,`utf-8`)}catch(e){a.warn({err:e,absPath:o},`skill ref rewrite could not be written; skipped`);continue}s.push({dir:e.dir,rel:t,absPath:o,markdown:l})}}}return s}function fV(e,t){let n=V(t),r;try{r=W(n)}catch(e){throw e.code===`ENOENT`?new PI(`root directory does not exist`):e}let i=V(e);for(let e=0;;e++){if(e>256)throw new PI(`too many symlink resolutions in path`);try{let e=W(i);if(!wj(e,r))throw new PI(`path resolves outside ${t}`);if(pV(e,r))throw new PI(`path resolves into the .git/.ok state tree`);return}catch(e){if(e instanceof PI)throw e;let r=e.code;if(r===`ELOOP`)throw new PI(`symlink cycle in path`);if(r!==`ENOENT`)throw e;let a=null;try{ql(i).isSymbolicLink()&&(a=eu(i))}catch{}if(a!==null){i=V(R(i),a);continue}let o=R(i);if(o===i)throw e;if(o!==n&&!wj(o,n))throw new PI(`path resolves outside ${t}`);i=o}}}function pV(e,t){let n=Cj(B(t,e));if(n===``||n.startsWith(`..`))return!1;let r=n.split(`/`)[0];return r===`.git`||r===`.ok`}var mV=class extends As{constructor(e,t){super(e,t,`ui`),this.name=`UiLockCollisionError`}};function hV(e,t){try{return Is({lockName:`ui`,lockDir:e,metadata:t}).lockPath}catch(e){throw e instanceof As&&e.lockName===`ui`?new mV(e.existing,e.lockPath):e}}function gV(e,t){Ps({lockName:`ui`,lockDir:e,port:t})}function _V(e){return Ms({lockName:`ui`,lockDir:e})}function vV(e,t){Ls({lockName:`ui`,lockDir:e,...t})}function yV(e){js({lockName:`ui`,lockDir:e})}var bV=class extends Error{reason;constructor(e,t){super(`UploadWriteError: ${e}`,{cause:t}),this.name=`UploadWriteError`,this.reason=e}};function xV(e){switch(e){case`urn:ok:error:malformed-upload`:return 400;case`urn:ok:error:storage-full`:return 507;case`urn:ok:error:storage-readonly`:return 500;case`urn:ok:error:storage-error`:return 500;case`urn:ok:error:collision-exhaustion`:return 500;default:return xt(e)}}function SV(e){return e.code===`ENOSPC`||e.code===`EDQUOT`?`urn:ok:error:storage-full`:e.code===`EROFS`||e.code===`EACCES`||e.code===`EPERM`?`urn:ok:error:storage-readonly`:`urn:ok:error:storage-error`}function CV(e){switch(e){case`urn:ok:error:malformed-upload`:return`Upload payload is malformed.`;case`urn:ok:error:storage-full`:return`Storage is full.`;case`urn:ok:error:storage-readonly`:return`Storage is read-only.`;case`urn:ok:error:storage-error`:return`Failed to write upload.`;case`urn:ok:error:collision-exhaustion`:return`Filename collision retries exhausted.`;default:return xt(e)}}const wV=L(`upload-streaming`);var TV=class extends wu{hash=Du(`sha256`);bytes=0;digested=!1;_transform(e,t,n){this.hash.update(e),this.bytes+=e.length,n(null,e)}digest(){if(this.digested)throw Error(`HashingPassThrough.digest() already called`);return this.digested=!0,this.hash.digest(`hex`)}byteLength(){return this.bytes}};function EV(e){return V(tN(e),`tmp`)}function DV(e){let t=EV(e);return Zo(t,{recursive:!0}),V(t,`upload-${Ou()}`)}function OV(e,t,n){let r=jl(n),i=n.slice(0,n.length-r.length),a=[n,...Array.from({length:99},(e,t)=>`${i}-${t+1}${r}`)];for(let n of a){let r=V(t,n);try{rs(e,r);try{Ko(e)}catch{}return n}catch(t){let n=t.code;if(n===`EEXIST`)continue;try{Ko(e)}catch{}throw n===`ENOSPC`||n===`EDQUOT`?new bV(`urn:ok:error:storage-full`,t):n===`EROFS`||n===`EACCES`||n===`EPERM`?new bV(`urn:ok:error:storage-readonly`,t):new bV(`urn:ok:error:storage-error`,t)}}try{Ko(e)}catch{}throw new bV(`urn:ok:error:collision-exhaustion`)}function kV(e,{ageMs:t=1440*60*1e3}={}){let n=EV(e),r={scanned:0,deleted:0,errors:0};if(!H(n))return r;let i;try{i=$l(n)}catch(e){return wV.warn({err:e,dir:n},`[upload-tempfile-sweep] readdir failed`),r.errors++,r}let a=Date.now()-t;for(let e of i){if(!e.startsWith(`upload-`))continue;r.scanned++;let t=V(n,e);try{if(iu(t).mtimeMs>=a)continue;Ko(t),r.deleted++}catch(e){wV.warn({err:e,path:t},`[upload-tempfile-sweep] entry failed`),r.errors++}}return(r.deleted>0||r.errors>0)&&wV.info({dir:n,scanned:r.scanned,deleted:r.deleted,errors:r.errors},`[upload-tempfile-sweep] swept ${r.deleted}/${r.scanned} (errors: ${r.errors})`),r}Do(),bs();let AV=null;function jV(){return AV||=ls().createCounter(`ok.index.rebuild_total`,{description:`Count of derived-index rebuild passes. Bounded labels: index.name ∈ {backlink, tag}, index.mode ∈ {full, reconcile}.`}),AV}let MV=null;function NV(){return MV||=ls().createHistogram(`ok.index.rebuild_duration_ms`,{description:`Duration of derived-index rebuild passes in milliseconds. Same bounded label pair as ok.index.rebuild_total.`,unit:`ms`}),MV}async function PV(e,t,n,r){return zo(`ok.index.rebuild`,{attributes:{"index.name":e,"index.mode":t}},async i=>{let a=performance.now();try{let e=await n();return r&&i.setAttributes(r(e)),e}finally{let n={"index.name":e,"index.mode":t};jV().add(1,n),NV().record(performance.now()-a,n)}})}const FV=L(`backlinks`);function IV(){return{backward:new Map,forward:new Map,externalForward:new Map,externalBackward:new Map,skillRefs:new Map}}function LV(e){let t=pa(e);if(t){let n=t.kind===`skill`?e:`${e.split(`/references/`)[0]}/SKILL`;return{name:t.name,kind:t.kind,skillDocName:n}}let n=mi(e);return n?{name:n.name,kind:n.kind,skillDocName:wr(`global`,n.name)}:null}function RV(e,t){if(!e)return t;let n=e.line===void 0?t:e;return{anchor:e.anchor??t.anchor,snippet:e.snippet??t.snippet,line:n.line,column:n.column}}function zV(e){if(!e)return null;for(let[,t]of[...e.entries()].sort(([e],[t])=>e.localeCompare(t)))if(t.anchor)return t.anchor;return null}function BV(e){return`external:${e}`}function VV(e){return e.startsWith(`external:`)?e.slice(9):null}function HV(e){return e.replace(/\s+/g,` `).trim()}function UV(e,t,n){if(!HV(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
@@ -94,7 +94,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D
94
94
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
95
95
  `).trim();e&&r.push(e)}return r}function IH(e){if(lC(e.docName)||uC(e.docName)||fC(e.docName)||pC(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;if(PH(r))return{kind:`refused`,reason:`conflict-markers`};if(r===t)return{kind:`noop`};if(n===t)return{kind:`clean`,newContent:r};let i=FH(t),a=FH(n),o=FH(r);return(i.length+1)*(a.length+1)>4e6||(i.length+1)*(o.length+1)>4e6?{kind:`refused`,reason:`too-large`}:LH(i,a,o)}function LH(e,t,n){let r=RH(e,t),i=RH(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
96
96
 
97
- `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function RH(e,t){let n=new Map,r=zH(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function zH(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint32Array((n+1)*i);for(let o=1;o<=n;o++){let n=o*i,s=(o-1)*i;for(let i=1;i<=r;i++)if(e[o-1]===t[i-1])a[n+i]=a[s+(i-1)]+1;else{let e=a[s+i],t=a[n+(i-1)];a[n+i]=e>t?e:t}}let o=[],s=n,c=r;for(;s>0&&c>0;)e[s-1]===t[c-1]?(o.push([s-1,c-1]),s--,c--):a[(s-1)*i+c]>=a[s*i+(c-1)]?s--:c--;return o.reverse()}function BH(e,t,n,r,i,a,o){if(lC(n)||uC(n)||fC(n)||pC(n))return;let s=t.documents.get(n);if(!s)return;let c=s.getText(`source`).toString(),l=c===r,u=bi(c).frontmatter,{frontmatter:d}=bi(r),f=o&&XS(jH.context.origin)?{report:e=>o(n,e,LS.id,`file-watcher-intake`),baselineFullMd:c}:void 0;try{s.transact(()=>{MH(s,r,i,n,a,f)},jH)}catch(t){throw e.setReconciledBase(n,s.getText(`source`).toString()),t}u!==d&&zC(`file-watcher`),l||sF(n,LS.id,LS.name,LS.id,xd(n)),e.setReconciledBase(n,r)}function VH(e,t,n,r,i){return async(a,o)=>{try{BH(e,t,a,o,n,r,i),L(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof lo||e instanceof Oa)throw e;eae(),L(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const HH={reconciled:!1,baseBytes:0,diskBytes:0};function UH(e){let{frontmatter:t,body:n}=bi(e.getText(`source`).toString());return Oi(t,n)}function WH(e,t,n,r,i,a){if(lC(n)||uC(n)||fC(n)||pC(n))return HH;let o=t.documents.get(n);if(o&&DC(o))return HH;let s=e.getReconciledBase(n);if(s===void 0)return HH;let c;try{let e=Tj(n,r);if(!H(e))return HH;c=W(e)}catch{return HH}if(!Ej(c,r))return L(`reconcile`).warn({docName:n,canonical:c,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),HH;let l;try{l=U(c,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&L(`reconcile`).warn({docName:n,canonical:c,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),HH}if(hi(l)===hi(s))return HH;let u=e.peekInFlightFlush(n);if(u!==void 0){if(hi(l)===u)return tae(),L(`reconcile`).debug({docName:n,diskBytes:l.length},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),HH;nae(),L(`reconcile`).warn({docName:n,diskBytes:l.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${n}; falling through to merge`)}if(!o)return HH;let d=IH({docName:n,base:s,ours:UH(o),theirs:l});switch(L(`reconcile`).info({docName:n,result:d.kind,baseBytes:s.length,diskBytes:l.length},`[reconcile] before-agent-write ${n} result=${d.kind}`),d.kind){case`noop`:return HH;case`conflicts`:case`refused`:{let e=o.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,d.kind===`refused`?d.reason:`reconcile-conflicts`),HH}case`clean`:case`merged`:return BH(e,t,n,d.kind===`clean`?l:d.newContent,i,void 0,a),d.kind===`merged`&&e.setReconciledBase(n,l),{reconciled:!0,baseBytes:Buffer.byteLength(s,`utf8`),diskBytes:Buffer.byteLength(l,`utf8`),mergeOutcome:d.kind}}}const GH=new Map;function KH(e,t){GH.set(e,t)}function qH(e,t){let n=GH.get(e);if(n===void 0)return null;if(!vr.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=V(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=V(n,...e)}if(!r.startsWith(n+Fl))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}const JH=L(`file-watcher`);function YH(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function XH(e,t){return{title:YN(e,t),icon:ZN(e)}}function ZH(e){let t=new Map;for(let[n,r]of e)r.kind===`markdown`&&t.set(n,r);return t}const QH=new Map,$H=1e4;function eU(e,t){let n=QH.get(e)??[];n.push({hash:t,timestamp:Date.now()}),QH.set(e,n)}function tU(){let e=Date.now();for(let[t,n]of QH){let r=n.filter(t=>e-t.timestamp<=$H);r.length===0?QH.delete(t):r.length!==n.length&&QH.set(t,r)}}function nU(e){return Du(`sha256`).update(e).digest(`hex`)}const rU=[],iU=new Map;let aU=0,oU=0,sU=0;function cU(e,t,n){if(rU.push({ts:Date.now(),decision:e,kind:t,path:$o(n),pathRole:is(n)}),rU.length>256&&rU.shift(),e===`dispatched`){aU++;return}if(e===`self-write-skip`){oU++;return}let r=e.slice(5);iU.set(r,(iU.get(r)??0)+1),sU++,jU().add(1,{"disk.drop_reason":r})}function lU(){return rU.map(e=>({...e}))}function uU(){if(sU===0)return;let e=sU;sU=0;let t={};for(let[e,n]of iU)t[e]=n;JH.info({droppedSinceLastSummary:e,dropTotals:t,dispatched:aU,selfWriteSkips:oU},`[file-watcher] drop summary: ${e} event(s) dropped since last summary`)}function dU(){rU.length=0,iU.clear(),aU=0,oU=0,sU=0}function fU(e,t){let n;try{n=ql(e)}catch(t){let n=Vs(t);return n===`ENOENT`?!1:(JH.warn({path:e,code:n},`lstat failed for escape check on ${e} (${n}), dropping event`),!0)}if(!n.isSymbolicLink())return!1;let r;try{r=W(e)}catch(t){let n=Vs(t);return n!==`ENOENT`&&n!==`ELOOP`&&JH.warn({path:e,code:n},`realpath failed for escape check on ${e} (${n}), dropping event`),!0}return!Ej(r,t)}function pU(e,t){return $S(Cj(B(t,e)))}function mU(e,t){let n=B(e,t).replaceAll(`\\`,`/`);return!n||n===`.`||n===`..`||n.startsWith(`../`)?null:n}function hU(e,t,n,r,i=n){let a=mU(t,n);return a?(e.set(a,{size:0,modified:r.mtime.toISOString(),canonicalPath:i,inode:Number(r.ino)}),a):null}function gU(e,t){let n=!1;for(let r of e.keys())(r===t||r.startsWith(`${t}/`))&&(e.delete(r),n=!0);return n}function _U(e){let t=jl(e);if(t===``)return null;let n=t.toLowerCase();return n===`.mdx`||n===`.md`?t:null}const vU=new Map;function yU(e,t){vU.set(e,t)}function bU(e){let t=vU.get(e);return vU.delete(e),t}async function xU(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(ZS(r.path)){if(n){let e=Cj(B(t,r.path));if(n.isExcluded(e)){cU(`drop-filter-excluded`,r.type,r.path);continue}}switch(r.type){case`delete`:i.push(r);break;case`create`:vU.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await vu(e.path,`utf-8`))}catch(t){cU(`drop-read-failed`,e.type,e.path),Vs(t)!==`ENOENT`&&JH.warn({path:e.path,err:t},`Failed to read ${e.path}`)}for(let e of o)try{c.set(e.path,await vu(e.path,`utf-8`))}catch(t){cU(`drop-read-failed`,e.type,e.path),Vs(t)!==`ENOENT`&&JH.warn({path:e.path,err:t},`Failed to read ${e.path}`)}function l(e){let n=pU(e,t);if(!r)return n;let i=null;try{i=ql(e)}catch(t){return Vs(t)!==`ENOENT`&&JH.warn({path:e,err:t},`resolveDocName lstat failed for ${e}`),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=W(e)}catch(t){let i=Vs(t);return i!==`ENOENT`&&i!==`ELOOP`&&JH.warn({path:e,err:t},`resolveDocName realpath failed for ${e}`),r.delete(n),n}if(!Ej(a,t))return r.delete(n),n;let o=pU(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=bU(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=nU(r);if(i===t){d.add(n.path),f.add(e.path),yU(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(bU(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=nU(t);yU(e.path,n),PH(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=nU(t);yU(e.path,n),PH(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function SU(e,t){let n=QH.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&QH.delete(e),!0)}async function CU(e,t,n,r,i,a,o,s){let c=s??new Set;try{let s=await yu(e,{withFileTypes:!0});for(let l of s){let s=z(e,l.name),u;try{u=await _u(s)}catch(e){Vs(e)!==`ENOENT`&&JH.warn({path:s,err:e},`Failed to lstat ${s}, skipping`);continue}if(u.isSymbolicLink()){let e;try{e=await bu(s)}catch(e){let t=Vs(e);t===`ENOENT`||t===`ELOOP`?JH.warn({path:s,code:t},`Broken/cyclic symlink at ${s}, skipping`):JH.warn({path:s,err:e},`Failed to resolve symlink ${s}`);continue}if(!Ej(e,t)){JH.warn({path:s,canonical:e},`Symlink escape: ${s} → ${e}, skipping`);continue}try{let u=await xu(e);if(c.has(u.ino)){if(u.isFile()&&ZS(l.name)){let n=pU(s,t),i=pU(e,t);a.set(n,i);let o=r.get(i);o&&!o.aliases.includes(n)&&o.aliases.push(n)}else if(u.isDirectory()){let r=mU(t,s);(!n||r&&!n.isDirExcluded(r))&&o.set(pU(s,t),pU(e,t))}continue}if(c.add(u.ino),u.isDirectory()){let l=mU(t,s);if(n&&(!l||n.isDirExcluded(l)))continue;o.set(pU(s,t),pU(e,t)),await CU(e,t,n,r,i,a,o,c)}else if(u.isFile()&&ZS(l.name)){if(n){let r=Cj(B(t,e));if(n.isExcluded(r))continue}let i=pU(s,t),o=pU(e,t);a.set(i,o);try{let t=await vu(e,`utf-8`),n=nU(t);vU.set(e,n);let a=_U(e);if(a){let e=rC(o,a);if(e.shadowed&&(JH.warn({docName:o,effective:e.effective,shadowed:e.shadowed},`docName "${o}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(o,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[i],kind:`markdown`,...XH(t,o)})}catch(t){Vs(t)!==`ENOENT`&&JH.warn({path:e,err:t},`Failed to seed hash for ${e}`)}}else if(u.isFile()){if(n){let r=Cj(B(t,e));if(n.isPathIgnored(r))continue}let i=pU(s,t);if(lC(i)||uC(i))continue;r.set(i,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[],kind:`file`})}}catch(t){JH.warn({path:e,err:t},`Failed to stat symlink target ${e}`)}}else if(u.isDirectory()){let e=mU(t,s);if(n&&(!e||n.isDirExcluded(e)))continue;hU(i,t,s,u),await CU(s,t,n,r,i,a,o,c)}else if(u.isFile()&&ZS(l.name)){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=Cj(B(t,s));if(n.isExcluded(e))continue}try{let e=await vu(s,`utf-8`);vU.set(s,nU(e));let n=pU(s,t),i=_U(s);if(i){let e=rC(n,i);if(e.shadowed&&(JH.warn({docName:n,effective:e.effective,shadowed:e.shadowed},`docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`markdown`,...XH(e,n)})}catch(e){let t=Vs(e);t===`EACCES`?JH.warn({path:s,code:t},`Permission denied reading ${s}, file excluded from index`):t!==`ENOENT`&&JH.warn({path:s,err:e},`Failed to seed hash for ${s}`)}}else if(u.isFile()){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=Cj(B(t,s));if(n.isPathIgnored(e))continue}let e=pU(s,t);if(lC(e)||uC(e))continue;r.set(e,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`file`})}}}catch(t){Vs(t)!==`ENOENT`&&JH.warn({dir:e,err:t},`Failed to read directory ${e}`)}}function wU(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let n=e.relativePath;if(lC(n)||uC(n))return;if(e.kind===`file-delete`){let e=t.get(n);e&&e.kind===`file`&&t.delete(n);return}let r=t.get(n);if(r&&r.kind===`markdown`)return;t.set(n,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:e.inode||r?.inode||0,aliases:r?.aliases??[],kind:`file`});return}if(!mC(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=_U(e.path);i&&rC(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[],kind:`markdown`,...XH(e.content,n)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),cC(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),cC(e.oldDocName);let r=_U(e.newPath);r&&rC(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[],kind:`markdown`,...XH(e.content,e.newDocName)});break}default:YH(e)}}}function TU(e,t,n,r){let i=[],a=[];for(let o of e){let e=mU(t,o.path);if(!e)continue;if(o.type===`delete`){gU(r,e)&&i.push({kind:`folder-delete`,path:o.path,relativePath:e});continue}let s;try{s=ql(o.path)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:o.path,code:t},`folder lstat failed for ${o.path} (${t})`);continue}let c=null,l=o.path;if(s.isDirectory())c=s;else if(s.isSymbolicLink())try{if(l=W(o.path),!Ej(l,t))continue;let e=iu(l);e.isDirectory()&&(c=e)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:o.path,code:t},`folder symlink resolve failed for ${o.path} (${t})`),c=null}if(!c||n?.isDirExcluded(e))continue;let u=r.has(e);hU(r,t,o.path,c,l),u||(i.push({kind:`folder-create`,path:o.path,relativePath:e}),EU(l,t,n,r,i,a))}return{events:i,untrackedFiles:a}}function EU(e,t,n,r,i,a){let o=[e];for(;o.length>0;){let e=o.shift();if(e===void 0)continue;let s;try{s=$l(e,{withFileTypes:!0})}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({dir:e,code:n},`folder rescan readdir failed for ${e} (${n})`);continue}for(let c of s){if(c.isFile()){a.push(z(e,c.name));continue}if(!c.isDirectory())continue;let s=z(e,c.name),l=mU(t,s);if(!l||n?.isDirExcluded(l))continue;let u;try{u=ql(s)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:s,code:t},`folder rescan lstat failed for ${s} (${t})`);continue}u.isDirectory()&&(r.has(l)||(hU(r,t,s,u),i.push({kind:`folder-create`,path:s,relativePath:l})),o.push(s))}}}async function DU(e,t,n,r,i,a,o){let s=e.filter(e=>fU(e.path,t)?(cU(`drop-symlink-escape`,e.type,e.path),JH.warn({path:e.path,type:e.type},`Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:c,untrackedFiles:l}=TU(s,t,n,i),d=[];if(l.length>0){let e=new Set(s.map(e=>e.path)),n=new Set;for(let e of r.values())n.add(e.canonicalPath);d=l.filter(t=>!e.has(t)&&!vU.has(t)&&!n.has(t)).filter(e=>fU(e,t)?(cU(`drop-symlink-escape`,`create`,e),!1):!0).map(e=>({type:`create`,path:e})),d.length>0&&JH.debug({count:d.length,paths:d.map(e=>Cj(B(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let f=d.length>0?s.concat(d):s,p=f.filter(e=>ZS(e.path)),m=f.filter(e=>QS(e.path,u)),h=f.filter(e=>!ZS(e.path));if(p.length===0&&m.length===0&&c.length===0&&h.length===0)return;let g=p.length>0?await xU(p,t,n,o):[];for(let e of g){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=nU(e.content),r=e.path;try{r=W(e.path)}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({path:e.path,code:n},`realpathSync failed for self-write check on ${e.path} (${n})`)}t=SU(r,n)}else if(e.kind===`rename`){let n=nU(e.content),r=e.newPath;try{r=W(e.newPath)}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({path:e.newPath,code:n},`realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=SU(r,n)}if(wU(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(R(e.docName));break;case`delete`:n.decrementMdDir(R(e.docName));break;case`rename`:n.decrementMdDir(R(e.oldDocName)),n.incrementMdDir(R(e.newDocName));break;case`update`:case`conflict`:break;default:YH(e)}if(t){JH.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!0}),cU(`self-write-skip`,e.kind,e.kind===`rename`?e.newPath:e.path);continue}JH.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!1});let i=e.kind===`rename`?e.newPath:e.path;cU(`dispatched`,e.kind,i),await zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":$o(i),"disk.path.role":is(i)}},async()=>a(e))}for(let e of c)JH.debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!1}),cU(`dispatched`,e.kind,e.path),await zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":$o(e.path),"disk.path.role":is(e.path)}},async()=>a(e));for(let e of m){if(n){let r=Cj(B(t,e.path));if(n.isExcluded(r)){cU(`drop-filter-excluded`,e.type,e.path);continue}}let r=Cj(B(t,e.path)),i=e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r};cU(`dispatched`,i.kind,e.path),await a(i)}for(let e of h){let i=Cj(B(t,e.path));if(n?.isPathIgnored(i)){cU(`drop-filter-excluded`,e.type,e.path);continue}if(lC(i)||uC(i)){cU(`drop-reserved-doc`,e.type,e.path);continue}if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:i};wU(t,r),cU(`dispatched`,t.kind,e.path),await a(t);continue}let o;try{o=ql(e.path),o.isSymbolicLink()&&(o=iu(e.path))}catch(t){let n=Vs(t);cU(`drop-stat-failed`,e.type,e.path),n!==`ENOENT`&&JH.warn({path:e.path,code:n},`file-event lstat failed for ${e.path} (${n})`);continue}if(!o.isFile())continue;let s=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)}:{kind:`file-update`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)};wU(s,r),cU(`dispatched`,s.kind,e.path),await a(s)}}let OU=null;function kU(){return OU||=ls().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),OU}let AU=null;function jU(){return AU||=ls().createCounter(`ok.file_watcher.drops`,{description:`File-watcher events dropped before dispatch, by bounded reason`}),AU}async function MU(e,t,n,r,i,a,o,s){let c;try{c=await import(`@parcel/watcher`)}catch(e){return JH.debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let l=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await c.subscribe(e,async(c,l)=>{if(c){JH.error({err:c},`parcel watcher callback error`);return}try{s?.(l.map(e=>e.path)),await DU(l.map(e=>({type:e.type,path:e.path})),e,t,n,r,i,a),o()}catch(e){JH.error({err:e},`parcel batch error`)}},l)}catch(e){return JH.warn({err:e},`@parcel/watcher subscribe failed, falling back to chokidar`),null}}function NU(e,t,n,r){let i=Cj(B(e,n));if(i===``||i===`.`)return!1;let a;if(r)a=r.isDirectory();else try{a=ql(n).isDirectory()}catch{return!1}if(a){let n=/^(\.[A-Za-z0-9_-]+)(\/skills(\/[^/]+)?)?$/.exec(i);return n&&n[1]!==`.ok`&&(n[2]!==void 0||H(z(e,i,`skills`)))?!1:t.isDirExcluded(i)}return t.isExcluded(i)}async function PU(e,t,n,r,i,a,o,s){let{watch:c}=await import(`./chokidar-BCS--vwu.mjs`),l=c(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(n,r)=>NU(e,t,n,r):void 0});l.on(`error`,e=>JH.error({err:e},`chokidar error`));let u=[],d=null;function f(c,l){u.push({type:c,path:l}),d||=setTimeout(()=>{let c=u;u=[],d=null,s?.(c.map(e=>e.path)),DU(c,e,t,n,r,i,a).then(o).catch(e=>JH.error({err:e},`chokidar batch error`))},50)}return l.on(`add`,e=>f(`create`,e)),l.on(`change`,e=>f(`update`,e)),l.on(`unlink`,e=>f(`delete`,e)),l.on(`addDir`,e=>f(`create`,e)),l.on(`unlinkDir`,e=>f(`delete`,e)),await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};l.once(`ready`,n),setTimeout(n,1e4).unref()}),{unsubscribe:()=>(d&&(clearTimeout(d),d=null,u=[]),l.close())}}async function FU(e,t,n,r={}){let{onRawBatch:i}=r,a;try{a=W(e)}catch{a=e}let o=new Map,s=new Map,c=new Map,l=new Map,u=0,d=null,f=-1,p=()=>{u++};await CU(a,a,n,o,s,c,l),p();let m=setInterval(tU,$H),h=setInterval(uU,6e4),g,_,v=process.env.OK_FILE_WATCHER_BACKEND===`chokidar`;try{let e=v||r.forceBackend===`chokidar`?null:await MU(a,n,o,s,t,c,p,i);if(e)g=e,_=`parcel`;else{if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable (forced backend)`);g=await PU(a,n,o,s,t,c,p,i),_=`chokidar`}}catch(e){throw clearInterval(m),clearInterval(h),e}let y=g.unsubscribe.bind(g);return JH.info({contentDir:a,backend:_},`watching for external .md changes`),{async unsubscribe(){return clearInterval(m),clearInterval(h),QH.clear(),vU.clear(),dU(),y()},getFileIndex(){return d&&f===u?d:(d=ZH(o),f=u,d)},getAllFilesIndex(){return o},getFileIndexGeneration(){return u},getFolderIndex(){return s},getAliasMap(){return c},getFolderAliasIndex(){return l},mutateFileIndex(e){wU(e,o),p()},pruneFileIndexNowExcluded(){if(!n)return 0;let e=0;for(let[t,r]of o){let i=Cj(B(a,r.canonicalPath));(r.kind===`file`?n.isPathIgnored(i):n.isExcluded(i))&&(o.delete(t),e++)}return e>0&&p(),e},pruneFolderIndexNowExcluded(){if(!n)return 0;let e=0;for(let t of s.keys())n.isDirExcluded(t)&&(s.delete(t),e++);return e},async rescanFromDisk(){await CU(a,a,n,o,s,c,l),p()}}}async function IU(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),n=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:n}}function LU(e){try{return iu(V(e,xe)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function RU(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=LU(t)}catch{e=!1}if(e)return{rootPath:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}async function zU(e,t){let{git:n}=ws(e),[r,i]=await Promise.allSettled([$re(n),nS(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function BU(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function VU(e,t,n,r){let{git:i}=ws(e);await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``?!0:i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=zU(e,t).catch(e=>(UU(e)||L(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${AR(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const HU=`git-branch-info`;function UU(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const WU=L(`git-checkout`),GU=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function KU(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(GU);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=W(n)}catch{r=n}return{held:!0,path:r}}const qU=`git-checkout`,JU=Ar;async function YU(e,t,n){if(n?.fastForward&&await XU(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r}=ws(e),i=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!i)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:JU(e)?`branch-not-found`:`fetch-failed`}}let a=await zU(e,i?t:`origin/${t}`);if(a.conflicts)return{ok:!1,reason:`dirty-conflict`,files:a.files};try{return await r.raw([`checkout`,t]),{ok:!0}}catch(e){let n=KU(e);return n.held?(WU.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(WU.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${AR(e)}`),{ok:!1,reason:`checkout-failed`})}}async function XU(e,t){let{git:n}=ws(e,{timeoutMs:15e3}),r=e=>n.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await n.raw([`fetch`,`origin`,t])}catch(e){return WU.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${AR(e)}`),`unavailable`}let i=await r(`refs/remotes/origin/${t}`);if(!i)return`unavailable`;let a=await r(`refs/heads/${t}`);if(!a||a===i)return`up-to-date`;let o=await n.raw([`merge-base`,a,i]).then(e=>e.trim()).catch(()=>``);if(o===a){try{await n.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return WU.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${AR(e)}`),`unavailable`}return await r(`refs/heads/${t}`)===i?`advanced`:`unavailable`}return o===i?`up-to-date`:`diverged`}const ZU=(e,t)=>{let n=Dl(`git`,[`config`,`--get`,t],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));return n.status!==0||!n.stdout?null:n.stdout.trim()||null};function QU(e){let t=Dl(`git`,[`rev-parse`,`--git-dir`],zF({cwd:e,encoding:`utf-8`,timeout:5e3})),n=Dl(`git`,[`rev-parse`,`--git-common-dir`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||n.status!==0?!1:V(e,t.stdout.trim())!==V(e,n.stdout.trim())}function $U(e){let t=Dl(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let n=Dl(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(n.status!==0){let e=n.stderr?.trim()??``,t=n.error?` [${n.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function eW(e,t,n,r=ZU){let i=r(e,`user.name`),a=r(e,`user.email`);if(i&&a)return{name:i,email:a};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function tW(e,t,n){let r=`--local`;QU(e)&&($U(e),r=`--worktree`);let i=(t,n)=>{let i=Dl(`git`,[`config`,r,t,n],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(i.status!==0){let e=i.stderr?.trim()??``,n=i.error?` [${i.error.message}]`:``;throw Error(`git config ${r} ${t} failed: ${e}${n}`)}};i(`user.name`,t),i(`user.email`,n)}function nW(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof Oa||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;q(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function rW(e,t){let n=Object.keys(e).join(`, `);return async(r,i)=>{let a=r.method===void 0?void 0:e[r.method];if(a){await a(r,i);return}q(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}const iW=`config.yml`;function aW(e,t){let n;try{n=ql(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(n.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function oW(e){let[t=`0`,n=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${n.length>0?n:`0`}`}function sW(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function cW(e,t){let n=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${pe}/config.project.schema.json
97
+ `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function RH(e,t){let n=new Map,r=zH(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function zH(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint32Array((n+1)*i);for(let o=1;o<=n;o++){let n=o*i,s=(o-1)*i;for(let i=1;i<=r;i++)if(e[o-1]===t[i-1])a[n+i]=a[s+(i-1)]+1;else{let e=a[s+i],t=a[n+(i-1)];a[n+i]=e>t?e:t}}let o=[],s=n,c=r;for(;s>0&&c>0;)e[s-1]===t[c-1]?(o.push([s-1,c-1]),s--,c--):a[(s-1)*i+c]>=a[s*i+(c-1)]?s--:c--;return o.reverse()}function BH(e,t,n,r,i,a,o){if(lC(n)||uC(n)||fC(n)||pC(n))return;let s=t.documents.get(n);if(!s)return;let c=s.getText(`source`).toString(),l=c===r,u=bi(c).frontmatter,{frontmatter:d}=bi(r),f=o&&XS(jH.context.origin)?{report:e=>o(n,e,LS.id,`file-watcher-intake`),baselineFullMd:c}:void 0;try{s.transact(()=>{MH(s,r,i,n,a,f)},jH)}catch(t){throw e.setReconciledBase(n,s.getText(`source`).toString()),t}u!==d&&zC(`file-watcher`),l||sF(n,LS.id,LS.name,LS.id,xd(n)),e.setReconciledBase(n,r)}function VH(e,t,n,r,i){return async(a,o)=>{try{BH(e,t,a,o,n,r,i),L(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof lo||e instanceof Oa)throw e;eae(),L(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const HH={reconciled:!1,baseBytes:0,diskBytes:0};function UH(e){let{frontmatter:t,body:n}=bi(e.getText(`source`).toString());return Oi(t,n)}function WH(e,t,n,r,i,a){if(lC(n)||uC(n)||fC(n)||pC(n))return HH;let o=t.documents.get(n);if(o&&DC(o))return HH;let s=e.getReconciledBase(n);if(s===void 0)return HH;let c;try{let e=Tj(n,r);if(!H(e))return HH;c=W(e)}catch{return HH}if(!Ej(c,r))return L(`reconcile`).warn({docName:n,canonical:c,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),HH;let l;try{l=U(c,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&L(`reconcile`).warn({docName:n,canonical:c,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),HH}if(hi(l)===hi(s))return HH;let u=e.peekInFlightFlush(n);if(u!==void 0){if(hi(l)===u)return tae(),L(`reconcile`).debug({docName:n,diskBytes:l.length},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),HH;nae(),L(`reconcile`).warn({docName:n,diskBytes:l.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${n}; falling through to merge`)}if(!o)return HH;let d=IH({docName:n,base:s,ours:UH(o),theirs:l});switch(L(`reconcile`).info({docName:n,result:d.kind,baseBytes:s.length,diskBytes:l.length},`[reconcile] before-agent-write ${n} result=${d.kind}`),d.kind){case`noop`:return HH;case`conflicts`:case`refused`:{let e=o.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,d.kind===`refused`?d.reason:`reconcile-conflicts`),HH}case`clean`:case`merged`:return BH(e,t,n,d.kind===`clean`?l:d.newContent,i,void 0,a),d.kind===`merged`&&e.setReconciledBase(n,l),{reconciled:!0,baseBytes:Buffer.byteLength(s,`utf8`),diskBytes:Buffer.byteLength(l,`utf8`),mergeOutcome:d.kind}}}const GH=new Map;function KH(e,t){GH.set(e,t)}function qH(e,t){let n=GH.get(e);if(n===void 0)return null;if(!vr.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=V(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=V(n,...e)}if(!r.startsWith(n+Fl))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}const JH=L(`file-watcher`);function YH(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function XH(e,t){return{title:YN(e,t),icon:ZN(e)}}function ZH(e){let t=new Map;for(let[n,r]of e)r.kind===`markdown`&&t.set(n,r);return t}const QH=new Map,$H=1e4;function eU(e,t){let n=QH.get(e)??[];n.push({hash:t,timestamp:Date.now()}),QH.set(e,n)}function tU(){let e=Date.now();for(let[t,n]of QH){let r=n.filter(t=>e-t.timestamp<=$H);r.length===0?QH.delete(t):r.length!==n.length&&QH.set(t,r)}}function nU(e){return Du(`sha256`).update(e).digest(`hex`)}const rU=[],iU=new Map;let aU=0,oU=0,sU=0;function cU(e,t,n){if(rU.push({ts:Date.now(),decision:e,kind:t,path:$o(n),pathRole:is(n)}),rU.length>256&&rU.shift(),e===`dispatched`){aU++;return}if(e===`self-write-skip`){oU++;return}let r=e.slice(5);iU.set(r,(iU.get(r)??0)+1),sU++,jU().add(1,{"disk.drop_reason":r})}function lU(){return rU.map(e=>({...e}))}function uU(){if(sU===0)return;let e=sU;sU=0;let t={};for(let[e,n]of iU)t[e]=n;JH.info({droppedSinceLastSummary:e,dropTotals:t,dispatched:aU,selfWriteSkips:oU},`[file-watcher] drop summary: ${e} event(s) dropped since last summary`)}function dU(){rU.length=0,iU.clear(),aU=0,oU=0,sU=0}function fU(e,t){let n;try{n=ql(e)}catch(t){let n=Vs(t);return n===`ENOENT`?!1:(JH.warn({path:e,code:n},`lstat failed for escape check on ${e} (${n}), dropping event`),!0)}if(!n.isSymbolicLink())return!1;let r;try{r=W(e)}catch(t){let n=Vs(t);return n!==`ENOENT`&&n!==`ELOOP`&&JH.warn({path:e,code:n},`realpath failed for escape check on ${e} (${n}), dropping event`),!0}return!Ej(r,t)}function pU(e,t){return $S(Cj(B(t,e)))}function mU(e,t){let n=B(e,t).replaceAll(`\\`,`/`);return!n||n===`.`||n===`..`||n.startsWith(`../`)?null:n}function hU(e,t,n,r,i=n){let a=mU(t,n);return a?(e.set(a,{size:0,modified:r.mtime.toISOString(),canonicalPath:i,inode:Number(r.ino)}),a):null}function gU(e,t){let n=!1;for(let r of e.keys())(r===t||r.startsWith(`${t}/`))&&(e.delete(r),n=!0);return n}function _U(e){let t=jl(e);if(t===``)return null;let n=t.toLowerCase();return n===`.mdx`||n===`.md`?t:null}const vU=new Map;function yU(e,t){vU.set(e,t)}function bU(e){let t=vU.get(e);return vU.delete(e),t}async function xU(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(ZS(r.path)){if(n){let e=Cj(B(t,r.path));if(n.isExcluded(e)){cU(`drop-filter-excluded`,r.type,r.path);continue}}switch(r.type){case`delete`:i.push(r);break;case`create`:vU.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await vu(e.path,`utf-8`))}catch(t){cU(`drop-read-failed`,e.type,e.path),Vs(t)!==`ENOENT`&&JH.warn({path:e.path,err:t},`Failed to read ${e.path}`)}for(let e of o)try{c.set(e.path,await vu(e.path,`utf-8`))}catch(t){cU(`drop-read-failed`,e.type,e.path),Vs(t)!==`ENOENT`&&JH.warn({path:e.path,err:t},`Failed to read ${e.path}`)}function l(e){let n=pU(e,t);if(!r)return n;let i=null;try{i=ql(e)}catch(t){return Vs(t)!==`ENOENT`&&JH.warn({path:e,err:t},`resolveDocName lstat failed for ${e}`),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=W(e)}catch(t){let i=Vs(t);return i!==`ENOENT`&&i!==`ELOOP`&&JH.warn({path:e,err:t},`resolveDocName realpath failed for ${e}`),r.delete(n),n}if(!Ej(a,t))return r.delete(n),n;let o=pU(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=bU(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=nU(r);if(i===t){d.add(n.path),f.add(e.path),yU(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||(bU(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=nU(t);yU(e.path,n),PH(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=nU(t);yU(e.path,n),PH(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function SU(e,t){let n=QH.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&QH.delete(e),!0)}async function CU(e,t,n,r,i,a,o,s){let c=s??new Set;try{let s=await yu(e,{withFileTypes:!0});for(let l of s){let s=z(e,l.name),u;try{u=await _u(s)}catch(e){Vs(e)!==`ENOENT`&&JH.warn({path:s,err:e},`Failed to lstat ${s}, skipping`);continue}if(u.isSymbolicLink()){let e;try{e=await bu(s)}catch(e){let t=Vs(e);t===`ENOENT`||t===`ELOOP`?JH.warn({path:s,code:t},`Broken/cyclic symlink at ${s}, skipping`):JH.warn({path:s,err:e},`Failed to resolve symlink ${s}`);continue}if(!Ej(e,t)){JH.warn({path:s,canonical:e},`Symlink escape: ${s} → ${e}, skipping`);continue}try{let u=await xu(e);if(c.has(u.ino)){if(u.isFile()&&ZS(l.name)){let n=pU(s,t),i=pU(e,t);a.set(n,i);let o=r.get(i);o&&!o.aliases.includes(n)&&o.aliases.push(n)}else if(u.isDirectory()){let r=mU(t,s);(!n||r&&!n.isDirExcluded(r))&&o.set(pU(s,t),pU(e,t))}continue}if(c.add(u.ino),u.isDirectory()){let l=mU(t,s);if(n&&(!l||n.isDirExcluded(l)))continue;o.set(pU(s,t),pU(e,t)),await CU(e,t,n,r,i,a,o,c)}else if(u.isFile()&&ZS(l.name)){if(n){let r=Cj(B(t,e));if(n.isExcluded(r))continue}let i=pU(s,t),o=pU(e,t);a.set(i,o);try{let t=await vu(e,`utf-8`),n=nU(t);vU.set(e,n);let a=_U(e);if(a){let e=rC(o,a);if(e.shadowed&&(JH.warn({docName:o,effective:e.effective,shadowed:e.shadowed},`docName "${o}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(o,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[i],kind:`markdown`,...XH(t,o)})}catch(t){Vs(t)!==`ENOENT`&&JH.warn({path:e,err:t},`Failed to seed hash for ${e}`)}}else if(u.isFile()){if(n){let r=Cj(B(t,e));if(n.isPathIgnored(r))continue}let i=pU(s,t);if(lC(i)||uC(i))continue;r.set(i,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[],kind:`file`})}}catch(t){JH.warn({path:e,err:t},`Failed to stat symlink target ${e}`)}}else if(u.isDirectory()){let e=mU(t,s);if(n&&(!e||n.isDirExcluded(e)))continue;hU(i,t,s,u),await CU(s,t,n,r,i,a,o,c)}else if(u.isFile()&&ZS(l.name)){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=Cj(B(t,s));if(n.isExcluded(e))continue}try{let e=await vu(s,`utf-8`);vU.set(s,nU(e));let n=pU(s,t),i=_U(s);if(i){let e=rC(n,i);if(e.shadowed&&(JH.warn({docName:n,effective:e.effective,shadowed:e.shadowed},`docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`markdown`,...XH(e,n)})}catch(e){let t=Vs(e);t===`EACCES`?JH.warn({path:s,code:t},`Permission denied reading ${s}, file excluded from index`):t!==`ENOENT`&&JH.warn({path:s,err:e},`Failed to seed hash for ${s}`)}}else if(u.isFile()){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=Cj(B(t,s));if(n.isPathIgnored(e))continue}let e=pU(s,t);if(lC(e)||uC(e))continue;r.set(e,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`file`})}}}catch(t){Vs(t)!==`ENOENT`&&JH.warn({dir:e,err:t},`Failed to read directory ${e}`)}}function wU(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let n=e.relativePath;if(lC(n)||uC(n))return;if(e.kind===`file-delete`){let e=t.get(n);e&&e.kind===`file`&&t.delete(n);return}let r=t.get(n);if(r&&r.kind===`markdown`)return;t.set(n,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:e.inode||r?.inode||0,aliases:r?.aliases??[],kind:`file`});return}if(!mC(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=_U(e.path);i&&rC(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[],kind:`markdown`,...XH(e.content,n)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),cC(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),cC(e.oldDocName);let r=_U(e.newPath);r&&rC(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[],kind:`markdown`,...XH(e.content,e.newDocName)});break}default:YH(e)}}}function TU(e,t,n,r){let i=[],a=[];for(let o of e){let e=mU(t,o.path);if(!e)continue;if(o.type===`delete`){gU(r,e)&&i.push({kind:`folder-delete`,path:o.path,relativePath:e});continue}let s;try{s=ql(o.path)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:o.path,code:t},`folder lstat failed for ${o.path} (${t})`);continue}let c=null,l=o.path;if(s.isDirectory())c=s;else if(s.isSymbolicLink())try{if(l=W(o.path),!Ej(l,t))continue;let e=iu(l);e.isDirectory()&&(c=e)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:o.path,code:t},`folder symlink resolve failed for ${o.path} (${t})`),c=null}if(!c||n?.isDirExcluded(e))continue;let u=r.has(e);hU(r,t,o.path,c,l),u||(i.push({kind:`folder-create`,path:o.path,relativePath:e}),EU(l,t,n,r,i,a))}return{events:i,untrackedFiles:a}}function EU(e,t,n,r,i,a){let o=[e];for(;o.length>0;){let e=o.shift();if(e===void 0)continue;let s;try{s=$l(e,{withFileTypes:!0})}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({dir:e,code:n},`folder rescan readdir failed for ${e} (${n})`);continue}for(let c of s){if(c.isFile()){a.push(z(e,c.name));continue}if(!c.isDirectory())continue;let s=z(e,c.name),l=mU(t,s);if(!l||n?.isDirExcluded(l))continue;let u;try{u=ql(s)}catch(e){let t=Vs(e);t!==`ENOENT`&&JH.warn({path:s,code:t},`folder rescan lstat failed for ${s} (${t})`);continue}u.isDirectory()&&(r.has(l)||(hU(r,t,s,u),i.push({kind:`folder-create`,path:s,relativePath:l})),o.push(s))}}}async function DU(e,t,n,r,i,a,o){let s=e.filter(e=>fU(e.path,t)?(cU(`drop-symlink-escape`,e.type,e.path),JH.warn({path:e.path,type:e.type},`Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:c,untrackedFiles:l}=TU(s,t,n,i),d=[];if(l.length>0){let e=new Set(s.map(e=>e.path)),n=new Set;for(let e of r.values())n.add(e.canonicalPath);d=l.filter(t=>!e.has(t)&&!vU.has(t)&&!n.has(t)).filter(e=>fU(e,t)?(cU(`drop-symlink-escape`,`create`,e),!1):!0).map(e=>({type:`create`,path:e})),d.length>0&&JH.debug({count:d.length,paths:d.map(e=>Cj(B(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let f=d.length>0?s.concat(d):s,p=f.filter(e=>ZS(e.path)),m=f.filter(e=>QS(e.path,u)),h=f.filter(e=>!ZS(e.path));if(p.length===0&&m.length===0&&c.length===0&&h.length===0)return;let g=p.length>0?await xU(p,t,n,o):[];for(let e of g){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=nU(e.content),r=e.path;try{r=W(e.path)}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({path:e.path,code:n},`realpathSync failed for self-write check on ${e.path} (${n})`)}t=SU(r,n)}else if(e.kind===`rename`){let n=nU(e.content),r=e.newPath;try{r=W(e.newPath)}catch(t){let n=Vs(t);n!==`ENOENT`&&JH.warn({path:e.newPath,code:n},`realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=SU(r,n)}if(wU(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(R(e.docName));break;case`delete`:n.decrementMdDir(R(e.docName));break;case`rename`:n.decrementMdDir(R(e.oldDocName)),n.incrementMdDir(R(e.newDocName));break;case`update`:case`conflict`:break;default:YH(e)}if(t){JH.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!0}),cU(`self-write-skip`,e.kind,e.kind===`rename`?e.newPath:e.path);continue}JH.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!1});let i=e.kind===`rename`?e.newPath:e.path;cU(`dispatched`,e.kind,i),await zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":$o(i),"disk.path.role":is(i)}},async()=>a(e))}for(let e of c)JH.debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),kU().add(1,{"disk.kind":e.kind,self:!1}),cU(`dispatched`,e.kind,e.path),await zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":$o(e.path),"disk.path.role":is(e.path)}},async()=>a(e));for(let e of m){if(n){let r=Cj(B(t,e.path));if(n.isExcluded(r)){cU(`drop-filter-excluded`,e.type,e.path);continue}}let r=Cj(B(t,e.path)),i=e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r};cU(`dispatched`,i.kind,e.path),await a(i)}for(let e of h){let i=Cj(B(t,e.path));if(n?.isPathIgnored(i)){cU(`drop-filter-excluded`,e.type,e.path);continue}if(lC(i)||uC(i)){cU(`drop-reserved-doc`,e.type,e.path);continue}if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:i};wU(t,r),cU(`dispatched`,t.kind,e.path),await a(t);continue}let o;try{o=ql(e.path),o.isSymbolicLink()&&(o=iu(e.path))}catch(t){let n=Vs(t);cU(`drop-stat-failed`,e.type,e.path),n!==`ENOENT`&&JH.warn({path:e.path,code:n},`file-event lstat failed for ${e.path} (${n})`);continue}if(!o.isFile())continue;let s=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)}:{kind:`file-update`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)};wU(s,r),cU(`dispatched`,s.kind,e.path),await a(s)}}let OU=null;function kU(){return OU||=ls().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),OU}let AU=null;function jU(){return AU||=ls().createCounter(`ok.file_watcher.drops`,{description:`File-watcher events dropped before dispatch, by bounded reason`}),AU}async function MU(e,t,n,r,i,a,o,s){let c;try{c=await import(`@parcel/watcher`)}catch(e){return JH.debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let l=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await c.subscribe(e,async(c,l)=>{if(c){JH.error({err:c},`parcel watcher callback error`);return}try{s?.(l.map(e=>e.path)),await DU(l.map(e=>({type:e.type,path:e.path})),e,t,n,r,i,a),o()}catch(e){JH.error({err:e},`parcel batch error`)}},l)}catch(e){return JH.warn({err:e},`@parcel/watcher subscribe failed, falling back to chokidar`),null}}function NU(e,t,n,r){let i=Cj(B(e,n));if(i===``||i===`.`)return!1;let a;if(r)a=r.isDirectory();else try{a=ql(n).isDirectory()}catch{return!1}if(a){let n=/^(\.[A-Za-z0-9_-]+)(\/skills(\/[^/]+)?)?$/.exec(i);return n&&n[1]!==`.ok`&&(n[2]!==void 0||H(z(e,i,`skills`)))?!1:t.isDirExcluded(i)}return t.isExcluded(i)}async function PU(e,t,n,r,i,a,o,s){let{watch:c}=await import(`./chokidar-CVNrjmRM.mjs`),l=c(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(n,r)=>NU(e,t,n,r):void 0});l.on(`error`,e=>JH.error({err:e},`chokidar error`));let u=[],d=null;function f(c,l){u.push({type:c,path:l}),d||=setTimeout(()=>{let c=u;u=[],d=null,s?.(c.map(e=>e.path)),DU(c,e,t,n,r,i,a).then(o).catch(e=>JH.error({err:e},`chokidar batch error`))},50)}return l.on(`add`,e=>f(`create`,e)),l.on(`change`,e=>f(`update`,e)),l.on(`unlink`,e=>f(`delete`,e)),l.on(`addDir`,e=>f(`create`,e)),l.on(`unlinkDir`,e=>f(`delete`,e)),await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};l.once(`ready`,n),setTimeout(n,1e4).unref()}),{unsubscribe:()=>(d&&(clearTimeout(d),d=null,u=[]),l.close())}}async function FU(e,t,n,r={}){let{onRawBatch:i}=r,a;try{a=W(e)}catch{a=e}let o=new Map,s=new Map,c=new Map,l=new Map,u=0,d=null,f=-1,p=()=>{u++};await CU(a,a,n,o,s,c,l),p();let m=setInterval(tU,$H),h=setInterval(uU,6e4),g,_,v=process.env.OK_FILE_WATCHER_BACKEND===`chokidar`;try{let e=v||r.forceBackend===`chokidar`?null:await MU(a,n,o,s,t,c,p,i);if(e)g=e,_=`parcel`;else{if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable (forced backend)`);g=await PU(a,n,o,s,t,c,p,i),_=`chokidar`}}catch(e){throw clearInterval(m),clearInterval(h),e}let y=g.unsubscribe.bind(g);return JH.info({contentDir:a,backend:_},`watching for external .md changes`),{async unsubscribe(){return clearInterval(m),clearInterval(h),QH.clear(),vU.clear(),dU(),y()},getFileIndex(){return d&&f===u?d:(d=ZH(o),f=u,d)},getAllFilesIndex(){return o},getFileIndexGeneration(){return u},getFolderIndex(){return s},getAliasMap(){return c},getFolderAliasIndex(){return l},mutateFileIndex(e){wU(e,o),p()},pruneFileIndexNowExcluded(){if(!n)return 0;let e=0;for(let[t,r]of o){let i=Cj(B(a,r.canonicalPath));(r.kind===`file`?n.isPathIgnored(i):n.isExcluded(i))&&(o.delete(t),e++)}return e>0&&p(),e},pruneFolderIndexNowExcluded(){if(!n)return 0;let e=0;for(let t of s.keys())n.isDirExcluded(t)&&(s.delete(t),e++);return e},async rescanFromDisk(){await CU(a,a,n,o,s,c,l),p()}}}async function IU(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),n=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:n}}function LU(e){try{return iu(V(e,xe)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function RU(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=LU(t)}catch{e=!1}if(e)return{rootPath:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}async function zU(e,t){let{git:n}=ws(e),[r,i]=await Promise.allSettled([$re(n),nS(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function BU(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function VU(e,t,n,r){let{git:i}=ws(e);await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``?!0:i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=zU(e,t).catch(e=>(UU(e)||L(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${AR(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const HU=`git-branch-info`;function UU(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const WU=L(`git-checkout`),GU=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function KU(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(GU);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=W(n)}catch{r=n}return{held:!0,path:r}}const qU=`git-checkout`,JU=Ar;async function YU(e,t,n){if(n?.fastForward&&await XU(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r}=ws(e),i=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!i)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:JU(e)?`branch-not-found`:`fetch-failed`}}let a=await zU(e,i?t:`origin/${t}`);if(a.conflicts)return{ok:!1,reason:`dirty-conflict`,files:a.files};try{return await r.raw([`checkout`,t]),{ok:!0}}catch(e){let n=KU(e);return n.held?(WU.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(WU.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${AR(e)}`),{ok:!1,reason:`checkout-failed`})}}async function XU(e,t){let{git:n}=ws(e,{timeoutMs:15e3}),r=e=>n.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await n.raw([`fetch`,`origin`,t])}catch(e){return WU.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${AR(e)}`),`unavailable`}let i=await r(`refs/remotes/origin/${t}`);if(!i)return`unavailable`;let a=await r(`refs/heads/${t}`);if(!a||a===i)return`up-to-date`;let o=await n.raw([`merge-base`,a,i]).then(e=>e.trim()).catch(()=>``);if(o===a){try{await n.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return WU.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${AR(e)}`),`unavailable`}return await r(`refs/heads/${t}`)===i?`advanced`:`unavailable`}return o===i?`up-to-date`:`diverged`}const ZU=(e,t)=>{let n=Dl(`git`,[`config`,`--get`,t],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));return n.status!==0||!n.stdout?null:n.stdout.trim()||null};function QU(e){let t=Dl(`git`,[`rev-parse`,`--git-dir`],zF({cwd:e,encoding:`utf-8`,timeout:5e3})),n=Dl(`git`,[`rev-parse`,`--git-common-dir`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||n.status!==0?!1:V(e,t.stdout.trim())!==V(e,n.stdout.trim())}function $U(e){let t=Dl(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let n=Dl(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(n.status!==0){let e=n.stderr?.trim()??``,t=n.error?` [${n.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function eW(e,t,n,r=ZU){let i=r(e,`user.name`),a=r(e,`user.email`);if(i&&a)return{name:i,email:a};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function tW(e,t,n){let r=`--local`;QU(e)&&($U(e),r=`--worktree`);let i=(t,n)=>{let i=Dl(`git`,[`config`,r,t,n],zF({cwd:e,encoding:`utf-8`,timeout:5e3}));if(i.status!==0){let e=i.stderr?.trim()??``,n=i.error?` [${i.error.message}]`:``;throw Error(`git config ${r} ${t} failed: ${e}${n}`)}};i(`user.name`,t),i(`user.email`,n)}function nW(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof Oa||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;q(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}function rW(e,t){let n=Object.keys(e).join(`, `);return async(r,i)=>{let a=r.method===void 0?void 0:e[r.method];if(a){await a(r,i);return}q(i,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:t.handler,extraHeaders:{Allow:n}})}}const iW=`config.yml`;function aW(e,t){let n;try{n=ql(e)}catch(e){if(e.code===`ENOENT`)return;throw e}if(n.isSymbolicLink())throw Error(`Refusing to follow symlink at ${t} (${e}). An untrusted upstream may have committed this symlink to redirect writes outside the project. Remove the symlink and re-run.`)}function oW(e){let[t=`0`,n=`0`]=e.split(`.`);return`${t.length>0?t:`0`}.${n.length>0?n:`0`}`}function sW(e){return/^[A-Za-z0-9._\-/]+$/.test(e)?e:JSON.stringify(e)}function cW(e,t){let n=`# yaml-language-server: $schema=https://unpkg.com/@inkeep/open-knowledge@latest/dist/schemas/${pe}/config.project.schema.json
98
98
  # OpenKnowledge — project configuration
99
99
  #
100
100
  # This file overrides built-in defaults for this project. Every key below
@@ -1240,7 +1240,7 @@ tags: [lore, history]
1240
1240
  `),m={brokenLinks:d};return c&&(m.summary=c),u&&(m.warnings=u),wN(p,bN(o,s?K2(o,i):void 0,m))}function vme(e,t,n){let r=aN(e,`${t.replace(/\/+$/,``)}/.ok/templates/${n}.md`);return r.ok?{ok:!0,abs:r.abs}:{ok:!1}}function yme(e){let t=Sr(e).trim();if(t===``)return{title:``};let n=(0,ej.parse)(t);if(typeof n!=`object`||!n||Array.isArray(n))return{title:``};let r=n;return{title:typeof r.title==`string`?r.title:``,...typeof r.description==`string`?{description:r.description}:{},...Array.isArray(r.tags)?{tags:r.tags.map(e=>String(e))}:{}}}async function bme(e,t,n,r,i){let a=T4(e,`template`);if(a)return X(`Error: ${a}`,!0);let o=r4(e.path);if(!o.ok)return X(`Error: ${o.error}`,!0);let{folder:s,name:c}=o;if(!r)return X(TN,!0);let l=vme(n,s,c);if(!l.ok||!H(l.abs))return X(`Error: template "${c}" not found in ${s||`(root)`}. Create it with \`write({ template })\` first.`,!0);let u;try{u=U(l.abs,`utf-8`)}catch(e){return X(`Error: could not read template: ${e.message}`,!0)}let{frontmatter:d,body:f}=bi(u),p=yme(d);if(e.frontmatter!==void 0){let n=await RN(r,`/api/template`,{folder:s,name:c,body:f,frontmatter:MP(p,e.frontmatter),...t===void 0?{}:{summary:t},...oN(i.identityRef?.current)});if(!n.ok)return X(`Error: ${n.error}`,!0);let a=typeof n.path==`string`?n.path:void 0;return wN(`Patched template "${c}" frontmatter${a?` (${a})`:``}.`,{template:{ok:!0,path:a}})}let m=e.occurrence??1,h=E4(f,e.find,m);if(h===-1)return X(`Error: \`find\` occurs fewer than ${m} time(s) in template "${c}".`,!0);let g=await RN(r,`/api/template`,{folder:s,name:c,body:f.slice(0,h)+e.replace+f.slice(h+e.find.length),frontmatter:p,...t===void 0?{}:{summary:t},...oN(i.identityRef?.current)});if(!g.ok)return X(`Error: ${g.error}`,!0);let _=typeof g.path==`string`?g.path:void 0;return wN(`Edited template "${c}"${_?` (${_})`:``}.`,{template:{ok:!0,path:_}})}async function xme(e,t,n,r){let i=s4(e.name);if(!i.ok)return X(`Error: ${i.error}`,!0);let a=c4(e.file);if(!a.ok)return X(`Error: ${a.error}`,!0);if(e.description!==void 0)return X("Error: `description` edits SKILL.md, not a bundle file. Drop `file`, or edit the file body with find+replace.",!0);if(e.find===void 0||e.replace===void 0)return X("Error: a bundle-file edit needs `find` + `replace`: { skill: { name, file, find, replace } }.",!0);if(!t)return X(TN,!0);let o=e.scope??`project`,s=await m4(t,o,e.name,a.path);if(!s.ok)return X(`Error: skill file "${a.path}" not found in skill "${e.name}" (${o} scope). Create it with \`write({ skill: { name, files: [...] } })\` first.`,!0);let c=e.occurrence??1,l=E4(s.text,e.find,c);if(l===-1)return X(`Error: \`find\` occurs fewer than ${c} time(s) in skill file "${a.path}".`,!0);let u=s.text.slice(0,l)+e.replace+s.text.slice(l+e.find.length);return p4(t,{name:e.name,scope:o,path:a.path,content:u,summary:n,identity:r})}async function Sme(e,t,n,r,i){let a=s4(e.name);if(!a.ok)return X(`Error: ${a.error}`,!0);if(e.file!==void 0)return xme(e,n,t,r.identityRef?.current);let o=e.find!==void 0||e.replace!==void 0,s=e.description!==void 0;if(e.find!==void 0&&e.replace===void 0)return X("Error: `find` needs a `replace`. Body edit: { skill: { name, find, replace } }.",!0);if(e.replace!==void 0&&e.find===void 0)return X("Error: `replace` needs a `find`. Body edit: { skill: { name, find, replace } }.",!0);if(o&&s)return X("Error: Pick ONE: edit the body (find+replace) OR the `description`, not both in one call.",!0);if(!o&&!s)return X("Error: Provide either a body edit (find+replace) or a `description` for { skill }.",!0);if(!n)return X(TN,!0);let c=e.scope??`project`,l=await f4(n,c,e.name);if(!l.ok)return X(`Error: skill "${e.name}" not found in ${c} scope. Create it with \`write({ skill })\` first.`,!0);let u=l.body,d=l.description;if(s)d=e.description;else{let t=e.occurrence??1,n=E4(l.body,e.find,t);if(n===-1)return X(`Error: \`find\` occurs fewer than ${t} time(s) in skill "${e.name}".`,!0);u=l.body.slice(0,n)+e.replace+l.body.slice(n+e.find.length)}return d4(n,{scope:c,name:e.name,description:d,body:u,summary:t,identity:r.identityRef?.current,lockDir:i})}async function Cme(e,t,n,r){if(!n)return X(TN,!0);let i=await RN(n,`/api/folder-config`,{path:e.path,frontmatter:e.frontmatter,...t===void 0?{}:{summary:t},...oN(r.identityRef?.current)});if(!i.ok)return X(`Error: ${i.error}`,!0);let a=(Array.isArray(i.applied)?i.applied:[])[0]??{},o=a.action??`written`;return wN(`${o===`deleted`?`Cleared`:o===`noop`?`No change to`:`Updated`} folder properties for ${e.path}.`,{folder:{ok:!0,path:a.path??`${e.path}/.ok/frontmatter.yml`,action:o}})}function wme(e,t){let n={find:F().optional().describe("Exact BODY text to find. Use WITH `replace`. For metadata, use `frontmatter` instead — not this."),replace:F().optional().describe("Replacement for the `find` match."),occurrence:N().int().positive().optional().describe(`Which match to edit (1 = first). Default: first.`)};e.registerTool(`edit`,{description:mme,inputSchema:{document:M({path:F().describe(`Document path, no extension — the slashes are its folder. Example: "meetings/standup".`),...n,frontmatter:e4.optional().describe("Metadata merge-patch (set keys; `null` deletes a key). Use INSTEAD of find/replace.")}).optional().describe(`Edit a DOCUMENT: its body (find+replace) OR its frontmatter (patch). Body: { document: { path, find, replace } }. Metadata: { document: { path, frontmatter } }.`),folder:M({path:F().describe(`Folder path.`),frontmatter:e4.describe("Update the folder's own title/description/tags (merge-patch; `null` deletes).")}).optional().describe(`Edit a FOLDER: only its frontmatter (folders have no body). Example: { folder: { path: "meetings", frontmatter: { description: "All-hands" } } }`),template:M({path:F().describe(n4),...n,frontmatter:e4.optional().describe(`Template metadata merge-patch.`)}).optional().describe(`Edit a TEMPLATE: body (find+replace) or frontmatter (patch).`),skill:M({name:F().describe(i4),file:F().optional().describe('A single SKILL-RELATIVE bundle file path (e.g. "references/tiers.md"). For `edit`, names the one bundle file to find/replace in; for `skills`, the one file to read.'),...n,description:F().optional().describe(a4),scope:o4.optional()}).optional().describe("Edit a SKILL: SKILL.md body (find+replace) OR its `description`; or pass `file` to find/replace inside ONE bundle file."),summary:cN,cwd:F().optional().describe(sN)},outputSchema:CN({document:M(yN).optional().describe("Document edit result. Always present on a successful document edit (body or frontmatter) — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`warnings`. Absent only for folder/template edits."),folder:M({ok:D(),path:F(),action:F().describe("`written` (created/updated) | `deleted` (cleared) | `noop`.")}).optional().describe(`Folder frontmatter edit result.`),template:M({ok:D(),path:F()}).optional().describe(`Template edit result.`),skill:M({ok:D(),path:F().optional(),created:D().optional().describe(`Always false for an edit (the skill already existed).`),file:M({path:F(),kind:F().optional(),created:D().optional()}).optional().describe(`Present for a bundle-file edit: the file edited.`)}).optional().describe(`Skill edit result (SKILL.md or a bundle file).`),previewUrl:dN.optional(),previewUrlSource:fN,warning:gN})},async e=>{let n=await AN(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return X(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=eN(i,r),s=i.appearance.preview.autoOpen,c=l4(e,[`document`,`folder`,`template`,`skill`]);if(c)return X(`Error: ${c}`,!0);if(e.document!==void 0){let n=T4(e.document,`document`);return n?X(`Error: ${n}`,!0):a?e.document.frontmatter===void 0?gme(e.document,e,r,o,a,t,s):_me({path:e.document.path,frontmatter:e.document.frontmatter},e,r,o,a,t,s):X(TN,!0)}return e.folder===void 0?e.skill===void 0?bme(e.template,e.summary,r,a,t):Sme(e.skill,e.summary,a,t,nN(r)):Cme(e.folder,e.summary,a,t)})}const Tme=new Set([`cat`,`ls`,`grep`,`find`]),Eme=/\b[\w./-]+\.(md|mdx)\b/g;function O4(e){return/\.(md|mdx)$/.test(e)}function k4(e){let t=e.trim();return t?(t=t.replace(/\/+/g,`/`),t.startsWith(`./`)&&(t=t.slice(2)),t.endsWith(`/`)&&(t=t.slice(0,-1)),t):``}function A4(e){return e.args.slice(1)}function j4(e){return e.filter(e=>!e.startsWith(`-`))}function Dme(e){return j4(A4(e)).filter(O4)}function Ome(e,t){let n=j4(A4(t)),r=n.length>0?n[n.length-1]:``,i=r&&r!==`.`?k4(r):``,a=[];i&&a.push(i);for(let t of e.split(`
1241
1241
  `)){let e=t.trim();if(!e||/\.[a-z0-9]+$/i.test(e)&&!O4(e))continue;let n=i?`${i}/${e}`:e;a.push(n)}return a}function kme(e){let t=[];for(let n of e.split(`
1242
1242
  `)){if(!n)continue;let e=n.indexOf(`:`);if(e<0)continue;let r=k4(n.slice(0,e));O4(r)&&t.push(r)}return t}function Ame(e){let t=[];for(let n of e.split(`
1243
- `)){let e=k4(n);e&&O4(e)&&t.push(e)}return t}function jme(e){return j4(A4(e)).filter(O4)}function Mme(e){return j4(A4(e)).length>0}function M4(e){let t=[],n=e.matchAll(Eme);for(let e of n)t.push(k4(e[0]));return t}function Nme(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(Tme.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&Mme(r)){n=r;break}}let r;if(!n)r=M4(e);else{switch(n.command){case`cat`:r=Dme(n);break;case`ls`:r=Ome(e,n);break;case`grep`:r=kme(e);break;case`find`:r=Ame(e);break;case`head`:case`tail`:r=jme(n);break;default:r=M4(e)}r.length===0&&(r=M4(e))}let i=new Set,a=[];for(let e of r){let t=k4(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var N4=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-B8YWvx1Q.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-C3vpYzfr.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-DyVBy6Mg.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-DQIF-HgH.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BnpJKc8r.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-C9jARGFn.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-CJL2LWzm.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-vsz0Vtsc.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-sYSLIPgW.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-CFyBiApv.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-DErk_Yl0.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-BzT6KWst.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-Pga3crue.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-D9QYkCU0.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-BkVS3Xmr.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-Bu45hbfn.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-8TWuJ_OV.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-BzZhqUU7.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-BHpyAWOj.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-BHpyAWOj.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-BHpyAWOj.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-BMfKONjk.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-YSD3Wwpz.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-C0jQbtG6.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-urKKiOkB.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-Jq_1JF4a.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-C4Rjg6X-.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-Bh_filgx.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-CnLMuz8G.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-BMEHkLkI.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-BGL4FR9H.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-CgnuF_hC.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CkAvzOUr.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-CMN49iyc.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-Cz9o379Y.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-BYF-zQB5.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-Dl-r5t6o.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-B1OOeDAs.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-O6S65p4r.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-D5VPiyFZ.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-D4DqPp7j.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-Dq2O0Dr6.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-DNEfkSJA.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-B9nDoMUt.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-D_erNUzD.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-Cor7cJ6o.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-Cor7cJ6o.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-BvhaFG9J.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-BvhaFG9J.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-ChaCzoJD.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-CfQ6WD0x.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-BrTi18ZN.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-BrTi18ZN.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-DiniSeCm.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-BWspyNyq.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-BWspyNyq.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-DTUwGGgl.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-E_RwmVUf.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-DhZaF2MX.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-ByX6dFhf.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-DNxq1g-4.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-BJzTDNVp.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-DTXF6o9u.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-hcgHczjD.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-VEQOsPiP.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-BElHH82h.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-KpqF3VUr.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-BI7zTPJ3.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-CsAmedJu.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-DRmuleyA.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-Cnq4Pk95.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-C0nS7069.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-ByjKkvjF.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-TD2KmZjb.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-BRFeF7SV.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-BTJQNl6y.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kgzROhmg.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-kgzROhmg.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-kgzROhmg.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(N4.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-B2cyr2d4.mjs`)).tarCommand}),N4.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-q34fmnbQ.mjs`)).yqCommand}),N4.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-CsuyuKIz.mjs`)).xanCommand}),N4.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-DV5JBdcO.mjs`)).sqlite3Command}));var P4=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(P4.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-BPxhh_Jp.mjs`)).python3Command}),P4.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-BPxhh_Jp.mjs`)).pythonCommand}));var F4=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(F4.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-BJsjY3Aj.mjs`)).jsExecCommand}),F4.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-BJsjY3Aj.mjs`)).nodeStubCommand}));var Pme=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-DtUGPJbr.mjs`)).curlCommand}],I4=new Map;function L4(e){return{name:e.name,async execute(t,n){let r=I4.get(e.name);if(r||(r=await fl.runTrustedAsync(()=>e.load()),I4.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-6JEX67RU-C21BAvUp.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function Fme(e){return(e?N4.filter(t=>e.includes(t.name)):N4).map(L4)}function Ime(){return Pme.map(L4)}function Lme(){return P4.map(L4)}function Rme(){return F4.map(L4)}function zme(e){return`load`in e&&typeof e.load==`function`}function Bme(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var R4=new TextEncoder;function Vme(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var z4=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):Vme(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=$c(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){rl(e,`write`);let i=Qc(e);this.ensureParentDirs(i);let a=sl(t,ol(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){rl(e,`write`);let r=Qc(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?R4.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return cl(await this.readFileBuffer(e),ol(t))}async readFileBuffer(e){rl(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:R4.encode(e.content)}return n.content instanceof Uint8Array?n.content:R4.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){rl(e,`append`);let r=Qc(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=sl(t,ol(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:R4.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){rl(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:R4.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){rl(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:R4.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=Qc(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=al(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=Qc(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=al(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){rl(e,`mkdir`);let n=Qc(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=$c(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){rl(e,`scandir`);let t=Qc(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=al(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}async rm(e,t){rl(e,`rm`);let n=Qc(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=Xc(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){rl(e,`cp`),rl(t,`cp`);let r=Qc(e),i=Qc(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=Xc(r,e),a=Xc(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return Zc(e,t)}async chmod(e,t){rl(e,`chmod`);let n=Qc(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){rl(t,`symlink`);let n=Qc(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){rl(e,`link`),rl(t,`link`);let n=Qc(e),r=Qc(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){rl(e,`readlink`);let t=Qc(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){rl(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){rl(e,`utimes`);let r=Qc(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function Hme(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function Ume(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function Wme(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function Gme(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${Cc}
1243
+ `)){let e=k4(n);e&&O4(e)&&t.push(e)}return t}function jme(e){return j4(A4(e)).filter(O4)}function Mme(e){return j4(A4(e)).length>0}function M4(e){let t=[],n=e.matchAll(Eme);for(let e of n)t.push(k4(e[0]));return t}function Nme(e,t){let n=null;for(let e=t.length-1;e>=0;e--){let r=t[e];if(Tme.has(r.command)){n=r;break}if((r.command===`head`||r.command===`tail`)&&Mme(r)){n=r;break}}let r;if(!n)r=M4(e);else{switch(n.command){case`cat`:r=Dme(n);break;case`ls`:r=Ome(e,n);break;case`grep`:r=kme(e);break;case`find`:r=Ame(e);break;case`head`:case`tail`:r=jme(n);break;default:r=M4(e)}r.length===0&&(r=M4(e))}let i=new Set,a=[];for(let e of r){let t=k4(e);!t||i.has(t)||(i.add(t),a.push(t))}return a}var N4=[{name:`echo`,load:async()=>(await import(`./echo-O45JWWI2-BacOdfFs.mjs`)).echoCommand},{name:`cat`,load:async()=>(await import(`./cat-RDUMLXKC-BtNo16C3.mjs`)).catCommand},{name:`printf`,load:async()=>(await import(`./printf-CX64KX2P-CKuJk-Cs.mjs`)).printfCommand},{name:`ls`,load:async()=>(await import(`./ls-KSXFZCWH-BEv3e7-2.mjs`)).lsCommand},{name:`mkdir`,load:async()=>(await import(`./mkdir-TDEMSB6C-BY7IIkok.mjs`)).mkdirCommand},{name:`rmdir`,load:async()=>(await import(`./rmdir-XTQXT7RK-Dk19R-p8.mjs`)).rmdirCommand},{name:`touch`,load:async()=>(await import(`./touch-DX2IJOQ4-CZteiICw.mjs`)).touchCommand},{name:`rm`,load:async()=>(await import(`./rm-RTZG23RL-BOvMrhon.mjs`)).rmCommand},{name:`cp`,load:async()=>(await import(`./cp-XOYR4ABJ-D0LUaMQT.mjs`)).cpCommand},{name:`mv`,load:async()=>(await import(`./mv-Z6MORUFL-C4m2WG8E.mjs`)).mvCommand},{name:`ln`,load:async()=>(await import(`./ln-4TRFBYAT-Dhr3hBr6.mjs`)).lnCommand},{name:`chmod`,load:async()=>(await import(`./chmod-SYMGL4JA-B15Xlp42.mjs`)).chmodCommand},{name:`pwd`,load:async()=>(await import(`./pwd-D4OZ7N27-CSTLotxZ.mjs`)).pwdCommand},{name:`readlink`,load:async()=>(await import(`./readlink-MI4GCHJF-V9fwXBrg.mjs`)).readlinkCommand},{name:`head`,load:async()=>(await import(`./head-HT2B6D2J-DSBJixLD.mjs`)).headCommand},{name:`tail`,load:async()=>(await import(`./tail-S5ULNTJU-CWnyTuXg.mjs`)).tailCommand},{name:`wc`,load:async()=>(await import(`./wc-TQB3VNOX-D8llmcL9.mjs`)).wcCommand},{name:`stat`,load:async()=>(await import(`./stat-BT5A227F-B4qwqNn_.mjs`)).statCommand},{name:`grep`,load:async()=>(await import(`./grep-2HUTXO5U-CsEE08ya.mjs`)).grepCommand},{name:`fgrep`,load:async()=>(await import(`./grep-2HUTXO5U-CsEE08ya.mjs`)).fgrepCommand},{name:`egrep`,load:async()=>(await import(`./grep-2HUTXO5U-CsEE08ya.mjs`)).egrepCommand},{name:`rg`,load:async()=>(await import(`./rg-XNF3R3II-CuFYIwNn.mjs`)).rgCommand},{name:`sed`,load:async()=>(await import(`./sed-JAPPVBEU-BUaK4riL.mjs`)).sedCommand},{name:`awk`,load:async()=>(await import(`./awk2-BBAGSFUB-BH8WxyhW.mjs`)).awkCommand2},{name:`sort`,load:async()=>(await import(`./sort-DCNRDA7U-C1gRzOOY.mjs`)).sortCommand},{name:`uniq`,load:async()=>(await import(`./uniq-SUNANL47-DpupkNiO.mjs`)).uniqCommand},{name:`comm`,load:async()=>(await import(`./comm-5SLSESQG-aGB098lH.mjs`)).commCommand},{name:`cut`,load:async()=>(await import(`./cut-OPC3VAGB-FXZX1WQM.mjs`)).cutCommand},{name:`paste`,load:async()=>(await import(`./paste-7N6AFSDS-DQNANxpk.mjs`)).pasteCommand},{name:`tr`,load:async()=>(await import(`./tr-2HXZRDSW-D4XuTGWg.mjs`)).trCommand},{name:`rev`,load:async()=>(await import(`./rev-XOSYPP45-G2PvMYC2.mjs`)).rev},{name:`nl`,load:async()=>(await import(`./nl-U5YJDM32-CrNZhLtI.mjs`)).nl},{name:`fold`,load:async()=>(await import(`./fold-LDSORVYE-CDU-6eOS.mjs`)).fold},{name:`expand`,load:async()=>(await import(`./expand-DTNXU4LQ-BD32VJaK.mjs`)).expand},{name:`unexpand`,load:async()=>(await import(`./unexpand-RGTMIGZM-x3XCmR3I.mjs`)).unexpand},{name:`strings`,load:async()=>(await import(`./strings-7PLOGTPD-BJ6vWsQi.mjs`)).strings},{name:`split`,load:async()=>(await import(`./split-SITCSYCZ-D4U2N_sH.mjs`)).split},{name:`column`,load:async()=>(await import(`./column-WLPMMSTS-BrY1gQI1.mjs`)).column},{name:`join`,load:async()=>(await import(`./join-GG2LDHE5-kABASDPB.mjs`)).join},{name:`tee`,load:async()=>(await import(`./tee-O7VXZDCO-B_duU1hV.mjs`)).teeCommand},{name:`find`,load:async()=>(await import(`./find-DH2ALKQS-z-G7VPmU.mjs`)).findCommand},{name:`basename`,load:async()=>(await import(`./basename-AA2KJYZQ-sv8gJZXS.mjs`)).basenameCommand},{name:`dirname`,load:async()=>(await import(`./dirname-LEMTZZFS-RRQ5Ar_Z.mjs`)).dirnameCommand},{name:`tree`,load:async()=>(await import(`./tree-LYXBS7DC-CUIzQKTG.mjs`)).treeCommand},{name:`du`,load:async()=>(await import(`./du-WO2ENHXQ-Cg71FvLi.mjs`)).duCommand},{name:`env`,load:async()=>(await import(`./env-5EPCWSXR-T8XCKOX_.mjs`)).envCommand},{name:`printenv`,load:async()=>(await import(`./env-5EPCWSXR-T8XCKOX_.mjs`)).printenvCommand},{name:`alias`,load:async()=>(await import(`./alias-JE7RI5QX-BfILuEvo.mjs`)).aliasCommand},{name:`unalias`,load:async()=>(await import(`./alias-JE7RI5QX-BfILuEvo.mjs`)).unaliasCommand},{name:`history`,load:async()=>(await import(`./history-J4QRNGRO-CULSDkzp.mjs`)).historyCommand},{name:`xargs`,load:async()=>(await import(`./xargs-I6EZUCYF-Bu8VhXV_.mjs`)).xargsCommand},{name:`true`,load:async()=>(await import(`./true-WHJNXCHG-BzxCUQFd.mjs`)).trueCommand},{name:`false`,load:async()=>(await import(`./true-WHJNXCHG-BzxCUQFd.mjs`)).falseCommand},{name:`clear`,load:async()=>(await import(`./clear-5CZ5X4YR-BNXs_KRD.mjs`)).clearCommand},{name:`bash`,load:async()=>(await import(`./bash-IJWYRKFO-DKUaUgF9.mjs`)).bashCommand},{name:`sh`,load:async()=>(await import(`./bash-IJWYRKFO-DKUaUgF9.mjs`)).shCommand},{name:`jq`,load:async()=>(await import(`./jq-LYZFFBZB-CIwp4u6h.mjs`)).jqCommand},{name:`base64`,load:async()=>(await import(`./base64-4YMZCVJ5-CDuRvFBG.mjs`)).base64Command},{name:`diff`,load:async()=>(await import(`./diff-HJF2MPDN-bcOaHvDo.mjs`)).diffCommand},{name:`date`,load:async()=>(await import(`./date-DD7FVA2V-7hk1aW9g.mjs`)).dateCommand},{name:`sleep`,load:async()=>(await import(`./sleep-VZFPZFWA-DcISab6N.mjs`)).sleepCommand},{name:`timeout`,load:async()=>(await import(`./timeout-VRKMCG72-DaJVXXR3.mjs`)).timeoutCommand},{name:`time`,load:async()=>(await import(`./time-DEUO3QV2-CekCKA2I.mjs`)).timeCommand},{name:`seq`,load:async()=>(await import(`./seq-RN5ZUASB-D5aLn_so.mjs`)).seqCommand},{name:`expr`,load:async()=>(await import(`./expr-YYCVMXE3-CgQib9F9.mjs`)).exprCommand},{name:`md5sum`,load:async()=>(await import(`./md5sum-INMIK4DX-CJ1G9gTe.mjs`)).md5sumCommand},{name:`sha1sum`,load:async()=>(await import(`./sha1sum-VJPNLNU6-DnTKth9v.mjs`)).sha1sumCommand},{name:`sha256sum`,load:async()=>(await import(`./sha256sum-PI32XWXY-Z-xtGDHc.mjs`)).sha256sumCommand},{name:`file`,load:async()=>(await import(`./file-IGDTDPLG-BAlm5q29.mjs`)).fileCommand},{name:`html-to-markdown`,load:async()=>(await import(`./html-to-markdown-TFCECAGV-CF0t8_d3.mjs`)).htmlToMarkdownCommand},{name:`help`,load:async()=>(await import(`./help-VVWX7SA5-BncYWg0B.mjs`)).helpCommand},{name:`which`,load:async()=>(await import(`./which-XZHEH76L-imZgNd5x.mjs`)).whichCommand},{name:`tac`,load:async()=>(await import(`./tac-SJGXQ4T2-D-bfDFKg.mjs`)).tac},{name:`hostname`,load:async()=>(await import(`./hostname-BK6HG2DE-CaZb-T_R.mjs`)).hostname},{name:`whoami`,load:async()=>(await import(`./whoami-DGKU3D2X-CzLNG51j.mjs`)).whoami},{name:`od`,load:async()=>(await import(`./od-VJEF2UR5-5RFpmlxK.mjs`)).od},{name:`gzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CmMf6H0r.mjs`)).gzipCommand},{name:`gunzip`,load:async()=>(await import(`./gzip-AQXSGOVS-CmMf6H0r.mjs`)).gunzipCommand},{name:`zcat`,load:async()=>(await import(`./gzip-AQXSGOVS-CmMf6H0r.mjs`)).zcatCommand}];(typeof __BROWSER__>`u`||!__BROWSER__)&&(N4.push({name:`tar`,load:async()=>(await import(`./tar-MZQD7NO4-Cx5bpVMY.mjs`)).tarCommand}),N4.push({name:`yq`,load:async()=>(await import(`./yq-OAKYHSXH-BcCBaLJN.mjs`)).yqCommand}),N4.push({name:`xan`,load:async()=>(await import(`./xan-UD7JYIL2-_38Iv1cI.mjs`)).xanCommand}),N4.push({name:`sqlite3`,load:async()=>(await import(`./sqlite3-TE5AIOTF-DcjYN7WW.mjs`)).sqlite3Command}));var P4=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(P4.push({name:`python3`,load:async()=>(await import(`./python3-DNGS4G3E-BZ5fPY5e.mjs`)).python3Command}),P4.push({name:`python`,load:async()=>(await import(`./python3-DNGS4G3E-BZ5fPY5e.mjs`)).pythonCommand}));var F4=[];(typeof __BROWSER__>`u`||!__BROWSER__)&&(F4.push({name:`js-exec`,load:async()=>(await import(`./js-exec-VXN6TZ7U-1yyCDQqM.mjs`)).jsExecCommand}),F4.push({name:`node`,load:async()=>(await import(`./js-exec-VXN6TZ7U-1yyCDQqM.mjs`)).nodeStubCommand}));var Pme=[{name:`curl`,load:async()=>(await import(`./curl-47BFPSFW-d1TMPUJw.mjs`)).curlCommand}],I4=new Map;function L4(e){return{name:e.name,async execute(t,n){let r=I4.get(e.name);if(r||(r=await fl.runTrustedAsync(()=>e.load()),I4.set(e.name,r)),n.coverage&&(typeof __BROWSER__>`u`||!__BROWSER__)){let{emitFlagCoverage:r}=await import(`./flag-coverage-6JEX67RU-Cj_NycUm.mjs`);r(n.coverage,e.name,t)}return r.execute(t,n)}}}function Fme(e){return(e?N4.filter(t=>e.includes(t.name)):N4).map(L4)}function Ime(){return Pme.map(L4)}function Lme(){return P4.map(L4)}function Rme(){return F4.map(L4)}function zme(e){return`load`in e&&typeof e.load==`function`}function Bme(e){let t=null;return{name:e.name,trusted:!0,async execute(n,r){return t||=await e.load(),t.execute(n,r)}}}var R4=new TextEncoder;function Vme(e){return typeof e==`object`&&!!e&&!(e instanceof Uint8Array)&&`content`in e}var z4=class{data=new Map;constructor(e){if(this.data.set(`/`,{type:`directory`,mode:493,mtime:new Date}),e)for(let[t,n]of Object.entries(e))typeof n==`function`?this.writeFileLazy(t,n):Vme(n)?this.writeFileSync(t,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(t,n)}ensureParentDirs(e){let t=$c(e);t!==`/`&&(this.data.has(t)||(this.ensureParentDirs(t),this.data.set(t,{type:`directory`,mode:493,mtime:new Date})))}writeFileSync(e,t,n,r){rl(e,`write`);let i=Qc(e);this.ensureParentDirs(i);let a=sl(t,ol(n));this.data.set(i,{type:`file`,content:a,mode:r?.mode??420,mtime:r?.mtime??new Date})}writeFileLazy(e,t,n){rl(e,`write`);let r=Qc(e);this.ensureParentDirs(r),this.data.set(r,{type:`file`,lazy:t,mode:n?.mode??420,mtime:n?.mtime??new Date})}async materializeLazy(e,t){let n=await t.lazy(),r={type:`file`,content:typeof n==`string`?R4.encode(n):n,mode:t.mode,mtime:t.mtime};return this.data.set(e,r),r}async readFile(e,t){return cl(await this.readFileBuffer(e),ol(t))}async readFileBuffer(e){rl(e,`open`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!==`file`)throw Error(`EISDIR: illegal operation on a directory, read '${e}'`);if(`lazy`in n){let e=await this.materializeLazy(t,n);return e.content instanceof Uint8Array?e.content:R4.encode(e.content)}return n.content instanceof Uint8Array?n.content:R4.encode(n.content)}async writeFile(e,t,n){this.writeFileSync(e,t,n)}async appendFile(e,t,n){rl(e,`append`);let r=Qc(e),i=this.data.get(r);if(i&&i.type===`directory`)throw Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=sl(t,ol(n));if(i?.type===`file`){let e=i;`lazy`in e&&(e=await this.materializeLazy(r,e));let t=`content`in e&&e.content instanceof Uint8Array?e.content:R4.encode(`content`in e?e.content:``),n=new Uint8Array(t.length+a.length);n.set(t),n.set(a,t.length),this.data.set(r,{type:`file`,content:n,mode:e.mode,mtime:new Date})}else this.writeFileSync(e,t,n)}async exists(e){if(e.includes(`\0`))return!1;try{let t=this.resolvePathWithSymlinks(e);return this.data.has(t)}catch{return!1}}async stat(e){rl(e,`stat`);let t=this.resolvePathWithSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, stat '${e}'`);n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:R4.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}async lstat(e){rl(e,`lstat`);let t=this.resolveIntermediateSymlinks(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type===`symlink`)return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};n.type===`file`&&`lazy`in n&&(n=await this.materializeLazy(t,n));let r=0;return n.type===`file`&&`content`in n&&n.content&&(r=n.content instanceof Uint8Array?n.content.length:R4.encode(n.content).length),{isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:!1,mode:n.mode,size:r,mtime:n.mtime||new Date}}resolveIntermediateSymlinks(e){let t=Qc(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`);if(n.length<=1)return t;let r=``,i=new Set;for(let t=0;t<n.length-1;t++){let a=n[t];r=`${r}/${a}`;let o=this.data.get(r),s=0;for(;o&&o.type===`symlink`&&s<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`);i.add(r),r=al(r,o.target),o=this.data.get(r),s++}if(s>=40)throw Error(`ELOOP: too many levels of symbolic links, lstat '${e}'`)}return`${r}/${n[n.length-1]}`}resolvePathWithSymlinks(e){let t=Qc(e);if(t===`/`)return`/`;let n=t.slice(1).split(`/`),r=``,i=new Set;for(let t of n){r=`${r}/${t}`;let n=this.data.get(r),a=0;for(;n&&n.type===`symlink`&&a<40;){if(i.has(r))throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(r),r=al(r,n.target),n=this.data.get(r),a++}if(a>=40)throw Error(`ELOOP: too many levels of symbolic links, open '${e}'`)}return r}async mkdir(e,t){this.mkdirSync(e,t)}mkdirSync(e,t){rl(e,`mkdir`);let n=Qc(e);if(this.data.has(n)){if(this.data.get(n)?.type===`file`)throw Error(`EEXIST: file already exists, mkdir '${e}'`);if(!t?.recursive)throw Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let r=$c(n);if(r!==`/`&&!this.data.has(r))if(t?.recursive)this.mkdirSync(r,{recursive:!0});else throw Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:`directory`,mode:493,mtime:new Date})}async readdir(e){return(await this.readdirWithFileTypes(e)).map(e=>e.name)}async readdirWithFileTypes(e){rl(e,`scandir`);let t=Qc(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);let r=new Set;for(;n&&n.type===`symlink`;){if(r.has(t))throw Error(`ELOOP: too many levels of symbolic links, scandir '${e}'`);r.add(t),t=al(t,n.target),n=this.data.get(t)}if(!n)throw Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!==`directory`)throw Error(`ENOTDIR: not a directory, scandir '${e}'`);let i=t===`/`?`/`:`${t}/`,a=new Map;for(let[e,n]of this.data.entries())if(e!==t&&e.startsWith(i)){let t=e.slice(i.length),r=t.split(`/`)[0];r&&!t.includes(`/`,r.length)&&!a.has(r)&&a.set(r,{name:r,isFile:n.type===`file`,isDirectory:n.type===`directory`,isSymbolicLink:n.type===`symlink`})}return Array.from(a.values()).sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}async rm(e,t){rl(e,`rm`);let n=Qc(e),r=this.data.get(n);if(!r){if(t?.force)return;throw Error(`ENOENT: no such file or directory, rm '${e}'`)}if(r.type===`directory`){let r=await this.readdir(n);if(r.length>0){if(!t?.recursive)throw Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let e of r){let r=Xc(n,e);await this.rm(r,t)}}}this.data.delete(n)}async cp(e,t,n){rl(e,`cp`),rl(t,`cp`);let r=Qc(e),i=Qc(t),a=this.data.get(r);if(!a)throw Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type===`file`)if(this.ensureParentDirs(i),`content`in a){let e=a.content instanceof Uint8Array?new Uint8Array(a.content):a.content;this.data.set(i,{...a,content:e})}else this.data.set(i,{...a});else if(a.type===`symlink`)this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type===`directory`){if(!n?.recursive)throw Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let t=await this.readdir(r);for(let e of t){let t=Xc(r,e),a=Xc(i,e);await this.cp(t,a,n)}}}async mv(e,t){await this.cp(e,t,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,t){return Zc(e,t)}async chmod(e,t){rl(e,`chmod`);let n=Qc(e),r=this.data.get(n);if(!r)throw Error(`ENOENT: no such file or directory, chmod '${e}'`);r.mode=t}async symlink(e,t){rl(t,`symlink`);let n=Qc(t);if(this.data.has(n))throw Error(`EEXIST: file already exists, symlink '${t}'`);this.ensureParentDirs(n),this.data.set(n,{type:`symlink`,target:e,mode:511,mtime:new Date})}async link(e,t){rl(e,`link`),rl(t,`link`);let n=Qc(e),r=Qc(t),i=this.data.get(n);if(!i)throw Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!==`file`)throw Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(r))throw Error(`EEXIST: file already exists, link '${t}'`);let a=i;`lazy`in a&&(a=await this.materializeLazy(n,a)),this.ensureParentDirs(r),this.data.set(r,{type:`file`,content:a.content,mode:a.mode,mtime:a.mtime})}async readlink(e){rl(e,`readlink`);let t=Qc(e),n=this.data.get(t);if(!n)throw Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!==`symlink`)throw Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}async realpath(e){rl(e,`realpath`);let t=this.resolvePathWithSymlinks(e);if(!this.data.has(t))throw Error(`ENOENT: no such file or directory, realpath '${e}'`);return t}async utimes(e,t,n){rl(e,`utimes`);let r=Qc(e),i=this.resolvePathWithSymlinks(r),a=this.data.get(i);if(!a)throw Error(`ENOENT: no such file or directory, utimes '${e}'`);a.mtime=n}};function Hme(e){let t=e;return typeof t.mkdirSync==`function`&&typeof t.writeFileSync==`function`}function Ume(e,t){e.mkdirSync(`/bin`,{recursive:!0}),e.mkdirSync(`/usr/bin`,{recursive:!0}),t&&(e.mkdirSync(`/home/user`,{recursive:!0}),e.mkdirSync(`/tmp`,{recursive:!0}))}function Wme(e){e.mkdirSync(`/dev`,{recursive:!0}),e.writeFileSync(`/dev/null`,``),e.writeFileSync(`/dev/zero`,new Uint8Array),e.writeFileSync(`/dev/stdin`,``),e.writeFileSync(`/dev/stdout`,``),e.writeFileSync(`/dev/stderr`,``)}function Gme(e,t){e.mkdirSync(`/proc/self/fd`,{recursive:!0}),e.writeFileSync(`/proc/version`,`${Cc}
1244
1244
  `),e.writeFileSync(`/proc/self/exe`,`/bin/bash`),e.writeFileSync(`/proc/self/cmdline`,`bash\0`),e.writeFileSync(`/proc/self/comm`,`bash
1245
1245
  `),e.writeFileLazy?e.writeFileLazy(`/proc/self/status`,()=>uc(t)):e.writeFileSync(`/proc/self/status`,uc(t)),e.writeFileSync(`/proc/self/fd/0`,`/dev/stdin`),e.writeFileSync(`/proc/self/fd/1`,`/dev/stdout`),e.writeFileSync(`/proc/self/fd/2`,`/dev/stderr`)}function Kme(e,t,n={pid:1,ppid:0,uid:1e3,gid:1e3}){Hme(e)&&(Ume(e,t),Wme(e),Gme(e,n))}var qme=[`allexport`,`errexit`,`noglob`,`noclobber`,`noexec`,`nounset`,`pipefail`,`posix`,`verbose`,`xtrace`],Jme=[`braceexpand`,`hashall`,`interactive-comments`];function B4(e){let t=[],n=[...Jme.map(e=>({name:e,enabled:!0})),...qme.map(t=>({name:t,enabled:e[t]}))].sort((e,t)=>e.name.localeCompare(t.name));for(let e of n)e.enabled&&t.push(e.name);return t.join(`:`)}function V4(e){e.state.env.set(`SHELLOPTS`,B4(e.state.options))}var Yme=[`dotglob`,`expand_aliases`,`extglob`,`failglob`,`globskipdots`,`globstar`,`lastpipe`,`nocaseglob`,`nocasematch`,`nullglob`,`xpg_echo`];function H4(e){let t=[];for(let n of Yme)e[n]&&t.push(n);return t.join(`:`)}function U4(e){e.state.env.set(`BASHOPTS`,H4(e.state.shoptOptions))}var Xme=`BASH_ALIAS_`;function W4(e){return e.parts.length===1?e.parts[0].type===`Literal`:!1}function G4(e){if(e.parts.length!==1)return null;let t=e.parts[0];return t.type===`Literal`?t.value:null}function K4(e,t){return e.env.get(`${Xme}${t}`)}function q4(e,t,n){if(!t.name||!W4(t.name))return t;let r=G4(t.name);if(!r)return t;let i=K4(e,r);if(!i||n.has(r))return t;try{n.add(r);let a=new Wc,o=i,s=i.endsWith(` `);if(!s)for(let e of t.args){let t=Y4(e);o+=` ${t}`}let c;try{c=a.parse(o)}catch(e){if(e instanceof Vc)throw e;return t}if(c.statements.length!==1||c.statements[0].pipelines.length!==1||c.statements[0].pipelines[0].commands.length!==1)return J4(t,i);let l=c.statements[0].pipelines[0].commands[0];if(l.type!==`SimpleCommand`)return J4(t,i);let u={...l,assignments:[...t.assignments,...l.assignments],redirections:[...l.redirections,...t.redirections],line:t.line};if(s&&t.args.length>0&&(u={...u,args:[...u.args,...t.args]},u.args.length>0)){let t=u.args[0];if(W4(t)){let r=G4(t);if(r&&K4(e,r)){let r={type:`SimpleCommand`,name:t,args:u.args.slice(1),assignments:[],redirections:[]},i=q4(e,r,n);i!==r&&(u={...u,name:i.name,args:[...i.args]})}}}return u}catch(e){throw n.delete(r),e}}function J4(e,t){let n=t;for(let t of e.args){let e=Y4(t);n+=` ${e}`}let r=new Wc;return{type:`SimpleCommand`,name:r.parseWordFromString(`eval`,!1,!1),args:[r.parseWordFromString(`'${n.replace(/'/g,`'\\''`)}'`,!1,!1)],assignments:e.assignments,redirections:e.redirections,line:e.line}}function Y4(e){let t=``;for(let n of e.parts)switch(n.type){case`Literal`:t+=n.value.replace(/([\s"'$`\\*?[\]{}()<>|&;#!])/g,`\\$1`);break;case`SingleQuoted`:t+=`'${n.value}'`;break;case`DoubleQuoted`:t+=`"${n.parts.map(e=>e.type===`Literal`?e.value:`$${e.type}`).join(``)}"`;break;case`ParameterExpansion`:t+=`\${${n.parameter}}`;break;case`CommandSubstitution`:t+=`$(...)`;break;case`ArithmeticExpansion`:t+=`$((${n.expression}))`;break;case`Glob`:t+=n.pattern;break;default:break}return t}async function Zme(e,t){let n=t.parts.map(e=>e.type===`Literal`?e.value:`\0`).join(``),r=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\(/);if(!r||!n.endsWith(`)`))return null;let i=r[1],a=[],o=!1,s=``,c=!1;for(let n of t.parts)if(n.type===`Literal`){let e=n.value;if(!o){let t=e.indexOf(`=(`);t!==-1&&(o=!0,e=e.slice(t+2))}if(o){e.endsWith(`)`)&&(e=e.slice(0,-1));let t=e.split(/(\s+)/);for(let e of t)/^\s+$/.test(e)?(s||c)&&(a.push(s),s=``,c=!1):e&&(s+=e)}}else if(o)if(n.type===`BraceExpansion`)if(/^\[.+\]=/.test(s))s+=Mc({type:`Word`,parts:[n]});else{(s||c)&&(a.push(s),s=``,c=!1);let t=await Jc(e,{type:`Word`,parts:[n]});a.push(...t.values)}else{(n.type===`SingleQuoted`||n.type===`DoubleQuoted`||n.type===`Escaped`)&&(c=!0);let t=await kc(e,{type:`Word`,parts:[n]});s+=t}return(s||c)&&a.push(s),`${i}=(${a.map(e=>/^\[.+\]=/.test(e)?e:e===``?`''`:/[\s"'\\$`!*?[\]{}|&;<>()]/.test(e)&&!e.startsWith(`'`)&&!e.startsWith(`"`)?`'${e.replace(/'/g,`'\\''`)}'`:e).join(` `)})`}async function Qme(e,t){let n=-1,r=-1,i=!1;for(let e=0;e<t.parts.length;e++){let a=t.parts[e];if(a.type===`Literal`){let t=a.value.indexOf(`+=`);if(t!==-1){let o=a.value.slice(0,t);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){n=e,r=t,i=!0;break}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(o)){n=e,r=t,i=!0;break}}let o=a.value.indexOf(`=`);if(o!==-1&&(o===0||a.value[o-1]!==`+`)){let t=a.value.slice(0,o);if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)||/^[a-zA-Z_][a-zA-Z0-9_]*\[[^\]]+\]$/.test(t)){n=e,r=o;break}}}}if(n===-1)return null;let a=t.parts.slice(0,n),o=t.parts[n];if(o.type!==`Literal`)return null;let s=i?2:1,c=o.value.slice(0,r),l=o.value.slice(r+s),u=t.parts.slice(n+1),d=``;for(let t of a)d+=await kc(e,{type:`Word`,parts:[t]});d+=c;let f={type:`Word`,parts:l===``?u:[{type:`Literal`,value:l},...u]},p=f.parts.length>0?await kc(e,f):``;return`${d}${i?`+=`:`=`}${p}`}var $me=[`tar`,`yq`,`xan`,`sqlite3`,`python3`,`python`];function ehe(e){return $me.includes(e)}var X4=Object.freeze({stdout:``,stderr:``,exitCode:0});function Z4(e=``){return{stdout:e,stderr:``,exitCode:0}}function Q4(e,t=1){return{stdout:``,stderr:e,exitCode:t}}function $4(e,t,n){return{stdout:e,stderr:t,exitCode:n}}function e3(e){return{stdout:``,stderr:``,exitCode:+!e}}function t3(e,t,n=``,r=``){throw new Qs(e,t,n,r)}function n3(e){let t=e.state.fileDescriptors;if(t&&t.size>=e.limits.maxFileDescriptors)throw new Qs(`too many open file descriptors (max ${e.limits.maxFileDescriptors})`,`file_descriptors`)}function the(e,t){if(e.state.loopDepth===0){if(e.state.parentHasLoopContext)throw new ac;return X4}if(t.length>1)throw new nc(1,``,`bash: break: too many arguments
1246
1246
  `);let n=1;if(t.length>0){let e=Number.parseInt(t[0],10);if(Number.isNaN(e)||e<1)throw new nc(128,``,`bash: break: ${t[0]}: numeric argument required
@@ -1895,7 +1895,7 @@ sys 0m0.000s
1895
1895
  `,1)}}if(i=Math.max(...r.map(([e])=>typeof e==`number`?e:0))+1+i,i<0){let r=e.state.currentLine;return{index:0,error:$4(``,`bash: line ${r}: ${t}[${n}]: bad array subscript
1896
1896
  `,1)}}}return{index:i}}async function d_e(e,t,n,r,i,a){let o=``,s=n,c=null;if(Ec(e,n)){let t=mc(e,n,r);if(t===void 0)return{continueToNext:!1,xtraceOutput:``,error:$4(``,`bash: ${n}: circular name reference
1897
1897
  `,1)};if(t===null)return{continueToNext:!0,xtraceOutput:``};s=t;let i=s.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);i&&(c={arrayName:i[1],subscriptExpr:i[2]},s=i[1])}if(lc(e,s)){if(t.name)return o+=`bash: ${s}: readonly variable
1898
- `,{continueToNext:!0,xtraceOutput:o};let n=dc(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if(o6(e,s))try{let t=new Wc;if(i){let n=Dc(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await zc(e,n.expression))}else{let n=Dc(t,r);l=String(await zc(e,n.expression))}}catch{l=`0`}else{let{isArray:t}=await import(`./expansion-VBDYWVZR-e2HuIG0U.mjs`),n=t(e,s)?`${s}_0`:s;l=i?(e.state.env.get(n)||``)+r:r}l=l6(e,s,l),o+=await t_e(e,s,l);let u=s;if(c)u=await f_e(e,c);else{let{isArray:t}=await import(`./expansion-VBDYWVZR-e2HuIG0U.mjs`);t(e,s)&&(u=`${s}_0`)}return t.name?(a.set(u,e.state.env.get(u)),e.state.env.set(u,l)):(e.state.env.set(u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function f_e(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return U6(e,n,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await zc(e,Dc(new Wc,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=Oc(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return`${n}_${i}`}async function p_e(e,t,n,r){let i=await V3(e,t.redirections);if(i)return i;let a=new Map(e.state.env),o=e.state.cwd,s={...e.state.options},c=new Map(e.state.functions),l=e.state.localScopes,u=e.state.localVarStack,d=e.state.localVarDepth,f=e.state.fullyUnsetLocals;if(e.state.localScopes=l.map(e=>new Map(e)),u){e.state.localVarStack=new Map;for(let[t,n]of u.entries())e.state.localVarStack.set(t,n.map(e=>({...e})))}d&&(e.state.localVarDepth=new Map(d)),f&&(e.state.fullyUnsetLocals=new Map(f));let p=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let _=e.state.groupStdin;n&&(e.state.groupStdin=n);let v=``,y=``,b=0,x=()=>{e.state.env=a,e.state.cwd=o,e.state.options=s,e.state.functions=c,e.state.localScopes=l,e.state.localVarStack=u,e.state.localVarDepth=d,e.state.fullyUnsetLocals=f,e.state.loopDepth=p,e.state.parentHasLoopContext=m,e.state.groupStdin=_,e.state.bashPid=g,e.state.lastArg=h};try{for(let e of t.body){let t=await r(e);v+=t.stdout,y+=t.stderr,b=t.exitCode}}catch(n){if(x(),n instanceof Qs)throw n;return n instanceof ac||n instanceof qs||n instanceof ic?(v+=n.stdout,y+=n.stderr,H3(e,$4(v,y,0),t.redirections)):n instanceof nc||n instanceof $s?(v+=n.stdout,y+=n.stderr,H3(e,$4(v,y,n.exitCode),t.redirections)):n instanceof rc?H3(e,$4(v+n.stdout,y+n.stderr,n.exitCode),t.redirections):H3(e,$4(v,`${y}${xl(n)}
1898
+ `,{continueToNext:!0,xtraceOutput:o};let n=dc(e,s);if(n)return{continueToNext:!1,xtraceOutput:``,error:n}}let l;if(o6(e,s))try{let t=new Wc;if(i){let n=Dc(t,`(${e.state.env.get(s)||`0`}) + (${r})`);l=String(await zc(e,n.expression))}else{let n=Dc(t,r);l=String(await zc(e,n.expression))}}catch{l=`0`}else{let{isArray:t}=await import(`./expansion-VBDYWVZR-CeY6vkty.mjs`),n=t(e,s)?`${s}_0`:s;l=i?(e.state.env.get(n)||``)+r:r}l=l6(e,s,l),o+=await t_e(e,s,l);let u=s;if(c)u=await f_e(e,c);else{let{isArray:t}=await import(`./expansion-VBDYWVZR-CeY6vkty.mjs`);t(e,s)&&(u=`${s}_0`)}return t.name?(a.set(u,e.state.env.get(u)),e.state.env.set(u,l)):(e.state.env.set(u,l),e.state.options.allexport&&(e.state.exportedVars=e.state.exportedVars||new Set,e.state.exportedVars.add(s)),e.state.tempEnvBindings?.some(e=>e.has(s))&&(e.state.mutatedTempEnvVars=e.state.mutatedTempEnvVars||new Set,e.state.mutatedTempEnvVars.add(s))),{continueToNext:!1,xtraceOutput:o}}async function f_e(e,t){let{arrayName:n,subscriptExpr:r}=t;if(e.state.associativeArrays?.has(n))return U6(e,n,r);let i;if(/^-?\d+$/.test(r))i=Number.parseInt(r,10);else{try{i=await zc(e,Dc(new Wc,r).expression,!1)}catch{let t=e.state.env.get(r);i=t?Number.parseInt(t,10):0}Number.isNaN(i)&&(i=0)}if(i<0){let t=Oc(e,n);t.length>0&&(i=Math.max(...t.map(e=>e[0]))+1+i)}return`${n}_${i}`}async function p_e(e,t,n,r){let i=await V3(e,t.redirections);if(i)return i;let a=new Map(e.state.env),o=e.state.cwd,s={...e.state.options},c=new Map(e.state.functions),l=e.state.localScopes,u=e.state.localVarStack,d=e.state.localVarDepth,f=e.state.fullyUnsetLocals;if(e.state.localScopes=l.map(e=>new Map(e)),u){e.state.localVarStack=new Map;for(let[t,n]of u.entries())e.state.localVarStack.set(t,n.map(e=>({...e})))}d&&(e.state.localVarDepth=new Map(d)),f&&(e.state.fullyUnsetLocals=new Map(f));let p=e.state.loopDepth,m=e.state.parentHasLoopContext;e.state.parentHasLoopContext=p>0,e.state.loopDepth=0;let h=e.state.lastArg,g=e.state.bashPid;e.state.bashPid=e.state.nextVirtualPid++;let _=e.state.groupStdin;n&&(e.state.groupStdin=n);let v=``,y=``,b=0,x=()=>{e.state.env=a,e.state.cwd=o,e.state.options=s,e.state.functions=c,e.state.localScopes=l,e.state.localVarStack=u,e.state.localVarDepth=d,e.state.fullyUnsetLocals=f,e.state.loopDepth=p,e.state.parentHasLoopContext=m,e.state.groupStdin=_,e.state.bashPid=g,e.state.lastArg=h};try{for(let e of t.body){let t=await r(e);v+=t.stdout,y+=t.stderr,b=t.exitCode}}catch(n){if(x(),n instanceof Qs)throw n;return n instanceof ac||n instanceof qs||n instanceof ic?(v+=n.stdout,y+=n.stderr,H3(e,$4(v,y,0),t.redirections)):n instanceof nc||n instanceof $s?(v+=n.stdout,y+=n.stderr,H3(e,$4(v,y,n.exitCode),t.redirections)):n instanceof rc?H3(e,$4(v+n.stdout,y+n.stderr,n.exitCode),t.redirections):H3(e,$4(v,`${y}${xl(n)}
1899
1899
  `,1),t.redirections)}return x(),H3(e,$4(v,y,b),t.redirections)}async function m_e(e,t,n,r){let i=``,a=``,o=0,s=await B3(e,t.redirections);if(s)return s;let c=n;for(let n of t.redirections)if((n.operator===`<<`||n.operator===`<<-`)&&n.target.type===`HereDoc`){let t=n.target,r=await kc(e,t.content);t.stripTabs&&(r=r.split(`
1900
1900
  `).map(e=>e.replace(/^\t+/,``)).join(`
1901
1901
  `));let i=n.fd??0;i===0?c=r:(e.state.fileDescriptors||(e.state.fileDescriptors=new Map),n3(e),e.state.fileDescriptors.set(i,r))}else if(n.operator===`<<<`&&n.target.type===`Word`)c=`${await kc(e,n.target)}
@@ -2010,13 +2010,13 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
2010
2010
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
2011
2011
  `)+`\r
2012
2012
  \r
2013
- `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));Ixe(),q5(),J5(),X5(),Rxe();async function Z5(e,t){let n=L(`config-file-watcher`),{watch:r}=await import(`./chokidar-BCS--vwu.mjs`),i=R(e);try{Zo(i,{recursive:!0})}catch(e){Vs(e)!==`EEXIST`&&n.warn({err:e,watchDir:i},`failed to create watch directory; watcher may be inert`)}let a=r(i,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==i&&t!==e});await new Promise(e=>{a.once(`ready`,e)});let o=null;try{o=U(e,`utf-8`)}catch{}let s=(r,i=!0)=>{if(r!==e)return;let a;try{a=U(r,`utf-8`)}catch(e){if(Vs(e)===`ENOENT`){i&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(a!==o){o=a;try{t(a)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},c=e=>s(e);a.on(`add`,c),a.on(`change`,c),a.on(`unlink`,t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),a.on(`error`,t=>{n.warn({err:t,watchDir:i,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let l=0,u=setInterval(()=>{l++,s(e,!1),l>=20&&clearInterval(u)},500);u.unref?.();let d=!1;return async()=>{d||(d=!0,clearInterval(u),await a.close())}}async function zxe(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=L(`config-file-watcher`),{watch:r}=await import(`./chokidar-BCS--vwu.mjs`),i=new Set(e),a=Array.from(new Set(Array.from(i,e=>R(e))));for(let e of a)try{Zo(e,{recursive:!0})}catch(t){Vs(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let o=r(a,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!i.has(e)&&!a.includes(e)});await new Promise(e=>{o.once(`ready`,e)});let s=new Map;for(let e of i)try{s.set(e,U(e,`utf-8`))}catch{s.set(e,null)}let c=(e,r=!0)=>{if(!i.has(e))return;let a;try{a=U(e,`utf-8`)}catch(t){if(Vs(t)===`ENOENT`){r&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(a!==s.get(e)){s.set(e,a);try{t(e,a)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},l=e=>c(e);o.on(`add`,l),o.on(`change`,l),o.on(`unlink`,e=>{i.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)}),o.on(`error`,e=>{n.warn({err:e,watchDirs:a,paths:Array.from(i)},`[config-file-watcher] chokidar error in multi-path watcher`)});let u=0,d=setInterval(()=>{u++;for(let e of i)c(e,!1);u>=20&&clearInterval(d)},500);d.unref?.();let f=!1;return async()=>{f||(f=!0,clearInterval(d),await o.close())}}const Q5=L(`config-persistence`);function $5(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let e7=null;function t7(){return e7||=ls().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),e7}function n7(e){if(le(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)de(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function r7(e,t){if(e===`__config__/project`)return Lo(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return Lo(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return Lo(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return V(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let i7=null;function Bxe(){return i7===null&&(i7=(0,ej.stringify)(ke.parse({}))),i7}function Vxe(e){if(e.length===0)return{ok:!0};let t=e.split(`
2014
- `);for(let e=0;e<t.length;e++){let n=t[e]??``;if(n.length!==0&&/^\s+$/.test(n))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function a7(e,t){return e===`__config__/okignore`?Vxe(t):Hxe(t)}function o7(e){return e===`__config__/okignore`?``:Bxe()}function Hxe(e){let t=(0,ej.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let n=t.toJSON()??{},r=ke.safeParse(n);return r.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:r.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function Uxe(e,t,n){let r=e.getText(`source`);if(r.length>0)return;let i=r7(t,n),a=``;if(H(i))try{a=U(i,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);Q5.warn({path:i,err:e},`[config-persistence] Could not read ${i}: ${t}. Seeding with empty content.`),a=``}let o=a7(t,a);!o.ok&&a.length>0&&Q5.warn({docName:t,path:i},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{a.length>0&&r.insert(0,a)},rN),o.ok&&a.length>0?n.lkgCache.set(t,a):n.lkgCache.set(t,o7(t))}async function Wxe(e,t){await Uo(R(e),{recursive:!0});let n=`${e}.tmp.${crypto.randomUUID()}`;try{await Bo(n,t,`utf-8`),await as(n,e)}catch(e){try{Ko(n)}catch{}throw e}}async function Gxe(e,t,n,r){return ie(`config.persist`,{"config.scope":$5(t),"config.transport":`fs`},async i=>{let a=await qxe(e,t,n,r);return i.setAttribute(`config.outcome`,Kxe(a)),a})}function Kxe(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function qxe(e,t,n,r){if(r.ephemeral&&t===`__config__/okignore`||n===rN)return`no-op`;let i=e.getText(`source`),a=i.toString(),o=r.lkgCache.get(t);if(a.length===0&&(t!==`__config__/okignore`||o===void 0||o===``)||o!==void 0&&a===o)return`no-op`;let s=$5(t),c=Te(`config.validate`,{"config.scope":s,"config.validation.layer":`L3`},e=>{let n=a7(t,a);return e.setAttribute(`config.outcome`,n.ok?`success`:`rejected`),n.ok||n7(n.error),n});if(!c.ok)return await ie(`config.revert`,{"config.scope":s,"config.outcome":`reverted`},async()=>{let n=o??o7(t);e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},rN),o===void 0&&r.lkgCache.set(t,n),t===`__config__/okignore`&&le(c.error)&&t7().add(1,{"error.code":c.error.code}),r.onConfigRejected?.(t,c.error)}),`reverted`;let l=r7(t,r);try{await Uo(R(l),{recursive:!0})}catch(e){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] could not create parent dir for ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${l}: ${n}`}),`write-failed`}try{return await Yo(`${l}.lock`,async()=>{let n=null;try{n=U(l,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] could not read config for reconciliation: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${l}: ${n}`}),`write-failed`}}if(n!==null&&o!==void 0&&n!==o){if(a7(t,n).ok)return e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},iN),r.lkgCache.set(t,n),Q5.info({docName:t,path:l},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;Q5.warn({docName:t,path:l},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await Wxe(l,a)}catch(e){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] write-failed at ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${l}: ${n}`}),`write-failed`}return r.lkgCache.set(t,a),`persisted`},{onWarn:(e,t)=>{Q5.warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof jo)return Q5.warn({docName:t,path:l,err:e},`[config-persistence] lock timeout at ${l}: ${e.message}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function s7(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);if(i!==void 0&&i===n)return`no-op`;let a=Te(`config.validate`,{"config.scope":$5(t),"config.validation.layer":`L3`},e=>{let r=a7(t,n);return e.setAttribute(`config.outcome`,r.ok?`success`:`rejected`),r.ok||n7(r.error),r});if(!a.ok)return t===`__config__/okignore`&&le(a.error)&&t7().add(1,{"error.code":a.error.code}),r.onConfigRejected?.(t,a.error),`rejected`;let o=e.getText(`source`);return e.transact(()=>{o.length>0&&o.delete(0,o.length),o.insert(0,n)},iN),r.lkgCache.set(t,n),`applied`}function c7(e,t,n,r){let i=Cj(B(r,z(n,e.file)));return i.startsWith(`..`)?!1:$S(i)===t}function Jxe(e){let{getSyncEngine:t,projectDir:n,contentDir:r}=e;return{async afterLoadDocument({documentName:e,document:i}){if(!(lC(e)||uC(e)))try{let a=t();if(!a)return;let o=a.getConflicts();if(o.length===0||!o.some(t=>c7(t,e,n,r)))return;let s=i.getMap(`lifecycle`);if(s.get(`status`)===`conflict`)return;s.set(`status`,`conflict`),s.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){L(`conflict-lifecycle-seed`).warn({docName:e,err:t instanceof Error?t:Error(String(t))},`failed to seed lifecycle on load (doc=${e})`)}}}}function Yxe(e,t,n){try{if(typeof t!=`string`||t.length===0||lC(e)||uC(e))return;let r=n.getLoadedDoc(e);if(r===void 0)throw gS(),Mo({"auth.reason":`doc-lineage-mismatch`}),new WZ(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let i=r.getMap(`lifecycle`).get(fr);if(typeof i!=`string`||i.length===0||i!==t)throw gS(),Mo({"auth.reason":`doc-lineage-mismatch`}),new WZ(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof WZ)throw t;lae(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}var l7=class{reconciledBaseByBranch=new Map;inFlightFlushByDoc=new Map;agentWriteStores=new Set;storeFailures=new Map;storeDivergences=new Set;activeBranch;batchInProgress=!1;constructor(e=`main`){this.activeBranch=e,this.reconciledBaseByBranch.set(e,new Map)}switchReconciledBaseScope(e){this.activeBranch=e,this.reconciledBaseByBranch.has(e)||this.reconciledBaseByBranch.set(e,new Map)}getActiveBranch(){return this.activeBranch}getReconciledBase(e){return this.reconciledBaseByBranch.get(this.activeBranch)?.get(e)}setReconciledBase(e,t){let n=this.reconciledBaseByBranch.get(this.activeBranch);n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n)),n.set(e,t)}deleteReconciledBase(e){this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e)}beginInFlightFlush(e,t){this.inFlightFlushByDoc.set(e,t)}peekInFlightFlush(e){return this.inFlightFlushByDoc.get(e)}finishInFlightFlush(e,t){this.inFlightFlushByDoc.get(e)===t&&this.inFlightFlushByDoc.delete(e)}setBatchInProgress(e){this.batchInProgress=e}isBatchInProgress(){return this.batchInProgress}markAgentWriteStore(e){this.agentWriteStores.add(e)}consumeAgentWriteStore(e){return this.agentWriteStores.delete(e)}recordStoreFailure(e,t){this.storeFailures.set(e,t)}clearStoreFailure(e){this.storeFailures.delete(e)}takeStoreFailure(e){let t=this.storeFailures.get(e)??null;return this.storeFailures.delete(e),t}recordStoreDivergence(e){this.storeDivergences.add(e)}takeStoreDivergence(e){return this.storeDivergences.delete(e)}};const u7=L(`head-watcher`),Xxe=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function d7(e){let t=e.readHead();if(t.kind===`detached`)return{branch:`detached-${t.oid.slice(0,12)}`,oid:t.oid};if(t.kind!==`branch`)return{branch:null,oid:null};let n=e.readRef(t.ref),r=n.kind===`present`&&n.value.kind===`oid`?n.value.oid:null;return{branch:t.branch,oid:r}}function f7(e){let t=Ju(e);return t.kind===`repository`?d7(t.repository):{branch:null,oid:null}}function Zxe(e){let t=e.split(`/`).pop()??``;return Xxe.has(t)?t:null}async function Qxe(e,t){let n;try{n=await import(`@parcel/watcher`)}catch(e){return u7.debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let r=await n.subscribe(e,(e,n)=>{if(e){u7.warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of n)t(e.path)});return()=>r.unsubscribe()}catch(e){return u7.debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function $xe(e,t){let{watch:n}=await import(`./chokidar-BCS--vwu.mjs`),r=n(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return r.on(`all`,(e,n)=>t(n)),r.on(`error`,e=>{u7.warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>r.close()}async function eSe(e,t,n,r={}){let i=Ju(e);if(i.kind!==`repository`)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let a=i.repository,o=a.gitDir,s=!1,c=null,l=null,u=null,d=null,f=null;async function p(e){if(h&&await h,f){await f;return}if(!s)return;c&&=(clearTimeout(c),null),l&&=(clearTimeout(l),null);let t=d7(a),r=t.oid,i=u!==r,o=t.branch,p;p=o?.startsWith(`detached-`)?`detached-head`:d===o?`within-branch`:`cross-branch`;let m=d,g=Promise.resolve().then(async()=>{try{await n({headMoved:i,oldHead:u,newHead:r,timeout:e,batchKind:p,oldBranch:m,newBranch:o})}catch(e){u7.error({err:e},`onBatchEnd callback failed`)}finally{s=!1,u=r,d=o}});f=g;try{await g}finally{f===g&&(f=null)}}function m(){c&&clearTimeout(c),c=setTimeout(()=>{c=null,p(!1)},100)}let h=null;async function g(e){if(f&&await f,!s){s=!0,u===null&&(u=d7(a).oid);let n=(async()=>{try{await t({trigger:e})}catch(e){u7.error({err:e},`onBatchBegin callback failed`)}})();h=n,await n,h=null,l=setTimeout(()=>{l=null,p(!0)},3e4)}m()}let _=e=>{let t=Zxe(e);t!==null&&g(t)},v=null,y=`chokidar`;if(r.subscribeForTest?(v=await r.subscribeForTest(o,_),y=`test`):r.forceBackend!==`chokidar`&&(v=await Qxe(o,_),v&&(y=`parcel`)),!v){if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);v=await $xe(o,_),y=`chokidar`}let b=v,x=d7(a);return u=x.oid,d=x.branch,u7.info({gitDir:o,backend:y},`watching for HEAD changes`),{unsubscribe:async()=>{s&&await p(!1),c&&clearTimeout(c),l&&clearTimeout(l),await b()},getLastKnownBranch:()=>d}}const tSe=100;function nSe(e){return typeof e!=`object`||!e?!1:e.source===`local`}function rSe(e){return e.getText(`source`).toString()}function p7(e){let{derivedDocumentIndex:t,onDocumentSettled:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t.timer),i.delete(e))}function o(e,r,i){let a;try{a=rSe(r)}catch(t){return L(`live-derived-index`).error({docName:e,err:t},`Failed to update derived views for ${e}`),Promise.resolve()}return t.recordLiveDocument(e,a,i).then(()=>{n?.(e)}).catch(t=>{L(`live-derived-index`).error({docName:e,err:t},`Failed to update derived views for ${e}`)})}async function s(e){let t=i.get(e);t&&(clearTimeout(t.timer),i.delete(e),await o(e,t.document,t.token))}function c(e,t,n){a(e),i.set(e,{document:t,token:n,timer:setTimeout(()=>{i.delete(e),o(e,t,n)},r)})}return{async onChange({documentName:e,document:n,transactionOrigin:r}){if(hC(e)||nSe(r)&&r.context?.origin===`file-watcher`)return;let i=t.captureLiveUpdateToken();if(i===null){a(e);return}c(e,n,i)},async beforeUnloadDocument({documentName:e}){await s(e)},async onDestroy(){for(let{timer:e}of i.values())clearTimeout(e);i.clear()}}}const m7=L(`shadow-gc`);function iSe(e){let t=new Set;for(let n of e){let e=n.replace(/^refs\/wip\//,``),r=e.lastIndexOf(`/`);if(r<=0)continue;let i=e.slice(0,r);Ed(e.slice(r+1)).classification!==`unknown`&&t.add(i)}return t}async function aSe(e,t){try{return(await xs().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function oSe(e){let t=new Set;try{let n=(await xs().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(n)for(let e of n.split(`
2013
+ `+n)}function v(e,t,n,r,i,a){if(e.listenerCount(`wsClientError`)){let r=Error(i);Error.captureStackTrace(r,v),e.emit(`wsClientError`,r,n,t)}else _(n,r,i,a)}}));Ixe(),q5(),J5(),X5(),Rxe();async function Z5(e,t){let n=L(`config-file-watcher`),{watch:r}=await import(`./chokidar-CVNrjmRM.mjs`),i=R(e);try{Zo(i,{recursive:!0})}catch(e){Vs(e)!==`EEXIST`&&n.warn({err:e,watchDir:i},`failed to create watch directory; watcher may be inert`)}let a=r(i,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:t=>t!==i&&t!==e});await new Promise(e=>{a.once(`ready`,e)});let o=null;try{o=U(e,`utf-8`)}catch{}let s=(r,i=!0)=>{if(r!==e)return;let a;try{a=U(r,`utf-8`)}catch(e){if(Vs(e)===`ENOENT`){i&&n.debug({path:r},`config file disappeared between event and read; dropping`);return}n.warn({err:e,path:r},`config file read failed; dropping event`);return}if(a!==o){o=a;try{t(a)}catch(e){n.warn({err:e,path:r},`config file change handler threw`)}}},c=e=>s(e);a.on(`add`,c),a.on(`change`,c),a.on(`unlink`,t=>{t===e&&n.debug({path:t},`config file unlinked; Y.Text retained at current state`)}),a.on(`error`,t=>{n.warn({err:t,watchDir:i,absPath:e},`[config-file-watcher] chokidar error while watching ${e}`)});let l=0,u=setInterval(()=>{l++,s(e,!1),l>=20&&clearInterval(u)},500);u.unref?.();let d=!1;return async()=>{d||(d=!0,clearInterval(u),await a.close())}}async function zxe(e,t){if(e.length===0)throw Error(`startMultiPathConfigFileWatcher requires at least one absolute path`);let n=L(`config-file-watcher`),{watch:r}=await import(`./chokidar-CVNrjmRM.mjs`),i=new Set(e),a=Array.from(new Set(Array.from(i,e=>R(e))));for(let e of a)try{Zo(e,{recursive:!0})}catch(t){Vs(t)!==`EEXIST`&&n.warn({err:t,dir:e},`failed to create watch directory; watcher may be inert`)}let o=r(a,{ignoreInitial:!0,depth:0,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},ignored:e=>!i.has(e)&&!a.includes(e)});await new Promise(e=>{o.once(`ready`,e)});let s=new Map;for(let e of i)try{s.set(e,U(e,`utf-8`))}catch{s.set(e,null)}let c=(e,r=!0)=>{if(!i.has(e))return;let a;try{a=U(e,`utf-8`)}catch(t){if(Vs(t)===`ENOENT`){r&&n.debug({path:e},`config file disappeared between event and read; dropping`);return}n.warn({err:t,path:e},`config file read failed; dropping event`);return}if(a!==s.get(e)){s.set(e,a);try{t(e,a)}catch(t){n.warn({err:t,path:e},`config file change handler threw`)}}},l=e=>c(e);o.on(`add`,l),o.on(`change`,l),o.on(`unlink`,e=>{i.has(e)&&n.debug({path:e},`config file unlinked; downstream state retained`)}),o.on(`error`,e=>{n.warn({err:e,watchDirs:a,paths:Array.from(i)},`[config-file-watcher] chokidar error in multi-path watcher`)});let u=0,d=setInterval(()=>{u++;for(let e of i)c(e,!1);u>=20&&clearInterval(d)},500);d.unref?.();let f=!1;return async()=>{f||(f=!0,clearInterval(d),await o.close())}}const Q5=L(`config-persistence`);function $5(e){if(e===`__config__/project`)return`project`;if(e===`__local__/project`)return`project-local`;if(e===`__user__/config.yml`)return`user`;if(e===`__config__/okignore`)return`project`}let e7=null;function t7(){return e7||=ls().createCounter(`ok.config.ignore.rejection_total`,{description:`Count of okignore L3 rejections by error code.`}),e7}function n7(e){if(le(e)&&e.code===`SCHEMA_INVALID`)for(let t of e.issues)de(`config.validation.issue`,{"issue.path":t.path.map(e=>String(e)).join(`.`),"issue.message":t.message})}function r7(e,t){if(e===`__config__/project`)return Lo(`project`,t.projectDir,t.homedirOverride);if(e===`__local__/project`)return Lo(`project-local`,t.projectDir,t.homedirOverride);if(e===`__user__/config.yml`)return Lo(`user`,t.projectDir,t.homedirOverride);if(e===`__config__/okignore`)return V(t.contentDir??t.projectDir,`.okignore`);throw Error(`configDocAbsPath: not a config doc name: ${e}`)}let i7=null;function Bxe(){return i7===null&&(i7=(0,ej.stringify)(ke.parse({}))),i7}function Vxe(e){if(e.length===0)return{ok:!0};let t=e.split(`
2014
+ `);for(let e=0;e<t.length;e++){let n=t[e]??``;if(n.length!==0&&/^\s+$/.test(n))return{ok:!1,error:{code:`OKIGNORE_INVALID`,detail:`Whitespace-only pattern is not allowed.`,lineNumber:e+1}}}return{ok:!0}}function a7(e,t){return e===`__config__/okignore`?Vxe(t):Hxe(t)}function o7(e){return e===`__config__/okignore`?``:Bxe()}function Hxe(e){let t=(0,ej.parseDocument)(e);if(t.errors.length>0)return{ok:!1,error:{code:`YAML_PARSE`,detail:t.errors.map(e=>e.message).join(`; `)}};let n=t.toJSON()??{},r=ke.safeParse(n);return r.success?{ok:!0}:{ok:!1,error:{code:`SCHEMA_INVALID`,issues:r.error.issues.map(e=>({path:e.path.map(e=>typeof e==`symbol`?String(e):e),message:e.message,issueCode:e.code}))}}}function Uxe(e,t,n){let r=e.getText(`source`);if(r.length>0)return;let i=r7(t,n),a=``;if(H(i))try{a=U(i,`utf-8`)}catch(e){let t=e instanceof Error?e.message:String(e);Q5.warn({path:i,err:e},`[config-persistence] Could not read ${i}: ${t}. Seeding with empty content.`),a=``}let o=a7(t,a);!o.ok&&a.length>0&&Q5.warn({docName:t,path:i},`[config-persistence] loadConfigDoc seeding invalid content for ${t} into Y.Text — first mutation will revert to LKG`),e.transact(()=>{a.length>0&&r.insert(0,a)},rN),o.ok&&a.length>0?n.lkgCache.set(t,a):n.lkgCache.set(t,o7(t))}async function Wxe(e,t){await Uo(R(e),{recursive:!0});let n=`${e}.tmp.${crypto.randomUUID()}`;try{await Bo(n,t,`utf-8`),await as(n,e)}catch(e){try{Ko(n)}catch{}throw e}}async function Gxe(e,t,n,r){return ie(`config.persist`,{"config.scope":$5(t),"config.transport":`fs`},async i=>{let a=await qxe(e,t,n,r);return i.setAttribute(`config.outcome`,Kxe(a)),a})}function Kxe(e){return e===`reverted`?`reverted`:e===`write-failed`?`rejected`:`success`}async function qxe(e,t,n,r){if(r.ephemeral&&t===`__config__/okignore`||n===rN)return`no-op`;let i=e.getText(`source`),a=i.toString(),o=r.lkgCache.get(t);if(a.length===0&&(t!==`__config__/okignore`||o===void 0||o===``)||o!==void 0&&a===o)return`no-op`;let s=$5(t),c=Te(`config.validate`,{"config.scope":s,"config.validation.layer":`L3`},e=>{let n=a7(t,a);return e.setAttribute(`config.outcome`,n.ok?`success`:`rejected`),n.ok||n7(n.error),n});if(!c.ok)return await ie(`config.revert`,{"config.scope":s,"config.outcome":`reverted`},async()=>{let n=o??o7(t);e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},rN),o===void 0&&r.lkgCache.set(t,n),t===`__config__/okignore`&&le(c.error)&&t7().add(1,{"error.code":c.error.code}),r.onConfigRejected?.(t,c.error)}),`reverted`;let l=r7(t,r);try{await Uo(R(l),{recursive:!0})}catch(e){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] could not create parent dir for ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not create parent directory for ${l}: ${n}`}),`write-failed`}try{return await Yo(`${l}.lock`,async()=>{let n=null;try{n=U(l,`utf-8`)}catch(e){if(e.code!==`ENOENT`){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] could not read config for reconciliation: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Could not read config for reconciliation at ${l}: ${n}`}),`write-failed`}}if(n!==null&&o!==void 0&&n!==o){if(a7(t,n).ok)return e.transact(()=>{i.length>0&&i.delete(0,i.length),i.insert(0,n)},iN),r.lkgCache.set(t,n),Q5.info({docName:t,path:l},`[config-persistence] reconciled: external writer landed; imported disk into Y.Text`),`reconciled`;Q5.warn({docName:t,path:l},`[config-persistence] disk diverged from LKG but contains invalid content; proceeding with local write`)}try{await Wxe(l,a)}catch(e){let n=e instanceof Error?e.message:String(e);return Q5.warn({docName:t,path:l,err:e},`[config-persistence] write-failed at ${l}: ${n}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:`Failed to persist config at ${l}: ${n}`}),`write-failed`}return r.lkgCache.set(t,a),`persisted`},{onWarn:(e,t)=>{Q5.warn(t,`[config-persistence] ${e}`)}})}catch(e){if(e instanceof jo)return Q5.warn({docName:t,path:l,err:e},`[config-persistence] lock timeout at ${l}: ${e.message}`),r.onConfigRejected?.(t,{code:`WRITE_ERROR`,detail:e.message}),`write-failed`;throw e}}function s7(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);if(i!==void 0&&i===n)return`no-op`;let a=Te(`config.validate`,{"config.scope":$5(t),"config.validation.layer":`L3`},e=>{let r=a7(t,n);return e.setAttribute(`config.outcome`,r.ok?`success`:`rejected`),r.ok||n7(r.error),r});if(!a.ok)return t===`__config__/okignore`&&le(a.error)&&t7().add(1,{"error.code":a.error.code}),r.onConfigRejected?.(t,a.error),`rejected`;let o=e.getText(`source`);return e.transact(()=>{o.length>0&&o.delete(0,o.length),o.insert(0,n)},iN),r.lkgCache.set(t,n),`applied`}function c7(e,t,n,r){let i=Cj(B(r,z(n,e.file)));return i.startsWith(`..`)?!1:$S(i)===t}function Jxe(e){let{getSyncEngine:t,projectDir:n,contentDir:r}=e;return{async afterLoadDocument({documentName:e,document:i}){if(!(lC(e)||uC(e)))try{let a=t();if(!a)return;let o=a.getConflicts();if(o.length===0||!o.some(t=>c7(t,e,n,r)))return;let s=i.getMap(`lifecycle`);if(s.get(`status`)===`conflict`)return;s.set(`status`,`conflict`),s.set(`reason`,`conflict-markers`),console.warn(JSON.stringify({event:`lifecycle-seeded-on-load-from-conflict-store`,"doc.name":e}))}catch(t){L(`conflict-lifecycle-seed`).warn({docName:e,err:t instanceof Error?t:Error(String(t))},`failed to seed lifecycle on load (doc=${e})`)}}}}function Yxe(e,t,n){try{if(typeof t!=`string`||t.length===0||lC(e)||uC(e))return;let r=n.getLoadedDoc(e);if(r===void 0)throw gS(),Mo({"auth.reason":`doc-lineage-mismatch`}),new WZ(`doc-lineage-mismatch`,`doc lineage mismatch: claim against unloaded ${e} is stale by construction`);let i=r.getMap(`lifecycle`).get(fr);if(typeof i!=`string`||i.length===0||i!==t)throw gS(),Mo({"auth.reason":`doc-lineage-mismatch`}),new WZ(`doc-lineage-mismatch`,`doc lineage mismatch for ${e}: claimed epoch does not match the live lineage`)}catch(t){if(t instanceof WZ)throw t;lae(),console.warn(JSON.stringify({event:`doc-lineage-guard-error`,documentName:e,errorName:t instanceof Error?t.name:typeof t,message:t instanceof Error?t.message:String(t)}))}}var l7=class{reconciledBaseByBranch=new Map;inFlightFlushByDoc=new Map;agentWriteStores=new Set;storeFailures=new Map;storeDivergences=new Set;activeBranch;batchInProgress=!1;constructor(e=`main`){this.activeBranch=e,this.reconciledBaseByBranch.set(e,new Map)}switchReconciledBaseScope(e){this.activeBranch=e,this.reconciledBaseByBranch.has(e)||this.reconciledBaseByBranch.set(e,new Map)}getActiveBranch(){return this.activeBranch}getReconciledBase(e){return this.reconciledBaseByBranch.get(this.activeBranch)?.get(e)}setReconciledBase(e,t){let n=this.reconciledBaseByBranch.get(this.activeBranch);n||(n=new Map,this.reconciledBaseByBranch.set(this.activeBranch,n)),n.set(e,t)}deleteReconciledBase(e){this.reconciledBaseByBranch.get(this.activeBranch)?.delete(e)}beginInFlightFlush(e,t){this.inFlightFlushByDoc.set(e,t)}peekInFlightFlush(e){return this.inFlightFlushByDoc.get(e)}finishInFlightFlush(e,t){this.inFlightFlushByDoc.get(e)===t&&this.inFlightFlushByDoc.delete(e)}setBatchInProgress(e){this.batchInProgress=e}isBatchInProgress(){return this.batchInProgress}markAgentWriteStore(e){this.agentWriteStores.add(e)}consumeAgentWriteStore(e){return this.agentWriteStores.delete(e)}recordStoreFailure(e,t){this.storeFailures.set(e,t)}clearStoreFailure(e){this.storeFailures.delete(e)}takeStoreFailure(e){let t=this.storeFailures.get(e)??null;return this.storeFailures.delete(e),t}recordStoreDivergence(e){this.storeDivergences.add(e)}takeStoreDivergence(e){return this.storeDivergences.delete(e)}};const u7=L(`head-watcher`),Xxe=new Set([`HEAD`,`MERGE_HEAD`,`ORIG_HEAD`,`index.lock`]);function d7(e){let t=e.readHead();if(t.kind===`detached`)return{branch:`detached-${t.oid.slice(0,12)}`,oid:t.oid};if(t.kind!==`branch`)return{branch:null,oid:null};let n=e.readRef(t.ref),r=n.kind===`present`&&n.value.kind===`oid`?n.value.oid:null;return{branch:t.branch,oid:r}}function f7(e){let t=Ju(e);return t.kind===`repository`?d7(t.repository):{branch:null,oid:null}}function Zxe(e){let t=e.split(`/`).pop()??``;return Xxe.has(t)?t:null}async function Qxe(e,t){let n;try{n=await import(`@parcel/watcher`)}catch(e){return u7.debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher unavailable; falling back to chokidar`),null}try{let r=await n.subscribe(e,(e,n)=>{if(e){u7.warn({err:e},`[head-watcher] parcel subscription error`);return}for(let e of n)t(e.path)});return()=>r.unsubscribe()}catch(e){return u7.debug({err:e instanceof Error?e.message:String(e)},`[head-watcher] @parcel/watcher subscribe failed; falling back to chokidar`),null}}async function $xe(e,t){let{watch:n}=await import(`./chokidar-CVNrjmRM.mjs`),r=n(e,{ignoreInitial:!0,depth:0,followSymlinks:!1});return r.on(`all`,(e,n)=>t(n)),r.on(`error`,e=>{u7.warn({err:e},`[head-watcher] chokidar watcher error`)}),()=>r.close()}async function eSe(e,t,n,r={}){let i=Ju(e);if(i.kind!==`repository`)return{unsubscribe:async()=>{},getLastKnownBranch:()=>null};let a=i.repository,o=a.gitDir,s=!1,c=null,l=null,u=null,d=null,f=null;async function p(e){if(h&&await h,f){await f;return}if(!s)return;c&&=(clearTimeout(c),null),l&&=(clearTimeout(l),null);let t=d7(a),r=t.oid,i=u!==r,o=t.branch,p;p=o?.startsWith(`detached-`)?`detached-head`:d===o?`within-branch`:`cross-branch`;let m=d,g=Promise.resolve().then(async()=>{try{await n({headMoved:i,oldHead:u,newHead:r,timeout:e,batchKind:p,oldBranch:m,newBranch:o})}catch(e){u7.error({err:e},`onBatchEnd callback failed`)}finally{s=!1,u=r,d=o}});f=g;try{await g}finally{f===g&&(f=null)}}function m(){c&&clearTimeout(c),c=setTimeout(()=>{c=null,p(!1)},100)}let h=null;async function g(e){if(f&&await f,!s){s=!0,u===null&&(u=d7(a).oid);let n=(async()=>{try{await t({trigger:e})}catch(e){u7.error({err:e},`onBatchBegin callback failed`)}})();h=n,await n,h=null,l=setTimeout(()=>{l=null,p(!0)},3e4)}m()}let _=e=>{let t=Zxe(e);t!==null&&g(t)},v=null,y=`chokidar`;if(r.subscribeForTest?(v=await r.subscribeForTest(o,_),y=`test`):r.forceBackend!==`chokidar`&&(v=await Qxe(o,_),v&&(y=`parcel`)),!v){if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable for HEAD watching (forced backend)`);v=await $xe(o,_),y=`chokidar`}let b=v,x=d7(a);return u=x.oid,d=x.branch,u7.info({gitDir:o,backend:y},`watching for HEAD changes`),{unsubscribe:async()=>{s&&await p(!1),c&&clearTimeout(c),l&&clearTimeout(l),await b()},getLastKnownBranch:()=>d}}const tSe=100;function nSe(e){return typeof e!=`object`||!e?!1:e.source===`local`}function rSe(e){return e.getText(`source`).toString()}function p7(e){let{derivedDocumentIndex:t,onDocumentSettled:n,debounceMs:r=100}=e,i=new Map;function a(e){let t=i.get(e);t&&(clearTimeout(t.timer),i.delete(e))}function o(e,r,i){let a;try{a=rSe(r)}catch(t){return L(`live-derived-index`).error({docName:e,err:t},`Failed to update derived views for ${e}`),Promise.resolve()}return t.recordLiveDocument(e,a,i).then(()=>{n?.(e)}).catch(t=>{L(`live-derived-index`).error({docName:e,err:t},`Failed to update derived views for ${e}`)})}async function s(e){let t=i.get(e);t&&(clearTimeout(t.timer),i.delete(e),await o(e,t.document,t.token))}function c(e,t,n){a(e),i.set(e,{document:t,token:n,timer:setTimeout(()=>{i.delete(e),o(e,t,n)},r)})}return{async onChange({documentName:e,document:n,transactionOrigin:r}){if(hC(e)||nSe(r)&&r.context?.origin===`file-watcher`)return;let i=t.captureLiveUpdateToken();if(i===null){a(e);return}c(e,n,i)},async beforeUnloadDocument({documentName:e}){await s(e)},async onDestroy(){for(let{timer:e}of i.values())clearTimeout(e);i.clear()}}}const m7=L(`shadow-gc`);function iSe(e){let t=new Set;for(let n of e){let e=n.replace(/^refs\/wip\//,``),r=e.lastIndexOf(`/`);if(r<=0)continue;let i=e.slice(0,r);Ed(e.slice(r+1)).classification!==`unknown`&&t.add(i)}return t}async function aSe(e,t){try{return(await xs().env({GIT_DIR:e}).raw(`rev-parse`,`refs/heads/${t}`)).trim()}catch{return null}}async function oSe(e){let t=new Set;try{let n=(await xs().env({GIT_DIR:e}).raw(`for-each-ref`,`refs/heads/`,`--format=%(refname:short)`)).trim();if(n)for(let e of n.split(`
2015
2015
  `))e&&t.add(e)}catch(e){m7.warn({err:e},`[shadow-gc] listProjectBranches failed; treating as no project branches`)}return t}async function sSe(e,t,n=KS,r=`.`){let i={deletedBranches:[],renamedBranches:[],retainedBranches:[],checkpointGc:{},deletedStaleSessionRefs:0},a=OS(e,{timeoutMs:DS}),o;try{o=(await a.raw(`for-each-ref`,`refs/wip/`,`--format=%(refname)`)).trim()}catch{return i}if(!o)return i;let s=o.split(`
2016
2016
  `).filter(Boolean),c=iSe(s),l=await oSe(t),u=[];for(let e of c)e.startsWith(`detached-`)||(l.has(e)?i.retainedBranches.push(e):u.push(e));if(u.length!==0){let e=new Set;for(let t of l)c.has(t)||e.add(t);for(let n of u){let r=!1;if(e.size>0){let o=null;for(let e of s)if(e.startsWith(`refs/wip/${n}/`))try{o=(await a.raw(`rev-parse`,e)).trim();break}catch{}if(o){for(let c of e)if(await aSe(t,c)===o){let t=s.filter(e=>e.startsWith(`refs/wip/${n}/`));for(let e of t){let t=`refs/wip/${c}/${e.slice(`refs/wip/${n}/`.length)}`;try{let n=(await a.raw(`rev-parse`,e)).trim();await a.raw(`update-ref`,t,n),await a.raw(`update-ref`,`-d`,e)}catch(n){m7.error({err:n,oldRef:e,newRef:t},`[shadow-gc] failed to migrate WIP ref`)}}i.renamedBranches.push({from:n,to:c}),e.delete(c),r=!0;break}}}if(!r){let e=s.filter(e=>e.startsWith(`refs/wip/${n}/`));for(let t of e)try{let e=(await a.raw(`log`,`-1`,`--format=%ci`,t)).trim(),r=new Date(e).getTime();if(Date.now()-r<864e5){i.retainedBranches.push(n);break}await a.raw(`update-ref`,`-d`,t)}catch{}i.retainedBranches.includes(n)||i.deletedBranches.push(n)}}}let d=new Set([...l,...i.retainedBranches]);for(let t of d)try{let r=await qS(e,t,n);(r.scanned>0||r.deletedBridgeMergeLoss>0||r.deletedExternalChangeRescue>0||r.deletedAutoConsolidation>0)&&(i.checkpointGc[t]={scanned:r.scanned,deletedBridgeMergeLoss:r.deletedBridgeMergeLoss,deletedExternalChangeRescue:r.deletedExternalChangeRescue,deletedAutoConsolidation:r.deletedAutoConsolidation,retained:r.retained})}catch(e){m7.warn({err:e,branch:t},`[shadow-gc] checkpoint GC failed`)}try{await Vq(e,Cq(e.gitDir))}catch(e){m7.warn({err:e},`[shadow-gc] rename-log GC failed`)}let f=Date.now();for(let t of l){let n=await kS(e,t),a=[];for(let e of n)if(!(e.classification===`classified-file-system`||e.classification===`classified-git-upstream`||e.classification===`classified-git-author`||e.classification===`classified-openknowledge-service`)){if(e.classification===`unknown`){m7.warn({branch:t,writerId:e.writerId},`[shadow-gc] unknown writer id in active branch ref — preserved`);continue}if(e.classification===`agent`||e.classification===`principal`){if(e.isPark)continue;e.committedAtMs>0&&f-e.committedAtMs>=2592e6&&a.push({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})}}if(a.length>0)try{await JS(e,r,a,t,void 0,{checkpointKind:{foldedRefs:a.length,trigger:`ttl`},includeUpstream:!1,timeoutMs:DS}),i.deletedStaleSessionRefs+=a.length}catch(e){m7.warn({err:e,branch:t},`[shadow-gc] TTL consolidation failed`)}}return i}let h7=null,g7=null,_7=null;function cSe(){return h7||=ls().createHistogram(`ok.shadow.maintenance.run_duration_ms`,{description:`Wall-clock duration of one maintenance op. Bounded labels: op ∈ {gc, consolidation, reap}, outcome ∈ {ok, skipped, error}.`,unit:`ms`}),h7}function lSe(){return g7||=ls().createCounter(`ok.shadow.maintenance.gc_latch_total`,{description:`Distinct gc.log latch EPISODES (counted on the absent→present transition, not per observation, so one persistent ~1-day latch counts once). A latch means auto-gc is silently disabled until it self-expires; a nonzero rate means a repo is re-degrading invisibly.`}),g7}function uSe(){return _7||=ls().createCounter(`ok.shadow.maintenance.consolidation_total`,{description:`Auto-consolidation runs that folded ≥1 dead chain. Bounded label: trigger ∈ {dead-chain, session-close, boot, ttl}. Width before/after ride the structured log, not metric labels.`}),_7}function v7(e,t,n){cSe().record(Math.max(0,n),{op:e,outcome:t})}function dSe(){lSe().add(1)}function fSe(e){uSe().add(1,{trigger:e})}async function y7(e){let t=await OS(e).raw(`count-objects`,`-v`),n=new Map;for(let e of t.split(`
2017
2017
  `)){let t=e.indexOf(`:`);if(t<0)continue;let r=e.slice(0,t).trim(),i=Number.parseInt(e.slice(t+1).trim(),10);r&&n.set(r,Number.isFinite(i)?i:0)}return{looseObjects:n.get(`count`)??0,looseKiB:n.get(`size`)??0,packfiles:n.get(`packs`)??0,packedObjects:n.get(`in-pack`)??0}}function b7(e){return H(V(e.gitDir,`gc.log`))}async function x7(e,t){let n=OS(e),r=t?`refs/wip/${t}/`:`refs/wip/`;try{return(await n.raw(`for-each-ref`,`--format=%(refname)`,r)).trim().split(`
2018
2018
  `).filter(Boolean).length}catch{return 0}}async function pSe(e,t){let n=OS(e),r;try{r=(await n.raw(`for-each-ref`,`--format=%(refname)%00%(committerdate:unix)%00%(contents:subject)`,`refs/wip/`)).trim().split(`
2019
- `).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||Ed(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const S7=L(`shadow-maintenance`),mSe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),hSe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function C7(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function w7(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var gSe=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){C7()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(C7()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),n,r=new Promise(t=>{n=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),r]),n&&clearTimeout(n),t.catch(e=>{S7.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(C7()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(C7()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await sSe(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),v7(`reap`,`ok`,performance.now()-n)}catch(t){v7(`reap`,`error`,performance.now()-n),S7.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(C7()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<hSe)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<mSe)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await x7(r,i);await JS(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:w7(e)},timeoutMs:DS}),this.lastConsolidationAt=Date.now();let s=await x7(r,i);return fSe(w7(e)),S7.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return S7.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await kS(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(C7())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return v7(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?wS(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await y7(t);await OS(t,{timeoutMs:DS}).raw(`gc`,`--auto`);let i=await y7(t),a=b7(t),o=performance.now()-n;return v7(`gc`,`ok`,o),a&&(this.lastGcLatch||dSe(),S7.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,S7.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return v7(`gc`,`error`,performance.now()-n),S7.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function _Se(e){return new gSe(e)}const vSe={depth:1,acceptLeaf:e=>kl(e)===`SKILL.md`},ySe={depth:0,acceptLeaf:e=>kl(e).endsWith(`.md`)};async function T7(e,t,n=vSe,r){let i=L(`managed-artifact-watcher`),{watch:a}=await import(`./chokidar-BCS--vwu.mjs`),o=Array.from(new Set(e));for(let e of o)try{Zo(e,{recursive:!0})}catch(t){Vs(t)!==`EEXIST`&&i.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let s=a(o,{ignoreInitial:!0,depth:n.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{s.once(`ready`,e)});let c=new Map,l=e=>{if(!n.acceptLeaf(e))return;let r;try{r=U(e,`utf-8`)}catch(t){if(Vs(t)===`ENOENT`){i.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}i.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(r!==c.get(e)){c.set(e,r);try{t(e,r)}catch(t){i.warn({err:t,path:e},`managed-artifact change handler threw`)}}},u=e=>l(e);s.on(`add`,u),s.on(`change`,u),s.on(`unlink`,e=>{if(n.acceptLeaf(e)&&(c.delete(e),i.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`),r))try{r(e)}catch(t){i.warn({err:t,path:e},`managed-artifact unlink handler threw`)}}),s.on(`error`,e=>{i.warn({err:e,watchRoots:o},`[managed-artifact-watcher] chokidar error`)});let d=!1;return async()=>{d||(d=!0,await s.close())}}const E7=L(`mermaid-persistence`),D7={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function O7(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=V(t,oC(e));if(!wj(n,t))throw Error(`Invalid document name: ${e}`);return n}function k7(e,t,n){let r=e.getText(`source`);e.transact(()=>{r.length>0&&r.delete(0,r.length),t.length>0&&r.insert(0,t),n&&e.getMap(`lifecycle`).set(fr,crypto.randomUUID())},D7)}function bSe(e,t,n){if(e.getText(`source`).length>0)return;let r=O7(t,n.contentDir);if(!H(r))return;let i;try{i=U(r,`utf-8`)}catch(e){E7.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}k7(e,i,!0),n.lkgCache.set(t,i)}async function xSe(e,t,n,r){if(n===D7)return`no-op`;let i=e.getText(`source`).toString(),a=r.lkgCache.get(t);if(i===a)return`no-op`;let o=O7(t,r.contentDir);try{if(await Uo(V(o,`..`),{recursive:!0}),H(o)){let n=null;try{n=U(o,`utf-8`)}catch(e){e.code!==`ENOENT`&&E7.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==a&&n!==i)return k7(e,n,!1),r.lkgCache.set(t,n),`reconciled`}return await Io(o,i,{fs:Vo}),r.lkgCache.set(t,i),`persisted`}catch(e){return E7.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function A7(e){let{body:t}=bi(e);return hi(t).trim()}function SSe(e){return e===` `||e===`
2019
+ `).filter(Boolean)}catch{return 0}let i=0;for(let e of r){let[n=``,r=``,a=``]=e.split(`\0`);if(a.startsWith(`park:`))continue;let o=n.split(`/`).slice(3).join(`/`);if(!o||Ed(o).classification!==`agent`)continue;let s=Number.parseInt(r,10);Number.isFinite(s)&&s*1e3<t&&(i+=1)}return i}const S7=L(`shadow-maintenance`),mSe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_DEAD_CHAIN_THRESHOLD;if(!e)return 5;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:5})(),hSe=(()=>{let e=process.env.OK_SHADOW_MAINTENANCE_CONSOLIDATION_SPACING_MS;if(!e)return 600*1e3;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:600*1e3})();function C7(){return process.env.OK_SHADOW_MAINTENANCE_DISABLED===`1`}function w7(e){return e===`boot`?`boot`:e===`session-close`?`session-close`:e===`ttl`?`ttl`:`dead-chain`}var gSe=class{running=!1;destroyed=!1;flushCommitCounter=0;lastConsolidationAt=0;lastGcLatch=!1;constructor(e){this.deps=e}get isRunning(){return this.running}destroy(){this.destroyed=!0}noteFlushCommit(){C7()||this.destroyed||(this.flushCommitCounter+=1,this.flushCommitCounter>=200&&(this.flushCommitCounter=0,this.runScheduledMaintenance(`flush-counter`)))}async runBootMaintenance(e=1e3){if(C7()||this.destroyed)return;let t=this.runScheduledMaintenance(`boot`),n,r=new Promise(t=>{n=setTimeout(t,e)});await Promise.race([t.then(()=>void 0),r]),n&&clearTimeout(n),t.catch(e=>{S7.warn({err:e},`[shadow-maintenance] boot maintenance background continuation failed`)})}async onSessionClose(){await this.runScheduledMaintenance(`session-close`)}async runScheduledMaintenance(e){if(!(C7()||this.destroyed)&&!this.running){this.running=!0;try{await this.consolidateInner(e),await this.reapInner(e),await this.gcInner(e)}finally{this.running=!1}}}async runReap(e){if(!(C7()||this.destroyed)&&!this.running){this.running=!0;try{await this.reapInner(e)}finally{this.running=!1}}}async reapInner(e){if(!this.deps.projectGitDir)return;let t=this.deps.getShadow();if(!t)return;let n=performance.now();try{await sSe(t,this.deps.projectGitDir,void 0,this.deps.contentRoot??`.`),v7(`reap`,`ok`,performance.now()-n)}catch(t){v7(`reap`,`error`,performance.now()-n),S7.warn({trigger:e,err:t},`[shadow-maintenance] reap failed; retrying next trigger`)}}async consolidateDeadChains(e){if(C7()||this.destroyed)return{consolidated:!1,skipped:`disabled`};if(this.running)return{consolidated:!1,skipped:`busy`};this.running=!0;try{return await this.consolidateInner(e)}finally{this.running=!1}}async consolidateInner(e){let{getCurrentBranch:t,isWriterLive:n}=this.deps;if(!t||!n)return{consolidated:!1,skipped:`unconfigured`};if(Date.now()-this.lastConsolidationAt<hSe)return{consolidated:!1,skipped:`spacing`};let r=this.deps.getShadow();if(!r)return{consolidated:!1,skipped:`no-shadow`};try{let i=t()??`main`,a=await this.findDeadAgentChains(r,i,n);if(a.length<mSe)return{consolidated:!1,skipped:`below-threshold`,deadChains:a.length};let o=await x7(r,i);await JS(r,this.deps.contentRoot??``,a,i,void 0,{checkpointKind:{foldedRefs:a.length,trigger:w7(e)},timeoutMs:DS}),this.lastConsolidationAt=Date.now();let s=await x7(r,i);return fSe(w7(e)),S7.info({trigger:e,branch:i,foldedChains:a.length,widthBefore:o,widthAfter:s},`[shadow-maintenance] auto-consolidation folded dead agent chains`),{consolidated:!0,deadChains:a.length,widthBefore:o,widthAfter:s}}catch(t){return S7.warn({trigger:e,err:t},`[shadow-maintenance] consolidation failed; retrying next trigger`),{consolidated:!1,skipped:`error`}}}async findDeadAgentChains(e,t,n){return(await kS(e,t)).filter(e=>e.classification===`agent`&&!e.isPark&&!n(e.writerId)).map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`}))}async runGc(e){if(C7())return{ran:!1,skipped:`disabled`};if(this.destroyed)return{ran:!1,skipped:`no-shadow`};if(this.running)return v7(`gc`,`skipped`,0),{ran:!1,skipped:`busy`};this.running=!0;try{return await this.gcInner(e)}finally{this.running=!1}}async gcInner(e){let t=this.deps.getShadow();return t?wS(t).withExclusive(()=>this.gcRun(e,t)):{ran:!1,skipped:`no-shadow`}}async gcRun(e,t){let n=performance.now();try{let r=await y7(t);await OS(t,{timeoutMs:DS}).raw(`gc`,`--auto`);let i=await y7(t),a=b7(t),o=performance.now()-n;return v7(`gc`,`ok`,o),a&&(this.lastGcLatch||dSe(),S7.warn({trigger:e,looseObjects:i.looseObjects},`[shadow-maintenance] gc.log latch present — auto-gc disabled until it self-expires (~1 day); retrying next trigger`)),this.lastGcLatch=a,S7.info({trigger:e,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfiles:i.packfiles,durationMs:Math.round(o)},`[shadow-maintenance] gc complete`),{ran:!0,looseBefore:r.looseObjects,looseAfter:i.looseObjects,packfilesAfter:i.packfiles,latch:a,durationMs:o}}catch(t){return v7(`gc`,`error`,performance.now()-n),S7.warn({trigger:e,err:t},`[shadow-maintenance] gc failed; retrying next trigger`),{ran:!1,skipped:`error`}}}};function _Se(e){return new gSe(e)}const vSe={depth:1,acceptLeaf:e=>kl(e)===`SKILL.md`},ySe={depth:0,acceptLeaf:e=>kl(e).endsWith(`.md`)};async function T7(e,t,n=vSe,r){let i=L(`managed-artifact-watcher`),{watch:a}=await import(`./chokidar-CVNrjmRM.mjs`),o=Array.from(new Set(e));for(let e of o)try{Zo(e,{recursive:!0})}catch(t){Vs(t)!==`EEXIST`&&i.warn({err:t,dir:e},`failed to create watch root; watcher may be inert`)}let s=a(o,{ignoreInitial:!0,depth:n.depth,usePolling:!0,interval:200,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});await new Promise(e=>{s.once(`ready`,e)});let c=new Map,l=e=>{if(!n.acceptLeaf(e))return;let r;try{r=U(e,`utf-8`)}catch(t){if(Vs(t)===`ENOENT`){i.debug({path:e},`managed-artifact leaf disappeared between event and read; dropping`);return}i.warn({err:t,path:e},`managed-artifact leaf read failed; dropping event`);return}if(r!==c.get(e)){c.set(e,r);try{t(e,r)}catch(t){i.warn({err:t,path:e},`managed-artifact change handler threw`)}}},u=e=>l(e);s.on(`add`,u),s.on(`change`,u),s.on(`unlink`,e=>{if(n.acceptLeaf(e)&&(c.delete(e),i.debug({path:e},`managed-artifact leaf unlinked; live doc retained at current state`),r))try{r(e)}catch(t){i.warn({err:t,path:e},`managed-artifact unlink handler threw`)}}),s.on(`error`,e=>{i.warn({err:e,watchRoots:o},`[managed-artifact-watcher] chokidar error`)});let d=!1;return async()=>{d||(d=!0,await s.close())}}const E7=L(`mermaid-persistence`),D7={source:`local`,skipStoreHooks:!0,context:{origin:`mermaid-source`}};function O7(e,t){if(e.includes(`\0`))throw Error(`Invalid document name: ${e}`);let n=V(t,oC(e));if(!wj(n,t))throw Error(`Invalid document name: ${e}`);return n}function k7(e,t,n){let r=e.getText(`source`);e.transact(()=>{r.length>0&&r.delete(0,r.length),t.length>0&&r.insert(0,t),n&&e.getMap(`lifecycle`).set(fr,crypto.randomUUID())},D7)}function bSe(e,t,n){if(e.getText(`source`).length>0)return;let r=O7(t,n.contentDir);if(!H(r))return;let i;try{i=U(r,`utf-8`)}catch(e){E7.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}k7(e,i,!0),n.lkgCache.set(t,i)}async function xSe(e,t,n,r){if(n===D7)return`no-op`;let i=e.getText(`source`).toString(),a=r.lkgCache.get(t);if(i===a)return`no-op`;let o=O7(t,r.contentDir);try{if(await Uo(V(o,`..`),{recursive:!0}),H(o)){let n=null;try{n=U(o,`utf-8`)}catch(e){e.code!==`ENOENT`&&E7.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==a&&n!==i)return k7(e,n,!1),r.lkgCache.set(t,n),`reconciled`}return await Io(o,i,{fs:Vo}),r.lkgCache.set(t,i),`persisted`}catch(e){return E7.warn({documentName:t,err:e},`store: write failed`),`write-failed`}}function A7(e){let{body:t}=bi(e);return hi(t).trim()}function SSe(e){return e===` `||e===`
2020
2020
  `||e===` `||e===`\r`}function CSe(e,t){let n=A7(t);if(n.length===0)return{kind:`allow`,reason:`empty-base`};let r=A7(e);if(r===n)return{kind:`allow`,reason:`identical`};if(r.length<n.length*2)return{kind:`allow`,reason:`too-short`};let i=0,a=0;for(;i<r.length;){if(r.slice(i,i+n.length)!==n)return{kind:`allow`,reason:`not-integer-multiple`};for(i+=n.length,a++;i<r.length&&SSe(r[i]??``);)i++}return a>=2?{kind:`block`,reason:`structural-duplication`,copies:a}:{kind:`allow`,reason:`single-copy`}}const j7=L(`persistence`);var wSe=class extends Error{docName;size;limit;constructor(e,t,n=zt){super(`Document "${e}" is ${tn(t)}; OpenKnowledge opens documents up to ${tn(n)}.`),this.name=`DocumentOpenSizeLimitError`,this.docName=e,this.size=t,this.limit=n}};function M7(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.source===`local`){let e=n.context;if(!e)return null;if(typeof e.session_id==`string`){let t=e.session_id;return{id:`agent-${t}`,name:`Agent (${t.slice(0,8)})`,email:`agent-${t}@openknowledge.local`}}return e.origin===`file-watcher`?LS:e.origin===`upstream-import`||e.origin===`git-upstream`?RS:zS}if(n.source===`connection`){let e=n.connection?.context;if(typeof e?.principalId==`string`){let n=e.principalId,r=t?.();return r&&r.id===n&&r.display_name&&r.display_email?{id:r.id,name:r.display_name,email:r.display_email}:{id:n,name:`Local User`,email:`${n}@openknowledge.local`}}return zS}return null}const TSe=new Set([`EACCES`,`EBADF`,`EBUSY`,`EEXIST`,`EISDIR`,`ELOOP`,`EMFILE`,`ENFILE`,`ENOENT`,`ENOSPC`,`ENOTDIR`,`EPERM`,`EROFS`,`ETXTBSY`,`EXDEV`]);function ESe(e){if(typeof e!=`object`||!e)return`unknown`;let t=e,n=typeof t.message==`string`?t.message:``;return n.startsWith(`symlink-escape:`)?`disk-write`:typeof t.code==`string`&&TSe.has(t.code)?n.includes(`rename`)?`traced-rename`:`disk-write`:e instanceof lo?`serialize`:`unknown`}function DSe(e){return{sv:ly(e),json:Hx(e.getXmlFragment(`default`),ko).toJSON()}}function N7(e){let{frontmatter:t,body:n}=bi(e);return hi(Oi(t,n))}function P7(e){let t;try{let n=e?.code;typeof n==`string`&&(t=n)}catch{}let n=`unknown store error`;try{n=e instanceof Error?e.message:String(e)}catch{}return{code:t,message:n}}function F7(e){let t=e?.durabilityState??new l7,n=e?.contentDir??process.cwd(),r;try{r=W(n)}catch{r=n}let i=e?.projectDir??process.cwd(),a=e?.shadowRef,o=e?.contentRoot??(Cj(B(i,r))||`.`),s=e?.derivedDocumentIndex,c=e?.getPrincipal,l=e?.onAgentCommit,u=e?.onFlushCommit,d=e?.onDiskFlush,f=e?.onConfigPersisted,p=e?.mdManager??Ao,m=e?.ephemeral??!1,h={projectDir:i,contentDir:r,lkgCache:new Map,homedirOverride:e?.configHomedirOverride,onConfigRejected:e?.onConfigRejected,ephemeral:m},g=new Map,_={projectDir:i,homedirOverride:e?.configHomedirOverride,lkgCache:g,setReconciledBase:(e,n)=>t.setReconciledBase(e,n),getReconciledBase:e=>t.getReconciledBase(e),beforeReconcileDivergence:(e,t,n,r)=>be(e,t,n,r)},v={contentDir:r,lkgCache:new Map},y=new Set,b=new Set,x=e?.applyDiskContentToDoc??MH,S=null,C=new Map,w=e?.gitEnabled??!0,T=e?.commitDebounceMs??15e3,ee=e?.wipRef??`refs/wip/main`,te=e?.getCurrentBranch,ne=null,re=0,ie=null,E=!1,D=null,ae=new Map;async function O(){Se();let e=Date.now();return zo(`persistence.commitToWipRef`,void 0,async()=>await oe()).finally(()=>{xe?.record((Date.now()-e)/1e3)})}async function oe(){let e=a?.current;if(e){let t=cF(),n=te?.()??`main`;if(t.size===0){let t={v:1,writer_id:zS.id,principal:null,agent_session:null,agent_type:null,client_name:null,client_version:null,label:null,display_name:zS.name,color_seed:zS.id,docs:[]},r=`${bd([])}\n\n${md(t)}`;try{let t=await MS(e,zS,o,r,n);re=0,j7.info({sha:t.slice(0,8),writer:zS.id},`[persistence] Shadow WIP commit: ${t.slice(0,8)} on refs/wip/${zS.id}`);try{zq(e.gitDir,zS.id,t,Cq(e.gitDir))}catch(e){j7.warn({err:e},`[rename-log] service-writer backfill failed`)}}catch(e){re++,sS(),j7.error({err:e,attempt:re},`[persistence] Shadow commit failed (attempt ${re})`),re>=3&&j7.error({err:e,attempt:re},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}return}let r;try{r=await PS(e,o)}catch(e){lF(t),re++,sS(),j7.error({err:e,attempt:re},`[persistence] Shadow WIP tree build failed (attempt ${re})`);return}let i=!1;for(let[a,o]of t){let t={id:a,name:o.displayName,email:`${a}@openknowledge.local`},s=[...o.docs],c=o.actor,d=[...o.summaries],f=[...o.previousPaths],p={v:1,writer_id:a,principal:c?.principalId??null,agent_session:a.startsWith(`agent-`)?a.slice(6):null,agent_type:c?.agentType??null,client_name:c?.clientName??null,client_version:c?.clientVersion??null,label:c?.label??null,display_name:o.displayName,color_seed:o.colorSeed,docs:s,...d.length>0?{summaries:d}:{},...f.length>0?{previous_paths:f}:{}},m=`${Ste(o.subjectOverride??bd(s),d)}\n\n${md(p)}`;try{let o=await IS(e,t,r,m,n);i=!0;try{u?.()}catch(e){j7.warn({err:e},`[persistence] onFlushCommit callback failed (non-fatal)`)}j7.info({sha:o.slice(0,8),writer:a,tree:r.slice(0,8)},`[persistence] Shadow WIP commit: ${o.slice(0,8)} on refs/wip/${a}`);try{zq(e.gitDir,a,o,Cq(e.gitDir))}catch(e){j7.warn({err:e},`[rename-log] backfill failed; will retry next commit`)}a.startsWith(`agent-`)&&l?.()}catch(e){rce(a,o),oie(),j7.error({err:e,writer:a},`[persistence] Per-writer shadow commit failed for ${a}`)}}i?re=0:(re++,sS(),re>=3&&j7.error({attempt:re},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`));return}let t=OS({gitDir:V(i,`.git`),workTree:i}),n=V(i,`.git/index-wip`),r={GIT_INDEX_FILE:n};try{try{let e=(await t.raw(`rev-parse`,`HEAD^{tree}`)).trim();await t.env(r).raw(`read-tree`,e)}catch(e){let t=e instanceof Error?e.message:String(e);t.includes(`unknown revision`)||t.includes(`bad revision`)?j7.info({},`[persistence] Empty repo — starting with empty index`):j7.error({err:e},`[persistence] Failed to read HEAD tree, falling back to empty index`)}await t.env(r).raw(`add`,o);let e=(await t.env(r).raw(`write-tree`)).trim(),n=null;try{n=(await t.raw(`rev-parse`,ee)).trim()}catch(e){let t=e instanceof Error?e.message:String(e);if(!t.includes(`unknown revision`)&&!t.includes(`bad revision`))throw e}let i=[`commit-tree`,e,`-m`,`WIP auto-save ${new Date().toISOString()}`];n&&i.push(`-p`,n);let a=(await t.raw(...i)).trim();await t.raw(`update-ref`,ee,a),re=0,j7.info({sha:a.slice(0,8),wipRef:ee},`[persistence] Git commit: ${a.slice(0,8)} on ${ee}`)}catch(e){re++,sS(),j7.error({err:e,attempt:re},`[persistence] Git commit failed (attempt ${re})`),re>=3&&j7.error({err:e,attempt:re},`[persistence] CRITICAL: Git auto-save has failed 3+ times. Version history is NOT being recorded.`)}finally{try{Ko(n)}catch{}}}function se(e){if(e<=0)return T;let t=2**Math.min(e,5),n=Math.random()*.25*T;return T*t+n}function k(){w&&(t.isBatchInProgress()||(ne&&clearTimeout(ne),ne=setTimeout(()=>{if(ne=null,ie){E=!0;return}ie=O().finally(()=>{ie=null,E&&(E=!1,k())})},se(re))))}async function ce(){ne&&(clearTimeout(ne),ne=null,ie||=O().finally(()=>{ie=null,E&&(E=!1,k())})),ie&&await ie}function le(t,n){try{let{frontmatter:r,body:i}=bi(t),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:n}:void 0,o=p.parseWithFallback(i,a);return hi(Oi(r,p.serialize(o)))}catch(e){return j7.debug({err:e,documentName:n},`[g8] ephemeral canonical baseline failed; falling through to write`),null}}function ue(t,n,r){try{let i=t.getXmlFragment(`default`),a=e?.resolveEmbed?{resolveEmbed:e.resolveEmbed,resolveSize:e?.resolveSize,sourcePath:r}:void 0,o=Ao.parseWithFallback(n,a),s=ko.nodeFromJSON(o);t.transact(()=>{Bx(t,i,s,{mapping:new Map,isOMark:new Map})},lT)}catch(e){$ie(),j7.warn({err:e,documentName:r},`[persistence] reconcileFragmentNow failed for ${r}`)}}let de=`persistence-prewrite`,fe=`persistence-duplication-reset`,A=`persistence-divergence-realign`,pe=`managed-artifact-reconcile`,j=new WeakMap;function me(t,n){Iie(),e?.getLossRing?.()?.record({event:`persistence-hold`,docName:t,writerId:null,direction:`b`,site:de,lostLen:n.reduce((e,t)=>e+t.length,0)})}function he(t,n,r,i,s){if(Lie(),j.get(t)===r){zie();return}j.set(t,r);let c=$a(r,i,``),l=c.reduce((e,t)=>e+t.length,0),u=e?.getLossRing?.(),d=a?.current;if(!d){u?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:de,lostLen:l});return}let f=te?.()??`main`;queueMicrotask(()=>{WS(d,o,{kind:`persistence-reconcile-loss`,docName:n,contents:r,label:`Before persistence fragment rebuild @ ${new Date().toISOString()}`,branch:f,metadata:{atRiskLines:c.length,witnessAvailable:s}}).then(e=>{Rie(),u?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:de,lostLen:l,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-reconcile-loss-checkpoint-created`,docName:n,sha:e,kind:`persistence-reconcile-loss`,timestamp:new Date().toISOString()}))}).catch(e=>{j.get(t)===r&&j.delete(t);let i=e instanceof Error?e:Error(String(e));j7.warn({documentName:n,err:i},`[persistence] reconcile-loss checkpoint write failed`)})})}let ge=new WeakMap;function _e(t,n,r,i,s){Bie();let c=e?.getLossRing?.(),l=a?.current;if(!l){c?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length});return}if(ge.get(t)===r){Hie();return}ge.set(t,r);let u=te?.()??`main`;queueMicrotask(()=>{WS(l,o,{kind:`persistence-duplication-reset`,docName:n,contents:r,label:`Before duplication reset @ ${new Date().toISOString()}`,branch:u,metadata:{copies:i,fragmentChildren:s}}).then(e=>{Vie(),c?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:fe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-duplication-reset-checkpoint-created`,docName:n,sha:e,kind:`persistence-duplication-reset`,timestamp:new Date().toISOString()}))}).catch(e=>{ge.get(t)===r&&ge.delete(t);let i=e instanceof Error?e:Error(String(e));j7.warn({documentName:n,err:i},`[persistence] duplication-reset checkpoint write failed`)})})}let M=new WeakMap;function ve(t,n,r,i){Wie();let s=e?.getLossRing?.(),c=a?.current;if(!c){s?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:A,lostLen:r.length});return}if(M.get(t)===r){Kie();return}M.set(t,r);let l=te?.()??`main`;queueMicrotask(()=>{WS(c,o,{kind:`persistence-divergence-realign`,docName:n,contents:r,label:`Before divergence realign @ ${new Date().toISOString()}`,branch:l,metadata:{diskBytes:i.length,discardedBytes:r.length}}).then(e=>{Gie(),s?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:A,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`persistence-divergence-realign-checkpoint-created`,docName:n,sha:e,kind:`persistence-divergence-realign`,timestamp:new Date().toISOString()}))}).catch(e=>{M.get(t)===r&&M.delete(t);let i=e instanceof Error?e:Error(String(e));j7.warn({documentName:n,err:i},`[persistence] divergence-realign checkpoint write failed`)})})}let ye=new WeakMap;function be(t,n,r,i){let s=e?.getLossRing?.(),c={baselineFullMd:i,report:e=>{try{let t=YS(e);if(t.length===0)return;s?.record({event:Yx,docName:n,writerId:LS.id,direction:`b`,site:pe,lostLen:t.reduce((e,t)=>e+t.length,0),digest:nt(t.join(`
2021
2021
  `))})}catch(e){j7.warn({documentName:n,err:e},`[persistence] managed-artifact reconcile loss detection failed`)}}},l=wK(n),u=a?.current;if(!u||!l.managed||!l.versioned)return s?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length}),c;if(ye.get(t)===r)return Yie(),c;ye.set(t,r);let d=te?.()??`main`,f=l.docKey;return queueMicrotask(()=>{WS(u,o,{kind:`managed-artifact-reconcile`,docName:f,contents:r,label:`Before artifact reconcile @ ${new Date().toISOString()}`,branch:d,metadata:{diskBytes:i.length,discardedBytes:r.length}}).then(e=>{Jie(),s?.record({event:Zx,docName:n,writerId:null,direction:`b`,site:pe,lostLen:r.length,checkpointSha:e}),console.warn(JSON.stringify({event:`managed-artifact-reconcile-checkpoint-created`,docName:n,sha:e,kind:`managed-artifact-reconcile`,timestamp:new Date().toISOString()}))}).catch(e=>{ye.get(t)===r&&ye.delete(t);let i=e instanceof Error?e:Error(String(e));j7.warn({documentName:n,err:i},`[persistence] managed-artifact reconcile checkpoint write failed`)})}),c}let N=null,P=null,xe=null;function Se(){if(N)return;let e=ls();N=e.createHistogram(`ok.persistence.load.duration`,{description:`Duration of persistence.onLoadDocument in seconds`,unit:`s`}),P=e.createHistogram(`ok.persistence.store.duration`,{description:`Duration of persistence.onStoreDocument in seconds`,unit:`s`}),xe=e.createHistogram(`ok.persistence.git_commit.duration`,{description:`Duration of commitToWipRef drain in seconds`,unit:`s`})}async function Ce({document:n,documentName:i,lastTransactionOrigin:a}){Se();let o=Date.now(),l;return zo(`persistence.onStoreDocument`,{attributes:{"doc.name":i}},async()=>{let o=t.consumeAgentWriteStore(i),u=OC(n);if(u!==null){j7.info({documentName:i,lifecycleStatus:u},`[persistence] Skipped store for ${i}: lifecycle=${u}`),C.delete(i),y.delete(i);return}if(!_w(n)){let e=C.get(i)??0;if(e<8){let t=vw(n);console.warn(JSON.stringify({event:`persistence-skip-non-quiescent`,"doc.name":i,wallClockMsSinceLastTransaction:t??null,deferCount:e})),bie(),C.set(i,e+1);return}console.warn(JSON.stringify({event:`persistence-force-flush-during-burst`,"doc.name":i,wallClockMsSinceLastTransaction:vw(n)??null,deferCount:e})),xie()}let{sv:f,json:h}=DSe(n),g=n.getText(`source`).toString(),{frontmatter:_,body:v}=bi(g),S=Oi(_,v),w,T=null;try{T=Oi(_,p.serialize(h)),w=Lw(S,T,{site:`persistence`,docName:i,suppressDevThrow:!0,canonicalizeBody:Fw(p,{resolveEmbed:e?.resolveEmbed,resolveSize:e?.resolveSize,docName:i})})}catch(e){rae(),console.warn(JSON.stringify({event:`persistence-sanity-check-serialize-failed`,"doc.name":i,"error.type":e instanceof Error?e.constructor.name:typeof e,timestamp:new Date().toISOString()})),j7.warn({err:e,documentName:i},`[persistence] Sanity-check serialize failed for ${i}; proceeding with ytext bytes`),T=null,w=!1}if(!w){let e=T===null?void 0:goe(n);T!==null&&e!==void 0&&Tr(T,S,e)?me(i,$a(T,S,e)):(T!==null&&he(n,i,T,S,e!==void 0),ue(n,v,i))}let ee=t.getReconciledBase(i),te=N7(g),ne=ee!==void 0&&te===hi(ee)&&!Ya(ee,S);if(!ne&&m&&ee!==void 0){let e=le(ee,i);e!==null&&te===e&&(ne=!0)}if(ne){dF()>0&&k(),C.delete(i);return}if(ee===void 0&&hi(S)===``){j7.warn({documentName:i},`[persistence] Skipped phantom write for ${i}: empty Y.Doc with no reconciled base`),C.delete(i);return}let re=M7(a,c);if(re&&re.id!==zS.id&&(ace(re.id)||sF(i,re.id,re.name,re.id)),ee!==void 0){let t=CSe(S,ee);if(t.kind===`block`&&b.has(i))Uie(),console.warn(JSON.stringify({event:`ok-persistence-duplication-spared`,"doc.name":i,candidateBytes:S.length,baseBytes:ee.length,fragmentChildren:n.getXmlFragment(`default`).length,copies:t.copies,reason:t.reason}));else if(t.kind===`block`){if(y.has(i)){j7.warn({documentName:i},`[persistence] Tripwire breaker active — skipping duplicate store for ${i}`);return}let a=n.getXmlFragment(`default`).length;console.warn(JSON.stringify({event:`ok-persistence-duplication-blocked`,"doc.name":i,candidateBytes:S.length,baseBytes:ee.length,fragmentChildren:a,copies:t.copies,reason:t.reason}));try{let o=Tj(i,r),s;if(H(o)){let e=null;try{e=W(o)}catch(e){j7.warn({err:e,documentName:i},`[persistence] Tripwire reset realpath failed for ${i}; using currentBase`)}if(e&&Ej(e,r))try{s=U(e,`utf-8`)}catch(t){j7.warn({err:t,documentName:i,canonical:e},`[persistence] Tripwire reset readFileSync failed for ${i}; using currentBase`),s=ee}else e&&j7.warn({docName:i,originalPath:o,canonical:e,contentDir:r},`[persistence] symlink-escape on tripwire reset: ${o} → ${e}, using currentBase`),s=ee}else s=ee;_e(n,i,S,t.copies,a);let c=e?.getLossRing?.(),l={baselineFullMd:s,report:e=>{try{let t=YS(e);if(t.length===0)return;c?.record({event:Yx,docName:i,writerId:LS.id,direction:`b`,site:fe,lostLen:t.reduce((e,t)=>e+t.length,0),digest:nt(t.join(`
2022
2022
  `))})}catch(e){j7.warn({documentName:i,err:e},`[persistence] duplication-reset loss detection failed`)}}};n.transact(()=>{x(n,s,void 0,void 0,void 0,l)},jH),y.delete(i)}catch(e){y.add(i),j7.error({err:e,documentName:i},`[persistence] Tripwire reset failed for ${i}`)}C.delete(i);return}}l=hi(S),t.beginInFlightFlush(i,l);let ie=Tj(i,r);await Uo(R(ie),{recursive:!0});let E;try{E=await bu(ie)}catch(e){let t=Vs(e);if(t===`ENOENT`){let e=!1;try{e=ql(ie).isSymbolicLink()}catch(e){Vs(e)!==`ENOENT`&&j7.warn({err:e,path:ie},`[persistence] lstat failed during broken-symlink check`)}e&&j7.warn({docName:i,reason:`broken-symlink`},`[persistence] broken-symlink fallback`),E=ie}else if(t===`ELOOP`)throw j7.error({path:ie,err:e},`[persistence] Symlink cycle at ${ie}`),Error(`Symlink cycle detected at ${ie}`);else throw e}if(!Ej(E,r)){let e=`symlink-escape: ${ie} resolves to ${E} outside ${r}`;throw j7.error({docName:i,originalPath:ie,canonical:E,contentDir:r},`[persistence] ${e}`),Error(e)}if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_DIVERGENCE===i&&await Bo(E,`# NATIVE
@@ -2025,6 +2025,6 @@ native-divergence-injected
2025
2025
  `,`utf-8`),o&&ee!==void 0){let r=null;try{H(E)&&(r=U(E,`utf-8`))}catch(e){r=null,j7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&hi(r)!==hi(ee)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:ee.length,candidateBytes:S.length})),ve(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=YS(e);if(t.length===0)return;o?.record({event:Yx,docName:i,writerId:LS.id,direction:`b`,site:A,lostLen:t.reduce((e,t)=>e+t.length,0),digest:nt(t.join(`
2026
2026
  `))})}catch(e){j7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},jH)}catch(e){throw t.recordStoreFailure(i,P7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(rie(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let D=`${E}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await Bo(D,S,`utf-8`),await as(D,E),eU(E,nU(S)),t.clearStoreFailure(i),cie();try{d?.(i,f,S,ee??null)}catch(e){j7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{Ko(D)}catch{}throw C.delete(i),t.recordStoreFailure(i,P7(e)),j7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}j7.info({filePath:E,bytes:S.length},`[persistence] Wrote ${E} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){j7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Mo({"persistence.bytes":S.length}),k()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),P?.record((Date.now()-o)/1e3)})}function we({document:e,documentName:n,lastTransactionOrigin:r}){ae.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Te(e=`within-branch`){return D?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,D):(D=(async()=>{let n=e;for(;;){let e=[...ae.entries()];if(ae.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Ce({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=nt(r),a;try{a=ESe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:nt(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}iae(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),j7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,ae.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{D=null}),D)}let F={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),lC(i))return;if(uC(i)){Uxe(n,i,h);return}if(dC(i)){NK(n,i,_);return}if(fC(i)||pC(i)){bSe(n,i,v);return}Se();let o=Date.now();return zo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{j7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=Tj(i,r);if(!H(a))return;let o=a;try{let e=W(a);if(!Ej(e,r)){j7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Vs(e)===`ELOOP`){j7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=iu(o).size;if(s>524288)throw j7.warn({documentName:i,fileSize:s,limit:zt},`[persistence] Document exceeds open byte limit; refusing to load`),new wSe(i,s);let c=U(a,`utf-8`),l=n.getXmlFragment(`default`);j7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{MH(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(fr,crypto.randomUUID())},jH),j7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{j7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):j7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{N?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!lC(n)){if(uC(n)){let t=await Gxe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){j7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(dC(n)){if(await IK(e,n,r,_)===`persisted`){let e=M7(r,c);if(e&&e.id!==zS.id&&!e.id.startsWith(`agent-`)){let t=CK(n);t&&(sF(t.docKey,e.id,e.name,e.id,t.subject),k())}}return}if(fC(n)||pC(n)){await xSe(e,n,r,v);return}if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:r});return}return Ce({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Ee(){ie&&await ie}async function De(){if(ie){await ie;return}dF()!==0&&(ie=O().finally(()=>{ie=null,E&&(E=!1,k())}),await ie)}function Oe(){return{branchDeferred:ae.size,quiescenceDeferred:C.size}}async function ke(e,n){if(!gC(n)){if(t.isBatchInProgress()){we({document:e,documentName:n,lastTransactionOrigin:null});return}return Ce({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:F,durabilityState:t,flushDeferredStores:Te,flushPendingGitCommit:ce,flushContributors:De,waitForPendingCommits:Ee,getQueueDepths:Oe,forceStore:ke,configPersistenceCtx:h,managedArtifactCtx:_}}const I7=L(`persistence-staleness`);var L7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function OSe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??vw,c=new Map,l=!1,u=null;function d(e){return N7(e)}function f(e){return e===void 0?void 0:hi(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Ya(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),gC(n)||OC(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let ee=T?.fingerprint!==x;ee&&Sie();let te=!ee&&T?T.firstDetectedAtMs:C,ne=C-te,re=null,ie=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(re=`disk-file-never-loaded`):t===null?re=`disk-file-missing`:hi(t)!==S&&(re=`disk-diverged-from-base`)}catch(e){e instanceof L7?(re=`disk-read-refused`,I7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(re=`disk-read-failed`,ie=!0,I7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(re!==null){g++,wie(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!ie}),I7.warn({docName:n,ageMs:w,staleForMs:ne,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:re},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}I7.warn({docName:n,ageMs:w,staleForMs:ne,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!1}),Cie(),h++;try{await e.forceStore(v,n)}catch(e){I7.error({err:e,docName:n,staleForMs:ne},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let E=v.getText(`source`).toString(),D=i(n),ae=d(E);p(ae,f(D),E,D)&&ae===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!0}),I7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?I7.info(v,`[persistence-staleness] sweep complete`):I7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{I7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function kSe(e){try{let t=xs({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function R7(e){let t=tN(e),n=V(t,`principal.json`),{name:r,email:i}=await kSe(e);if(H(n)){let e;try{e=JSON.parse(U(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Ou()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Kh(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Kh(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return ou(n,JSON.stringify(s,null,2),`utf-8`),s}Jl(t,{recursive:!0});let a=`principal-${Ou()}`,o=a.slice(10,18),s={id:a,display_name:r?Kh(r):`Local User`,display_email:i?Kh(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return ou(n,JSON.stringify(s,null,2),`utf-8`),s}var ASe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function z7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function jSe(e,t){try{if(mC(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(z7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw hS(),Mo({"auth.reason":`doc-deleted`}),new WZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){cae(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw mS(),Mo({"auth.reason":`rename-redirect`}),new WZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw z7(t,i)?(t.recentlyRemovedDocs.delete(i),mS(),Mo({"auth.reason":`rename-redirect`}),new WZ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(hS(),Mo({"auth.reason":`doc-deleted`}),new WZ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof WZ)throw t;sae(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const B7=L(`removed-docs-journal`);function V7(e){return z(tN(e),`removed-docs.json`)}function MSe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function NSe(e){let t=V7(e);if(!H(t))return[];try{let e=JSON.parse(U(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return B7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!MSe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return B7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function H7(e,t){let n=V7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};Zo(R(n),{recursive:!0});let i=`${n}.tmp`;os(i,JSON.stringify(r),`utf-8`),Wo(i,n)}const U7=L(`server-observers`);function W7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(lC(r)||uC(r)||fC(r)||pC(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=DT({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return U7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),dS(`a`),dS(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(U7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){U7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const G7=`state.json`;function K7(e){return e.lockDir,H(e.shadowRepoDir)?`adopt`:`fresh`}function q7(e){return V(e,G7)}function PSe(e,t){return e===t||e===0&&t===1}var J7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function FSe(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function Y7(e){let t=q7(e);if(!H(t))return{status:`absent`};let n;try{n=U(t,`utf-8`)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!FSe(r))throw new J7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function X7(e,t){let n=q7(e);Jl(R(n),{recursive:!0}),ou(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function Z7(e){let t=L(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Ns,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=q7(e.lockDir),s=Y7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!PSe(c.stateSchemaVersion,n))throw new J7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return X7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(K7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return X7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return X7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function ISe(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function LSe(e){return e.git?.toString()??e.message??``}function Q7(e,t){return t.some(t=>t.test(e))}const RSe={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},zSe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],$7=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],BSe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],VSe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],HSe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],USe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],WSe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],GSe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],KSe=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],qSe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],JSe=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],YSe=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],XSe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function e9(e){let t=ZSe(e);return{...t,userFacingCode:ISe(t.class,t.subclass)}}function ZSe(e){let t=e instanceof Error?e:Error(String(e)),n=LSe(t),r=`${t.message}\n${n}`.toLowerCase();if(Q7(r,GSe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Q7(r,KSe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Q7(r,qSe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=Ii(t);return i.kind===`auth`?i.subclass===`403`&&Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:RSe[i.subclass],rawStderr:n}:Q7(r,$7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Q7(r,zSe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Q7(r,BSe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Q7(r,VSe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Q7(r,HSe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Q7(r,WSe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Q7(r,USe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Q7(r,XSe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Q7(r,YSe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Q7(r,JSe)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function QSe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const t9=L(`github-permissions`);function $Se(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function eCe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function tCe(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function nCe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return t9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=tCe(t);return n===null?(t9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return t9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function rCe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){t9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function iCe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await rCe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(t9.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(t9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${$Se(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;t9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:eCe(l)}),t=await nCe(e,l!==void 0);return t9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(t9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(t9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function aCe(e){let t=performance.now(),n=await iCe(e);return lCe(n,performance.now()-t),n}function oCe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let n9=null;function sCe(){return n9||=ls().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),n9}let r9=null;function cCe(){return r9||=ls().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),r9}function lCe(e,t){let n=oCe(e);sCe().add(1,n),cCe().record(t,{outcome:n.outcome})}function i9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function uCe(e,t){return t===`anonymous`?Math.max(180,e):e}const a9=L(`sync-engine`),o9=/^[0-9a-f]{40}$/i,dCe=zu(wl);function fCe(e){let{exitCode:t,stderr:n}=e,r=n??``;return t===128||/^fatal:/m.test(r)&&/not possible to fast-forward/i.test(r)?`divergence`:/^error:/m.test(r)&&/would be overwritten by merge/i.test(r)?`overlay-overlap`:`unknown`}function pCe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function s9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function c9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function l9(e){let t=qu(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function mCe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const u9=12e4;var hCe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=QSe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??aCe,this.statePath=V(tN(this.projectDir),`sync-state.json`),this.conflictStore=new JZ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return zR(this.projectDir)}gitHandle(e){return ws(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){a9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),a9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){a9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=rd(this.projectDir),n=t?z(t,`MERGE_HEAD`):null,r=n!==null&&H(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){a9.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await nS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&a9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){a9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){a9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),a9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=i9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=i9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),a9.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,a9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){a9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Ru(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||l9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||l9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){a9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){a9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Ss(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,a9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,a9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?a9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):a9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return a9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||l9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?BR(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await eW(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=RR(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,s9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,a9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){a9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=pCe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,a9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,a9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!s9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,a9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!H(z(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return a9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=rd(this.projectDir),r=n?z(n,`MERGE_HEAD`):null;if(r!==null&&H(r))try{let n=this.gitHandle(),r=new Set(await nS(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&a9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){a9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{a9.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&(a9.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{a9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??c9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{a9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){a9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?uCe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=mCe(this.consecutiveFailures);return c9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(l9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,a9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),a9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await nS(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await nS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){a9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return a9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return a9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(a9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(e9(Error(`git merge --ff-only timed out after ${u9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),a9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return a9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(e9(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return a9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(e9(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return a9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await dCe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:u9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:fCe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!H(z(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),a9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=U(z(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&a9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=Ci(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){a9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){for(let{path:t,bytes:n}of e){let e=z(this.projectDir,t);fV(e,this.projectDir),os(e,n)}for(let e of t){let t=z(this.projectDir,e);fV(t,this.projectDir);try{Ko(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=z(this.projectDir,e),n=Cj(B(this.contentDir,t));return!n.startsWith(`..`)&&ZS(n)&&!this.contentFilter.isExcluded(n)}async gitBlobSha(e,t){try{return(await e.git.revparse([t])).trim()}catch{return}}classifyRefReadFailure(e){let t=e instanceof Error?e.message:String(e);return/does not exist in|exists on disk, but not in/i.test(t)?`absent`:`error`}async gitBlobContent(e,t){return e.git.raw([`cat-file`,`blob`,t])}async countStandingOverlay(e){try{return(await nS(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(l9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=z(pu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Ss(async()=>{let e=this.gitHandle(n);if(l9(this.projectDir)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){a9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(e9(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i);if(t.length>0)for(let n=0;n<t.length;n+=100){let r=t.slice(n,n+100).map(e=>e.projectRelPath);await e.git.raw([`add`,`--`,...r])}let o=new Set(t.map(e=>e.projectRelPath)),s=[...a].filter(e=>!o.has(e));await this.removePathsFromIndex(e,s);let c=(await e.git.raw([`write-tree`])).trim(),l=``;try{l=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(l&&l===c){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){a9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}a9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let u=[],d=[];try{let n=await nS(e.git,[`diff-tree`,`--name-only`,`-r`,i,c]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){u.push(t);let n=e.get(t)??Cj(B(this.contentDir,z(this.projectDir,t)));n&&!n.startsWith(`..`)&&d.push(n)}}}catch{u=t.map(e=>e.projectRelPath).concat(s),d=t.map(e=>e.contentRelPath)}let f=this.buildCommitMessage(d),p=await eW(this.projectDir),m=p===null;this.identityUnresolved!==m&&(this.identityUnresolved=m,this.cc1Broadcaster?.signal(`sync-status`));let h=p?.name??`OpenKnowledge`,g=p?.email??`sync@open-knowledge.local`;Es(e,{GIT_AUTHOR_NAME:h,GIT_AUTHOR_EMAIL:g,GIT_COMMITTER_NAME:h,GIT_COMMITTER_EMAIL:g});let _=(await e.git.raw([`commit-tree`,c,`-p`,i,`-m`,f])).trim();if(!_||!o9.test(_)){a9.warn({raw:_},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,_,i]),await this.resetRealIndexForPaths(u);let v=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),v=!0}catch{}v?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=_}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=e9(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){a9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=e9(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}a9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{au(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=z(pu(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);for(let e=0;e<n.length;e+=100){let t=n.slice(e,e+100).map(e=>e.projectRelPath);await a.git.raw([`add`,`--`,...t])}let i=new Set(n.map(e=>e.projectRelPath)),o=[...r].filter(e=>!i.has(e));await this.removePathsFromIndex(a,o);let s=(await a.git.raw([`write-tree`])).trim();if(s===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let c=[];try{c=await nS(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await eW(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Es(a,{GIT_AUTHOR_NAME:u,GIT_AUTHOR_EMAIL:d,GIT_COMMITTER_NAME:u,GIT_COMMITTER_EMAIL:d});let f=(await a.git.raw([`commit-tree`,s,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!f||!o9.test(f)?(a9.warn({raw:f},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,f,t]),await this.resetRealIndexForPaths(c,e),f)}finally{try{au(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await nS(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return a9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await nS(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return a9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return a9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){a9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=$l(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=z(n,i.name);if(i.isDirectory()){let e=Cj(B(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Cj(B(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Cj(B(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return H(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await nS(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=z(this.projectDir,e),r=Cj(B(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await nS(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){a9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=z(this.projectDir,e),i=Cj(B(this.contentDir,t));!i.startsWith(`..`)&&ZS(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),a9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){a9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),a9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),a9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=rd(this.projectDir);t=n===null||!H(z(n,`MERGE_HEAD`))}catch(e){a9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),a9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){a9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),a9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){a9.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),a9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,a9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};ou(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){a9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(H(this.statePath))try{let e=U(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){a9.warn({err:e},`[sync] failed to load sync state`)}}};Do();const gCe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _Ce(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(lC(e)||uC(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&gCe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Po(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Oo.with(To.extract(Oo.active(),r),e)}else e()}catch(e){L(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let d9=!1;function f9(){if(d9)return;let e=fte;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){d9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),d9=!0}catch(e){L(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const vCe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function yCe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(y8).join(` `)} auth git-credential`]}function bCe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Dl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],zF({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return L(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return L(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
2027
2027
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=V(e,r);if(!Ej(a,t))continue;let s=pU(a,t);i.has(s)||H(a)&&i.set(s,o)}return i}function p9(e){f9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=L(`server`),x=new l7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),ee=e=>x.switchReconciledBaseScope(e),te=e=>x.setBatchInProgress(e),ne=()=>x.isBatchInProgress();function ie(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=le(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function E(){let e=Fo({absPath:Lo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=b(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:re(r.value.autoSync?.default)??`off`,source:`committed-default`}}function D(){let e=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Pr(e):oo}function ae(){return Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function O(){return PF(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function oe(){let e=Fo({absPath:Lo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function k(){return No({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function ce(){for(let e of k().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function ue(e){return`${wF(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function de(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=E();t=n.mode,ut?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=O();ke.applyConfig({enabled:n.enabled,providerFingerprint:ue(n)}),e===`__config__/project`&&Ce?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}cs();let fe=Ou(),A=tN(n),pe=new Ld({localDir:A,log:L(`acp-registry`)}),j=new kd(A,L(`acp-permissions`));if(Rs(A,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{Z7({lockDir:A,shadowRepoDir:id(n)})}catch(e){throw Os(A),e}let me=Ma(),he=(e,t)=>me.resolveEmbed(e,t),ge=(e,n)=>{let r=me.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=V(t,r);if(!wj(i,V(t)))return null;try{let e=iu(i);return e.isFile()?e.size:null}catch{return null}},_e,M,ve,ye,be,N,P,xe,Se,Ce=null,we=null,Te=null,F=null,Ee=null,De=null,Oe=O(),ke=new Hce({loadEmbedder:e.embedderLoader??(()=>{let t=O();return Oce({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:z(tN(n),`embeddings`),enabled:Oe.enabled,providerFingerprint:ue(Oe)}),I=null,Ae=new Set,je=!1,Me=[],Ne,Fe,Ie,Le=new Promise((e,t)=>{Fe=e,Ie=t});function Re(e){Ce?.signal(e)}let ze=null,Be=!1,Ve=()=>{try{H7(n,He.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},He=new ASe(void 0,{onEviction:()=>aae(),onSizeChange:e=>oae(e),onMutate:()=>{!Be||ze!==null||(ze=setTimeout(()=>{ze=null,Ve()},2e3))}});for(let[e,r]of NSe(n))mC(e)||NZ(e)&&([`.md`,`.mdx`].some(n=>{let r=V(t,`${e}${n}`);return wj(r,V(t))&&H(r)})||He.restore(e,r));Be=!0;let Ue={current:null},We=(e,t)=>{mC(e)||He.setRenamed(e,t)},Ge=e=>{if(!mC(e)){if(He.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}He.setDeleted(e),Ue.current?.deleted(e)}},Ke=e=>{mC(e)||He.delete(e)};try{_e=rL({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:lV(t),rescanInPlaceSkillDirs:()=>lV(t),onAfterRebuild:()=>{M.refreshContentScope().catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),IU(ct).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?L(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):L(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),M=new AH({projectDir:n,contentDir:t,contentFilter:_e,getGlobalSkillRoots:()=>TK(be.managedArtifactCtx),signalChannel:Re}),ve={current:d},ye=o?_Se({getShadow:()=>ve.current??null,getCurrentBranch:()=>lt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:rd(n)??void 0,isWriterLive:e=>{if(!F&&!xe)return L(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(F?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of xe?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,be=F7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:ve,ephemeral:v,contentRoot:f,derivedDocumentIndex:M,configHomedirOverride:l,getCurrentBranch:()=>lt?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge,getPrincipal:()=>I,onAgentCommit:()=>Ce?.signal(`session-activity`),onFlushCommit:()=>ye?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Ce?.emitDiskAck(e,t),!mC(e)&&Zj(r,n)&&(Ee?.(),Re(`files`))},onConfigRejected:(e,t)=>Ce?.emitConfigValidationRejected(e,t),onConfigPersisted:de,isRecentlyRemoved:e=>He.has(e),mdManager:e.mdManager,getLossRing:()=>N,durabilityState:x}),P=new Nxe({quiet:r,debounce:i,maxDebounce:a,extensions:[be.extension]});let p=P;Me.push(soe(()=>p.documents.size),coe(()=>be.getQueueDepths()),uoe(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),foe(),v||(De=OSe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>be.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=Tj(e,t),r,i;try{r=W(n),i=iu(r).size}catch(t){let n=Vs(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new L7(`symlink cycle at content path: ${e}`):t}if(!Ej(r,t))throw new L7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new L7(`document exceeds the open byte limit: ${e}`);try{return U(r,`utf-8`)}catch(e){if(Vs(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=P.shouldUnloadDocument.bind(P);P.shouldUnloadDocument=e=>{if(Ae.has(e)||je&&g(e))return!0;let t=e.name;return mC(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Ne=async e=>{Ae.add(e);try{await P.unloadDocument(e)}finally{Ae.delete(e)}},Ce=new _C(P),Te=new vD(P),F=new yD(P),xe=new JT(P,e.agentSessionOptions);let b=xe;Me.push(doe(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=p7({derivedDocumentIndex:M,onDocumentSettled:e=>Ue.current?.changed(e)});P.configuration.extensions.push(w),P.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=GZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==fe)throw new WZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${fe}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new WZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(I&&n.principalId===I.id?o.principalId=I.id:I?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:I.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),P.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!uC(t.documentName)&&!dC(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!dj(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&_j(a,e.remotePublicHost);if(!fj(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=V(t);function ee(e){if(!NZ(e))return null;let t=V(T,oC(e));return wj(t,T)?t:null}P.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await jSe(e.documentName,{recentlyRemovedDocs:He,resolveFilePath:ee,fileExists:H})}}),P.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=GZ(e.token);Yxe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>P.documents.get(e)})}}),P.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new D5(e.update);if(t.readVarString(),t.readVarUint()===R5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${za} rejected — server-only channel`)}});let te=FZ({hocuspocus:P,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:Ue,contentDir:t,contentFilter:_e,serverInstanceId:fe,getFileIndex:()=>ct?ct.getFileIndex():new Map,getAttachmentFolderPath:ie,getAllFilesIndex:()=>ct?ct.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ct?.getFileIndexGeneration()??0,mutateFileIndex:e=>ct?.mutateFileIndex(e),getFolderIndex:()=>ct?ct.getFolderIndex():new Map,getAliasMap:()=>ct?ct.getAliasMap():new Map,getFolderAliasIndex:()=>ct?ct.getFolderAliasIndex():new Map,rescanFiles:()=>ct?.rescanFromDisk(),enableTestRoutes:u,shadowRef:ve,flushGitCommit:()=>be.flushPendingGitCommit(),flushContributors:()=>be.flushContributors(),getCurrentBranch:()=>lt?.getLastKnownBranch()??null,getDiskAckSVs:()=>Ce?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:M,signalChannel:Re,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ut,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:he,getBridgeLossReporter:()=>Se,getPrincipal:()=>I,acpRegistry:pe,loadAcpCustomAgents:()=>Rd(A,L(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Ne,ready:Le,recentlyRemovedDocs:He,serializeDoc:Ze,evictManagedArtifactLkg:e=>{be.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:ke,getSemanticSimilarityFloor:()=>O().similarityFloor,getLinterBaseConfig:()=>D(),getLinksValidationSetting:()=>ae(),getLinkPreviewsEnabled:oe,getConfigDiagnostics:k,embeddingsSecretsFile:jF(l),readSemanticProviderConfig:O,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{Ee=e}});P.configuration.extensions.push(te);let ne=Fo({absPath:Lo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),re=ne.value.bridge.deferGuard.enabled,E=ne.value.bridge.fixedPoint.enabled,se=ne.value.bridge.preDrain.enabled;N=ne.value.lossCapture.enabled?new Jre({projectDir:n,maxBytes:ne.value.lossCapture.maxBytes}):void 0,ne.value.bridge.lossDetector.enabled&&(Se=zae({shadow:()=>ve.current,ring:N,getBranch:()=>lt?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(Se)),P.configuration.extensions.push(W7({mdManager:Ao,schema:ko,shadowRef:ve,contentRoot:f,getCurrentBranch:()=>lt?.getLastKnownBranch()??null,resolveEmbed:he,resolveSize:ge,deferGuardEnabled:re,lossDetectorEnabled:ne.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:E,preDrainEnabled:se,lossRing:N})),P.configuration.extensions.push(_Ce()),P.configuration.extensions.push(Jxe({getSyncEngine:()=>ut,projectDir:n,contentDir:t}))}catch(e){for(let e of Me.splice(0))e();throw De?.dispose(),De=null,Os(A),e}let qe=null,Je=new Map,Ye=[];function Xe(e,t){let n=V(e,`rescue`),r=V(n,oC(t));return wj(r,n)?r:null}function Ze(e){let t=P.documents.get(e);return t?UH(t):null}let Qe=(e,t)=>BH(x,P,e,t,he,ge,Se);function $e(e){if(!DC(e)||ut?.getConflicts().some(r=>c7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let et=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of P.documents){if(mC(n))continue;let r=P.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{MH(r,i,he,n)},jH)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},tt=null,nt=e=>{e&&(tt===null&&(tt=new Set,setImmediate(()=>{let e=tt;if(tt=null,e)try{for(let t of e)et(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),tt.add(e))};function rt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return YH(e)}}async function it(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await M.recordDiskUpsert(e.docName,e.content),Re(`files`),Ke(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=P.documents.get(t);if(!r){await M.recordDiskUpsert(t,n);return}let i=C(t)??``,a=Ze(t)??i,o=IH({docName:t,base:i,ours:a,theirs:n}),s=nU(i).slice(0,6),c=nU(a).slice(0,6),l=nU(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:$e(r),await M.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{Qe(t,o.newContent),w(t,o.newContent),rS(),$e(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),$e(r)}e&&await M.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{Qe(t,o.newContent),w(t,n),rS(),$e(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),$e(r)}e&&await M.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{Qe(t,o.newContent),w(t,o.newContent),rS(),iS(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await M.recordDiskUpsert(t,n);break}case`refused`:{iS();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=P.documents.get(t);if(!n){await M.recordDiskDelete(t),Re(`files`),Ge(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=Ze(t)??``,a=i!==r;if(a&&ve.current){let e=ve.current,n=lt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{WS(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{oS(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await M.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),P.closeConnections(t),await Ne(n),Re(`files`),Ge(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=P.documents.get(t);if(T(t),w(n,r),await M.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Re(`files`),We(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=P.documents.get(t);if(!n)return;let r=Ze(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:me.add(e.relativePath),Re(`files`),nt(kl(e.relativePath));break;case`asset-delete`:me.remove(e.relativePath),Re(`files`),nt(kl(e.relativePath));break;case`folder-create`:case`folder-delete`:Re(`files`);break;case`file-create`:case`file-update`:case`file-delete`:Re(`files`);break;default:YH(e)}}catch(t){let n=rt(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let at=[];async function ot(e){if(ne()){at.push(e);return}await it(e)}async function st(){let e=at.splice(0,at.length);for(let t of e)await it(t)}let ct=null,lt=null,ut=null,dt=null;async function ft(e){if(P.documents.size===0)return;let t=!1,n=new Promise(e=>{P.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(P.documents.keys());P.closeConnections(),P.flushPendingStores();for(let e of P.documents.values())e.getConnectionsCount()===0&&P.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(P.documents.keys()),i=[],o=[];if(ve.current){for(let e of n)if(!mC(e))try{let t=Ze(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Xe(ve.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:ve.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Jl(R(n),{recursive:!0}),ou(n,t,`utf-8`),oS(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function pt(){return dt||(dt=(async()=>{let e=Date.now(),t=[];je=!0;for(let e of Me.splice(0))e();try{await De?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}De=null;try{zs(A)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(ze!==null&&(clearTimeout(ze),ze=null),Be)try{H7(n,He.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Le.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=P.documents.size;ye?.destroy();try{try{try{we&&=(clearTimeout(we),null),lt&&=(await lt.unsubscribe(),null),ct&&=(await ct.unsubscribe(),null);for(let{docName:e,cleanup:t}of Ye)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Ye.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Ce?.destroy(),F?.destroy(),qe&&=(await qe.disconnect(),null);for(let[e,t]of Je)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Je.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await xe.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Yae()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await ft(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}M.close();let e;try{await Promise.race([(async()=>{await be.flushPendingGitCommit(),await be.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ut&&=(await ut.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ve.current){try{let e=(await xs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&ou(V(ve.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{bae(ve.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Os(A,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ss()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),dt)}let mt=[];async function ht(){try{I=await R7(n),y.info({principalId:I.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ve.current)try{ve.current=await AS(n),y.info({gitDir:ve.current.gitDir},`[server] history repo initialized at ${ve.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),mt.push(`shadow-repo`)}if(ve.current){let e=null;try{e=_q(ve.current.gitDir),Bq(ve.current.gitDir,e),Sq(ve.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([Vq(ve.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await ye?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ve.current)try{await OS(ve.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ve.current=await AS(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),ve.current=void 0,mt.includes(`shadow-repo`)||mt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(ve.current)try{let e=V(ve.current.gitDir,`last-known-head`),t=null;try{t=U(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await xs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await xs({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await VS(ve.current,f??``,t,r,e),aS()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{ou(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=rq(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),mt.push(`managed-rename-recovery`)}try{let e=kV(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),mt.push(`upload-tempfile-sweep`)}try{qe=await P.openDirectConnection(za),Ce?.emitServerInfo(fe,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),mt.push(`cc1-push`)}let r=v?[]:Cn;for(let e of r)try{let t=await P.openDirectConnection(e);Je.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),mt.push(`config-doc:${e}`)}let i=new Map([[si,Lo(`project`,n)],[Ga,Lo(`project-local`,n)],[_a,Lo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await Z5(t,t=>{let n=P.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=s7(n??null,e,t,be.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),de(e)});Ye.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),mt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=MK(e,be.managedArtifactCtx);if(!n)return;let r=LK(P.documents.get(n)??null,n,t,be.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Re(`files`),mi(n)&&M.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=MK(e,be.managedArtifactCtx);Re(`files`),t&&mi(t)&&M.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=TK(be.managedArtifactCtx),r=await T7(n,e,void 0,t);Ye.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),mt.push(`managed-artifact-watcher:skills`)}try{let e=V(SK(be.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await Z5(e,()=>{Re(`files`)});Ye.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),mt.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of(await vP(n)).templates)t.add(e.source_folder)}catch(e){y.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?V(n,e,`.ok`,`templates`):V(n,`.ok`,`templates`)),i=await T7(r,e,ySe);Ye.push({docName:`__template-files__`,cleanup:i}),y.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] templates failed to start`),mt.push(`managed-artifact-watcher:templates`)}}try{let e=V(t,`.okignore`),r=V(n,`.gitignore`),i=null;try{let e=Dl(`git`,[`rev-parse`,`--git-common-dir`],zF({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=z(V(n,e.stdout.trim()),`info`,`exclude`);H(R(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await zxe(a,(t,r)=>{(async()=>{if(t===e)try{let e=s7(P.documents.get(`__config__/okignore`)??null,Pe,r,be.configPersistenceCtx);o.info({docName:Pe,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:B(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await _e.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:B(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Ce?.signal(`files`);else{let e=B(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Ce?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:B(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Ye.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),mt.push(`ignore-files-watcher`)}let a=f7(n).branch??`main`;ee(a);let o=M.beginStartup(a),s=!1,c=performance.now();try{await zo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&mt.push(`backlink-index`);let i=0;for(let t of e)mC(t)||He.peek(t)?.kind!==`renamed`&&(He.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=_e?lV(t):new Set,d=e=>{e.some(e=>c.test(B(t,e).split(Fl).join(`/`)))&&(we&&clearTimeout(we),we=setTimeout(()=>{we=null;try{YJ(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Ce?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=lV(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,_e.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Ce?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ct=await zo(`ok.boot.seed-walk`,void 0,async()=>FU(t,ot,_e,{onRawBatch:d})),YJ(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??uu();YJ(e,e,oV(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}hH(`seedWalkMs`,Math.round(performance.now()-a));{let e=V(t),n=0;for(let[t]of He.entries()){if(!NZ(t))continue;let r=V(e,`${t}${iC(t)}`);wj(r,e)&&H(r)&&(He.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await M.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&mt.push(`tag-index`);let p=0;try{_===void 0?await RZ({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):LZ({contentDir:t,basenameIndex:me,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),mt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),mt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),mt.push(`file-watcher`),!s){let e=await M.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&mt.push(`tag-index`)}}finally{hH(`indexesMs`,Math.round(performance.now()-c)),ct&&gH(`fileCount`,ct.getFileIndex().size)}try{lt=await eSe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),nie(),P.flushPendingStores(),await be.flushPendingGitCommit(),te(!0),ve.current){let e=S(),t=f7(n).branch??e,r=[];for(let[e,t]of P.documents){if(mC(e))continue;let n=null;if(t.transact(()=>{n=Ze(e)},vCe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await Aae(ve.current,e,zS.id,r,t);n&&(aie(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=at.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(te(!1),await st(),e.headMoved&&e.newHead){let r=bCe(n,V(t),e.oldHead,e.newHead);if(r.size>0){tce(r.keys());for(let[e,t]of r)sF(e,gte(t.email),t.name,t.email,xd(e));await be.flushContributors()}}if(await be.flushDeferredStores(`within-branch`),ut!==null)try{await ut.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{iie(),at.splice(0,at.length);let n=!1,r;try{ee(i),r=await M.beginBranchSwitch(i),_e.rebuildDirCount();try{let e=0;me.clear(),await RZ({contentDir:t,contentFilter:_e,basenameIndex:me,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),mt.includes(`basename-index-partial`)||mt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of P.documents)if(!mC(e))try{let r=Tj(e,t);if(!H(r)){let t=C(e)??``,r=Ze(e)??``;if(r!==t&&ve.current){let t=ve.current;queueMicrotask(()=>{WS(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{oS(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=U(r,`utf-8`);Qe(e,a),w(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:P.documents.size},`[branch-switch] loaded branch ${i} (${P.documents.size} docs)`);try{await M.settleBranchFromDisk(r)}catch(e){M.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(ve.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of P.documents)if(!mC(t))try{let n=await Mae(ve.current,i,zS.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=IH({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Qe(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:Qe(t,a.newContent),w(t,a.newContent),iS(),e++;{let e=P.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&ve.current)try{let t=OS(ve.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await wS(ve.current).withMutator(async()=>{for(let e of n.split(`
2028
- `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Ce?.emitBranchSwitched(i)}finally{M.abortBranchSwitch(r),n||(te(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await VS(ve.current,t,e.oldHead,e.newHead,i);aS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),mt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Cj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=$S(e),a=P.documents.get(i);if(!a)continue;let o=Ze(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Cj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=P.documents.get($S(e));i&&$e(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=yCe(m),h=E();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ut=new hCe({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Ce,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await US(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await US(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Xo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:se(t.error),configPath:Lo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ut.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ut=null}Re(`files`),M.announceReadyViews();let g=mH();g!==void 0&&hH(`readyMs`,g),ce()}return ht().then(Fe,e=>{M.close(),Ie(e)}),{hocuspocus:P,durabilityState:x,sessionManager:xe,cc1Broadcaster:Ce,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,maintenanceCoordinator:ye,contentFilter:_e,basenameIndex:me,serverInstanceId:fe,destroy:pt,ready:Le,degraded:mt,lockDir:A,get syncEngine(){return ut},getLinkPreviewsEnabled:oe,resolveEmbed:he,acpRegistry:pe,acpPermissions:j}}function m9(e){return e/1048576}function xCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Ro(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function SCe(){if(h9)return;let e=ls().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=xCe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),h9=e}function CCe(){if(!g9){let e=ls().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Nu({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=ls().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),_9=e}}const x9=L(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=GD.indexOf(e.host),r=GD.indexOf(t.host);return(n===-1?GD.length:n)-(r===-1?GD.length:r)||e.host.localeCompare(t.host)})}const wCe=S9(Dt),TCe=S9(Jn);function ECe(e,t){Zo(R(t),{recursive:!0});try{Wo(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;es(e,t,{recursive:!0}),ts(e,{recursive:!0,force:!0})}}function DCe(e,t,n){let r=oB(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function C9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+Fl)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??wCe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=$l(n)}catch{return a}let s=B(t,n).split(Fl).join(`/`),c=new Set;for(let[e,n]of Object.entries(KJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!vr.test(e)||lz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=zD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:vB(t,i),state:DCe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ts(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ts(d.path,{recursive:!0,force:!0}),ECe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ts(e.path,{recursive:!0,force:!0}),es(d.path,e.path,{recursive:!0}));await mI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=L(`skill-reconcile`),OCe=lz;function E9(){let e=[];for(let t of St){let n=Dt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function kCe(e,t){let n=B(e,V(t));return Ml(n)?V(t):n}function D9(e){let{frontmatter:t,body:n}=bi(e),r={};if(t!==``)try{let e=(0,ej.parse)(Sr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function ACe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=iu(s).size+iu(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!ACe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of $l(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){ts(t,{recursive:!0,force:!0}),Zo(e,{recursive:!0}),qo(kCe(e,n),t,`dir`)}function j9(e,t){try{let n=eu(e);return V(Ml(n)?n:V(R(e),n))===V(t)}catch{return!1}}function jCe(e,t){try{let n=eu(e),r=Ml(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Ml(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const MCe=[...St,`agents`];function NCe(e){for(let t of MCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function PCe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=$l(n)}catch{return}let i=E9();for(let e of r){let r=NCe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=ql(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(vB(t,r))continue;let i=z(r,e);j9(i,a)&&A9(r,i,o)}ts(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function FCe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=V(t,e);if(!H(o)||vB(t,o))continue;let s;try{s=$l(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(OCe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=ql(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(jCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(ts(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!vr.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=dI(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await pI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??fB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{PCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=tN(e);M9=new vs({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ca(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Ca(null),await M9?.drain(),M9=null,N9=!1}Do();const ICe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LCe=[`cache`,`tmp`];function RCe(e){let t=V(e,ve);if(!(()=>{if(!H(t))return!0;try{return $l(t).length===0}catch{return!0}})())return[];let n=[];for(let t of ICe)H(V(e,t))&&n.push(t);for(let t of LCe){let r=V(e,t);try{H(r)&&iu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zCe(e){let t=nd(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function BCe(e){pH();let t=e.projectDir??e.contentDir,n=cQ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}ms.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}cs({localSink:n?.telemetry}),F9(t),SCe(),CCe();let{kind:r,gitdir:i}=zCe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=$o(i));let o=eQ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>zo(`ok.boot`,{attributes:a},async()=>VCe(e)),l=()=>{if(s)try{let e=To.extract(Oo.active(),{traceparent:s});return Oo.with(e,c)}catch(e){L(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function VCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?mj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new pj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-DyY9o-h3.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new X8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??BG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof LG||e instanceof RG){let t=e instanceof RG?e.detected:``,n=e instanceof RG?`too_old`:`not_available`;aK(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ss(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let v=RCe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ve}/.`);let y=p9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie}=y,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),D=e.port??0,ae=e.ephemeral?void 0:U8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${D}`,log:r}),O=l();O.headersTimeout=3e4,O.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:cM({contentFilter:y.contentFilter,contentSirv:Ws(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),se=!1;if(e.reactShellDistDir)try{hV(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof mV)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let k=e.reactShellDistDir?Ws(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new mD({contentDir:e.contentDir,localDir:T,globalDir:V(uu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:re,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${E}:${D}`,getMcpStdioCommand:()=>pD(e.localOpCliArgs,D),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=`pending`;C.then(()=>{le=`ready`},()=>{le=`failed`});let ue=J8({httpServer:O,hocuspocus:b,mcpHttpHandler:ae,remoteAccess:i,health:{readiness:()=>le,degraded:()=>w},log:r,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:k,ephemeral:e.ephemeral,acpThreadManager:ce}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;a!==null&&(fe=tQ({httpServer:O,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);O.once(`error`,r),O.listen(e.port,e.host,()=>{O.removeListener(`error`,r),t()})})}catch(e){if(se)try{vV(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let A=mH();A!==void 0&&hH(`httpListenMs`,A);let pe=O.address(),j=typeof pe==`object`&&pe?pe.port:e.port??0;if(D=j,f(T,j),se&&gV(T,j),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let me=!1,he=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};de=async()=>{if(me)return;me=!0,le=`draining`;let e=[],t=async(t,n)=>{try{await he(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),se&&yV(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),se&&await t(`releaseUiLock`,async()=>vV(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ss()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ms.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,aV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=uu(),t=await w9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:TCe,inPlaceNames:C9(e,oV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await FCe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:de,lockDir:T,contentDir:e.contentDir,port:j,ready:C,degraded:w,didAutoInit:p,serverInstance:y,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new JZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=rd(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Cs({baseDir:n,timeout:{block:5e3}});s=new Set(await nS(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=$S(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const HCe=ke;function UCe(e={}){let t=e.home??uu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(_s(),1);const B9=z(uu(),`.ok`,`logs`),WCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function GCe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function KCe(e){Jl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function qCe(e){try{if(iu(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{tu(n,r)}catch{}}try{au(`${e}.3`)}catch{}}function JCe(e){try{let t=Date.now(),n=10080*60*1e3,r=$l(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=iu(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{au(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{au(z(e,t.name)),a-=t.size}catch{}}}catch{}}function YCe(e){KCe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);qCe(n),(e._setTimeout??setTimeout)(()=>JCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:GCe(),name:e.name,redact:{paths:WCe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function XCe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function ZCe(e){return z(B9,`${e}.${V9()}.log`)}function QCe(){return B9}function $Ce(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=zu(wl),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ewe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],zF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function twe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!iu(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=BG()}catch(e){throw e instanceof LG||e instanceof RG?(aK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof RG?`too_old`:`not_available`,detectedVersion:e instanceof RG?e.detected:``},e instanceof RG?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await ewe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],zF({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!H(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,nwe=Kt.map(e=>e.replace(/\/$/,``));async function rwe(e){let t=rd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(swe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ws(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ss(async()=>{let t=await iwe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await awe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=ws(e,{gitIndexFile:z(pu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await owe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await eW(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Es(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${ja}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of nwe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function iwe(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function awe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function owe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function swe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function cwe(e,t){let n;try{n=Cl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await vu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const lwe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of lwe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function uwe(e){if(!ZS(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!iu(t).isFile())throw new Q9(e);let n=R(t),r=RU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:$S(B(dwe(e),t).split(Fl).join(`/`)),canonicalFilePath:t}}let i=kl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:$S(i)}}function dwe(e){return V(e,Fo({absPath:Lo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function fwe(e){let t=Yl(V(pu(),`ok-ephemeral-`)),n=V(t,`.ok`);return Jl(n,{recursive:!0}),ou(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),ou(V(n,`.gitignore`),`local/
2028
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}te(!1),await be.flushDeferredStores(`discard-stale`),n=!0,Ce?.emitBranchSwitched(i)}finally{M.abortBranchSwitch(r),n||(te(!1),await be.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ve.current&&r>0){let t=f??`.`;try{let n=await VS(ve.current,t,e.oldHead,e.newHead,i);aS(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),mt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Cj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=$S(e),a=P.documents.get(i);if(!a)continue;let o=Ze(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=Cj(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=P.documents.get($S(e));i&&$e(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=yCe(m),h=E();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ut=new hCe({projectDir:n,contentDir:t,contentFilter:_e,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:Ce,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||be.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ve.current;n&&await US(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ve.current;n&&await US(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await Xo({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:se(t.error),configPath:Lo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ut.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ut=null}Re(`files`),M.announceReadyViews();let g=mH();g!==void 0&&hH(`readyMs`,g),ce()}return ht().then(Fe,e=>{M.close(),Ie(e)}),{hocuspocus:P,durabilityState:x,sessionManager:xe,cc1Broadcaster:Ce,agentFocusBroadcaster:Te,agentPresenceBroadcaster:F,maintenanceCoordinator:ye,contentFilter:_e,basenameIndex:me,serverInstanceId:fe,destroy:pt,ready:Le,degraded:mt,lockDir:A,get syncEngine(){return ut},getLinkPreviewsEnabled:oe,resolveEmbed:he,acpRegistry:pe,acpPermissions:j}}function m9(e){return e/1048576}function xCe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:m9(e.rss),heapTotalMb:m9(e.heapTotal),heapUsedMb:m9(e.heapUsed),externalMb:m9(e.external),arrayBuffersMb:m9(e.arrayBuffers)}}}let h9=null,g9=null,_9=null;const v9=1e6;let y9=null,b9=null;Ro(()=>{h9=null,g9=null,_9=null,y9?.disable(),y9=null,b9=null});function SCe(){if(h9)return;let e=ls().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=xCe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),h9=e}function CCe(){if(!g9){let e=ls().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!y9){y9=Nu({resolution:20}),y9.enable();return}e.observe(y9.percentile(50)/v9,{stat:`p50`}),e.observe(y9.percentile(99)/v9,{stat:`p99`}),y9.reset()}),g9=e}if(!_9){let e=ls().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=b9;if(b9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),_9=e}}const x9=L(`skill-migrate`);function S9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=GD.indexOf(e.host),r=GD.indexOf(t.host);return(n===-1?GD.length:n)-(r===-1?GD.length:r)||e.host.localeCompare(t.host)})}const wCe=S9(Dt),TCe=S9(Jn);function ECe(e,t){Zo(R(t),{recursive:!0});try{Wo(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;es(e,t,{recursive:!0}),ts(e,{recursive:!0,force:!0})}}function DCe(e,t,n){let r=oB(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function C9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+Fl)}catch{return!0}}).map(e=>e.name))}async function w9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??wCe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=$l(n)}catch{return a}let s=B(t,n).split(Fl).join(`/`),c=new Set;for(let[e,n]of Object.entries(KJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!vr.test(e)||lz.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=zD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:vB(t,i),state:DCe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ts(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ts(d.path,{recursive:!0,force:!0}),ECe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ts(e.path,{recursive:!0,force:!0}),es(d.path,e.path,{recursive:!0}));await mI(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),x9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),x9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const T9=L(`skill-reconcile`),OCe=lz;function E9(){let e=[];for(let t of St){let n=Dt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function kCe(e,t){let n=B(e,V(t));return Ml(n)?V(t):n}function D9(e){let{frontmatter:t,body:n}=bi(e),r={};if(t!==``)try{let e=(0,ej.parse)(Sr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function ACe(e,t){let n=D9(e),r=D9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function O9(e,t){let n=k9(e),r=k9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=iu(s).size+iu(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!ACe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function k9(e,t=``){let n=[];for(let r of $l(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...k9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function A9(e,t,n){ts(t,{recursive:!0,force:!0}),Zo(e,{recursive:!0}),qo(kCe(e,n),t,`dir`)}function j9(e,t){try{let n=eu(e);return V(Ml(n)?n:V(R(e),n))===V(t)}catch{return!1}}function jCe(e,t){try{let n=eu(e),r=Ml(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Ml(i))}catch(t){return T9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const MCe=[...St,`agents`];function NCe(e){for(let t of MCe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function PCe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=$l(n)}catch{return}let i=E9();for(let e of r){let r=NCe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=ql(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!O9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(vB(t,r))continue;let i=z(r,e);j9(i,a)&&A9(r,i,o)}ts(a,{recursive:!0,force:!0}),T9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){T9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function FCe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of E9()){let o=V(t,e);if(!H(o)||vB(t,o))continue;let s;try{s=$l(o)}catch(e){T9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(OCe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=ql(t);if(l.isSymbolicLink()){if(j9(t,s)&&c)continue;if(jCe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(A9(o,t,s),r.healed.push({name:e,editor:i})):(ts(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!vr.test(e)){T9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&O9(t,s)){A9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){T9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=dI(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await pI(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??fB(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){T9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{PCe({projectDir:t,skillsRoot:n})}catch(e){T9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=tN(e);M9=new vs({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ca(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){Ca(null),await M9?.drain(),M9=null,N9=!1}Do();const ICe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LCe=[`cache`,`tmp`];function RCe(e){let t=V(e,ve);if(!(()=>{if(!H(t))return!0;try{return $l(t).length===0}catch{return!0}})())return[];let n=[];for(let t of ICe)H(V(e,t))&&n.push(t);for(let t of LCe){let r=V(e,t);try{H(r)&&iu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zCe(e){let t=nd(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function BCe(e){pH();let t=e.projectDir??e.contentDir,n=cQ({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}ms.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}cs({localSink:n?.telemetry}),F9(t),SCe(),CCe();let{kind:r,gitdir:i}=zCe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=$o(i));let o=eQ(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>zo(`ok.boot`,{attributes:a},async()=>VCe(e)),l=()=>{if(s)try{let e=To.extract(Oo.active(),{traceparent:s});return Oo.with(e,c)}catch(e){L(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function VCe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?mj(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new pj("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-owrYVjgw.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new X8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??BG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof LG||e instanceof RG){let t=e instanceof RG?e.detected:``,n=e instanceof RG?`too_old`:`not_available`;aK(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ss(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let v=RCe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ve}/.`);let y=p9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie}=y,E=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),D=e.port??0,ae=e.ephemeral?void 0:U8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${E}:${D}`,log:r}),O=l();O.headersTimeout=3e4,O.requestTimeout=6e4;let oe=e.serveContentAssets===!1?void 0:cM({contentFilter:y.contentFilter,contentSirv:Ws(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),se=!1;if(e.reactShellDistDir)try{hV(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),se=!0}catch(e){if(e instanceof mV)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let k=e.reactShellDistDir?Ws(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ce=e.ephemeral?null:new mD({contentDir:e.contentDir,localDir:T,globalDir:V(uu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:re,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${E}:${D}`,getMcpStdioCommand:()=>pD(e.localOpCliArgs,D),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ce!==null&&await ce.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let le=`pending`;C.then(()=>{le=`ready`},()=>{le=`failed`});let ue=J8({httpServer:O,hocuspocus:b,mcpHttpHandler:ae,remoteAccess:i,health:{readiness:()=>le,degraded:()=>w},log:r,sessionManager:te,agentFocusBroadcaster:ne,agentPresenceBroadcaster:re,maintenanceCoordinator:ie,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:oe,reactShellMiddleware:k,ephemeral:e.ephemeral,acpThreadManager:ce}),de=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},fe=null;a!==null&&(fe=tQ({httpServer:O,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await de()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);O.once(`error`,r),O.listen(e.port,e.host,()=>{O.removeListener(`error`,r),t()})})}catch(e){if(se)try{vV(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let A=mH();A!==void 0&&hH(`httpListenMs`,A);let pe=O.address(),j=typeof pe==`object`&&pe?pe.port:e.port??0;if(D=j,f(T,j),se&&gV(T,j),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let me=!1,he=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};de=async()=>{if(me)return;me=!0,le=`draining`;let e=[],t=async(t,n)=>{try{await he(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),se&&yV(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{fe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ce!==null&&await t(`acpThreads.destroy`,()=>ce.destroy()),await t(`mount.shutdown`,()=>ue.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ue.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),se&&await t(`releaseUiLock`,async()=>vV(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ss()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>ms.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await w9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:C9(e.contentDir,aV(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`store-skill-migration-failed`,error:String(e)},`Store-skill in-place migration failed (non-fatal).`)}try{let e=uu(),t=await w9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:TCe,inPlaceNames:C9(e,oV(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({event:`global-store-skill-migration-failed`,error:String(e)},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await FCe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:O,destroy:de,lockDir:T,contentDir:e.contentDir,port:j,ready:C,degraded:w,didAutoInit:p,serverInstance:y,acpThreadManager:ce}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new JZ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=rd(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Cs({baseDir:n,timeout:{block:5e3}});s=new Set(await nS(e,[`diff`,`--name-only`,`--diff-filter=U`]))}}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: git unmerged probe failed — restoring all entries`)}if(s!==null){let e=0;for(let t of a)!o(t)&&!s.has(t.file)&&(i.removeConflict(t.file),e++);if(e>0&&console.warn(JSON.stringify({event:`lifecycle-restore-pruned-resolved-entries`,pruned:e,remaining:a.length-e})),a=a.filter(e=>o(e)||s?.has(e.file)),a.length===0)return}for(let e of a){let n=$S(e.file),i=null,a=!1;try{i=await t.openDirectConnection(n);let e=i.document;if(!e)continue;let r=e.getMap(`lifecycle`);r.set(`status`,`conflict`),r.set(`reason`,`conflict-markers`),a=!0,console.warn(JSON.stringify({event:`lifecycle-restored-from-conflicts-json`,"doc.name":n}))}catch(e){r.warn({err:e,docName:n},`[boot] lifecycle restore: failed to set lifecycle for doc — skipping`)}finally{if(i)try{await i.disconnect()}catch(e){r.warn({err:e,docName:n,restored:a},`[boot] lifecycle restore: disconnect failed after lifecycle write`)}}}}const HCe=ke;function UCe(e={}){let t=e.home??uu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(_s(),1);const B9=z(uu(),`.ok`,`logs`),WCe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function GCe(){let e=process.env.OK_LOG_LEVEL??process.env.LOG_LEVEL;if(e){let t=[`fatal`,`error`,`warn`,`info`,`debug`],n=e.toLowerCase();if(t.includes(n))return n}return process.env.NODE_ENV===`test`?`silent`:`info`}function KCe(e){Jl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function qCe(e){try{if(iu(e).size<5242880)return}catch{return}for(let t=2;t>=1;t--){let n=t===1?e:`${e}.${t-1}`,r=`${e}.${t}`;try{tu(n,r)}catch{}}try{au(`${e}.3`)}catch{}}function JCe(e){try{let t=Date.now(),n=10080*60*1e3,r=$l(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=iu(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{au(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{au(z(e,t.name)),a-=t.size}catch{}}}catch{}}function YCe(e){KCe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);qCe(n),(e._setTimeout??setTimeout)(()=>JCe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:GCe(),name:e.name,redact:{paths:WCe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function XCe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function ZCe(e){return z(B9,`${e}.${V9()}.log`)}function QCe(){return B9}function $Ce(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=zu(wl),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function ewe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],zF({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function twe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!iu(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=BG()}catch(e){throw e instanceof LG||e instanceof RG?(aK(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof RG?`too_old`:`not_available`,detectedVersion:e instanceof RG?e.detected:``},e instanceof RG?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await ewe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],zF({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!H(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,nwe=Kt.map(e=>e.replace(/\/$/,``));async function rwe(e){let t=rd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(swe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ws(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ss(async()=>{let t=await iwe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await awe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=ws(e,{gitIndexFile:z(pu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await owe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await eW(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Es(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${ja}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of nwe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function iwe(e){try{let t=(await e.git.raw([`rev-parse`,`--abbrev-ref`,`HEAD`])).trim();return t.length===0||t===`HEAD`?null:t}catch{return null}}async function awe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function owe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function swe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function cwe(e,t){let n;try{n=Cl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await vu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const lwe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of lwe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function uwe(e){if(!ZS(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!iu(t).isFile())throw new Q9(e);let n=R(t),r=RU(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:$S(B(dwe(e),t).split(Fl).join(`/`)),canonicalFilePath:t}}let i=kl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:$S(i)}}function dwe(e){return V(e,Fo({absPath:Lo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function fwe(e){let t=Yl(V(pu(),`ok-ephemeral-`)),n=V(t,`.ok`);return Jl(n,{recursive:!0}),ou(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),ou(V(n,`.gitignore`),`local/
2029
2029
  `,`utf-8`),t}export{Y2 as $,GS as $i,Iz as $n,nce as $r,RG as $t,X7 as A,FT as Ai,QH as An,DI as Ar,BX as At,f7 as B,dC as Bi,nH as Bn,zF as Br,vJ as Bt,p9 as C,YT as Ci,SU as Cn,jL as Cr,RZ as Ct,Z7 as D,JT as Di,bU as Dn,$le as Dr,YX as Dt,J7 as E,GT as Ei,eU as En,kL as Er,JX as Et,pSe as F,q as Fi,IH as Fn,YF as Fr,yJ as Ft,q8 as G,RS as Gi,gV as Gn,Mce as Gr,dJ as Gt,Y8 as H,lC as Hi,hV as Hn,NF as Hr,pJ as Ht,x7 as I,wC as Ii,FH as In,XF as Ir,_J as It,B8 as J,VS as Ji,nB as Jn,Sce as Jr,lK as Jt,G8 as K,zS as Ki,aB as Kn,Pce as Kr,tJ as Kt,b7 as L,_C as Li,jH as Ln,GF as Lr,bJ as Lt,R7 as M,uT as Mi,VH as Mn,JF as Mr,kJ as Mt,F7 as N,DT as Ni,NH as Nn,qF as Nr,wJ as Nt,K7 as O,UT as Oi,FU as On,rL as Or,FZ as Ot,y7 as P,TC as Pi,PH as Pn,ZF as Pr,aJ as Pt,W2 as Q,AS as Qi,Uz as Qn,dF as Qr,LG as Qt,tSe as R,uC as Ri,wH as Rn,BF as Rr,lJ as Rt,I9 as S,qu as Sa,pD as Si,tU as Sn,NL as Sr,GZ as St,G7 as T,kT as Ti,pU as Tn,AL as Tr,TX as Tt,X8 as U,KS as Ui,_V as Un,AF as Ur,fJ as Ut,l7 as V,mC as Vi,mV as Vn,PF as Vr,xJ as Vt,J8 as W,LS as Wi,vV as Wn,Fce as Wr,hJ as Wt,H2 as X,IS as Xi,Rz as Xn,EF as Xr,iK as Xt,A8 as Y,MS as Yi,Wz as Yn,yF as Yr,sK as Yt,U2 as Z,qS as Zi,Hz as Zn,ice as Zr,aK as Zt,HCe as _,ld as _a,yD as _i,RU as _n,VL as _r,WZ as _t,uwe as a,yS as aa,eN as ai,HG as an,Tz as ar,npe as at,F9 as b,id as ba,mD as bi,xU as bn,ML as br,VZ as bt,rwe as c,pae as ca,Tj as ci,OG as cn,dz as cr,K0 as ct,$Ce as d,Xh as da,xj as di,pW as dn,pz as dr,bue as dt,US as ea,uF as ei,FG as en,Fz as er,mpe as et,YCe as f,Yh as fa,yj as fi,cW as fn,mz as fr,h1 as ft,UCe as g,kd as ga,xO as gi,hW as gn,BL as gr,BZ as gt,QCe as h,Rd as ha,dj as hi,oW as hn,zL as hr,KZ as ht,fwe as i,xS as ia,tN as ii,KG as in,Dz as ir,tpe as it,W7 as j,lT as ji,BH as jn,EI as jr,MJ as jt,Y7 as k,WT as ki,yU as kn,Rle as kr,MZ as kt,W9 as l,Jh as la,Sj as li,iW as ln,fz as lr,S1 as lt,ZCe as m,Ad as ma,fj as mi,mW as mn,uR as mr,tQ as mt,Z9 as n,JS as na,lF as ni,rK as nn,Lz as nr,F2 as nt,X9 as o,_S as oa,nN as oi,MG as on,vz as or,rpe as ot,XCe as p,Ld as pa,mj as pi,_W as pn,zR as pr,v1 as pt,U8 as q,PS as qi,Zz as qn,Nce as qr,nJ as qt,$9 as r,OS as ra,cF as ri,zG as rn,Ez as rr,A2 as rt,cwe as s,uS as sa,cM as si,jG as sn,wz as sr,w2 as st,Q9 as t,WS as ta,sF as ti,BG as tn,zz as tr,I2 as tt,twe as u,qh as ua,pj as ui,fW as un,cz as ur,e1 as ut,BCe as v,cd as va,vD as vi,LU as vn,RL as vr,zZ as vt,f9 as w,ZT as wi,vU as wn,eue as wr,EX as wt,P9 as x,Ju as xa,koe as xi,nU as xn,PL as xr,UZ as xt,R9 as y,Dd as ya,_D as yi,YH as yn,aue as yr,HZ as yt,p7 as z,hC as zi,uH as zn,UF as zr,uJ as zt};
2030
- //# sourceMappingURL=src-BVOdbrbz.mjs.map
2030
+ //# sourceMappingURL=src-C9LMhuL4.mjs.map