@inkeep/open-knowledge 0.49.0-beta.15 → 0.49.0-beta.16

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 (388) hide show
  1. package/dist/{acp-harness-probe-Ce0tfHhT.mjs → acp-harness-probe-DnyVs1Kt.mjs} +2 -2
  2. package/dist/cli.mjs +7 -7
  3. package/dist/config-schema.json +21 -0
  4. package/dist/config.user.schema.json +21 -0
  5. package/dist/constants-BSI73Ayf.mjs +2 -0
  6. package/dist/fs-traced-BLumSmkJ.mjs +1 -0
  7. package/dist/{fs-traced-Cq61rC8q.mjs → fs-traced-g8Nfed1O.mjs} +2 -2
  8. package/dist/{git-handle-3e6ruSEO.mjs → git-handle-Pv8SU_Wy.mjs} +2 -2
  9. package/dist/git-handle-o1JfXOwU.mjs +1 -0
  10. package/dist/index.d.mts +14 -0
  11. package/dist/index.mjs +1 -1
  12. package/dist/{init-Di0YD1B9.mjs → init-CmOnvenq.mjs} +3 -3
  13. package/dist/init-DYXmXwDM.mjs +1 -0
  14. package/dist/{launch-json-removal-94lSgz_J.mjs → launch-json-removal-B4OxMeoc.mjs} +2 -2
  15. package/dist/loader-BixbSsQp.mjs +1 -0
  16. package/dist/{loader-B8jawu5K.mjs → loader-DJYThXyr.mjs} +2 -2
  17. package/dist/md-manager-DMhQWacM.mjs +2 -0
  18. package/dist/{open-browser-DZDWUYF1.mjs → open-browser-BisNZFSC.mjs} +2 -2
  19. package/dist/parse-worker.mjs +1 -1
  20. package/dist/{preview-Bbo353IM.mjs → preview-B8qsYLtv.mjs} +2 -2
  21. package/dist/preview-BrxsRSXN.mjs +1 -0
  22. package/dist/public/assets/{ActivityModeContent-B5po6WtG.js → ActivityModeContent-B1bZdHQD.js} +1 -1
  23. package/dist/public/assets/{AgentDiffPane-ZiZJsn41.js → AgentDiffPane-Bz05Ih7k.js} +2 -2
  24. package/dist/public/assets/{AgentThreadClientBinder-BUoEh0WV.js → AgentThreadClientBinder-RhA0fCNT.js} +1 -1
  25. package/dist/public/assets/BugReportHistory-DG-lgp18.js +1 -0
  26. package/dist/public/assets/{BugReportHistoryDialog-DlY3rGJB.js → BugReportHistoryDialog-CNv7h40y.js} +1 -1
  27. package/dist/public/assets/{ChangedOutsideBadge-Bihnu7k7.js → ChangedOutsideBadge-Do91LcVl.js} +1 -1
  28. package/dist/public/assets/CodeMirrorPropInput-Ck96DeLI.js +3 -0
  29. package/dist/public/assets/{ConsentDialogBody-B4BDndYH.js → ConsentDialogBody-Kh6K_7rD.js} +1 -1
  30. package/dist/public/assets/{DiffView-CRnGOcsK.js → DiffView-CgTOnNpK.js} +1 -1
  31. package/dist/public/assets/DocumentContext-BS6XmTzN.js +38 -0
  32. package/dist/public/assets/{EditorModeToggle-FsNFbWj8.js → EditorModeToggle-Du5l0TJh.js} +1 -1
  33. package/dist/public/assets/{EnableSyncConfirmDialog-C0LTGFxm.js → EnableSyncConfirmDialog-DuGblmka.js} +1 -1
  34. package/dist/public/assets/FeedbackForm-DaFWV8Xh.js +1 -0
  35. package/dist/public/assets/{GraphPanel-BzI8bQVI.js → GraphPanel-z9u-l6kP.js} +1 -1
  36. package/dist/public/assets/{ImportSkillDialog-DxV_cD1x.js → ImportSkillDialog-Cj-5ldJn.js} +1 -1
  37. package/dist/public/assets/{LintConfigEditor-CJLnn55b.js → LintConfigEditor-BmWDCB0X.js} +1 -1
  38. package/dist/public/assets/ManagedArtifactProperties-Bw5bFeAL.js +2 -0
  39. package/dist/public/assets/ManagedArtifactProperties-CRdAv2oe.js +1 -0
  40. package/dist/public/assets/{McpConsentDialogBody-CBMcx-oi.js → McpConsentDialogBody-BFEpwub3.js} +1 -1
  41. package/dist/public/assets/{Mermaid-VtbzVjk9.js → Mermaid-Bua4Y8k1.js} +2 -2
  42. package/dist/public/assets/{MermaidDocEditor-Cs5cY1I4.js → MermaidDocEditor-xm6g4t-n.js} +1 -1
  43. package/dist/public/assets/{RegisteredAgentIcon-DaRhHE3D.js → RegisteredAgentIcon-D-voQuM7.js} +1 -1
  44. package/dist/public/assets/{ReportBugDialogBody-CqJmw2gc.js → ReportBugDialogBody-D7q4yP-D.js} +1 -1
  45. package/dist/public/assets/{SchemaConfigEditor-T9auWtcU.js → SchemaConfigEditor--zu1g6YF.js} +1 -1
  46. package/dist/public/assets/{SessionsHost-DDSYGLPw.js → SessionsHost-DtpZGRWd.js} +2 -2
  47. package/dist/public/assets/SettingsDialogBody-CFpjH7yr.js +12 -0
  48. package/dist/public/assets/{ShareBranchSwitchDialog-DpJWy6Wx.js → ShareBranchSwitchDialog-C91vrrkW.js} +1 -1
  49. package/dist/public/assets/{ShareReceiveDialog-Chmfb4jD.js → ShareReceiveDialog-DgH3CXpp.js} +1 -1
  50. package/dist/public/assets/{ShareReceiveMissDialog-DEO-0oqX.js → ShareReceiveMissDialog-B2Bj9Xlt.js} +1 -1
  51. package/dist/public/assets/{SkillEditBanner-m23hCynE.js → SkillEditBanner-CiGVcdLf.js} +1 -1
  52. package/dist/public/assets/{SkillOriginInline-CZD9-Qds.js → SkillOriginInline-oOiulqLY.js} +1 -1
  53. package/dist/public/assets/{SkillToolbarControls-BK7HSWax.js → SkillToolbarControls-Bf-FMpDZ.js} +1 -1
  54. package/dist/public/assets/SourceEditor-BUhhAOnA.js +1 -0
  55. package/dist/public/assets/{TerminalPanel-CY8ECSUN.js → TerminalPanel-B0uk6YjD.js} +3 -3
  56. package/dist/public/assets/{TerminalWindowApp-CPTC6ix0.js → TerminalWindowApp-Dgc7JWwE.js} +1 -1
  57. package/dist/public/assets/{TextDocEditor-80U8mDiT.js → TextDocEditor-M0ORd9L6.js} +1 -1
  58. package/dist/public/assets/{ThreadView-BUoOjt6c.js → ThreadView-CgunciP2.js} +1 -1
  59. package/dist/public/assets/{TimelineDiffPane-CfmFp4dH.js → TimelineDiffPane-BD2Tv4MA.js} +2 -2
  60. package/dist/public/assets/{abnfDiagram-VRR7QNED-BmIGpDzR.js → abnfDiagram-VRR7QNED-B9waE4EK.js} +1 -1
  61. package/dist/public/assets/{agent-diff-store-B_Ggyl4B.js → agent-diff-store-IIgf47cB.js} +1 -1
  62. package/dist/public/assets/{agent-visibility-C3Lr_sAC.js → agent-visibility-BqQueoyX.js} +1 -1
  63. package/dist/public/assets/{arc-CQb2AKAx.js → arc-sbHykFJf.js} +1 -1
  64. package/dist/public/assets/architecture-TIHT7OUA-De4Q2LNd.js +1 -0
  65. package/dist/public/assets/{architectureDiagram-ZJ3FMSHR-B7kRa73u.js → architectureDiagram-ZJ3FMSHR-CTnd5XGZ.js} +1 -1
  66. package/dist/public/assets/auth-state-cache-oh0JZKQ-.js +11 -0
  67. package/dist/public/assets/{blockDiagram-677ZJIJ3-CW_RPrF5.js → blockDiagram-677ZJIJ3-FR-RGOU0.js} +1 -1
  68. package/dist/public/assets/{c4Diagram-LMCZKHZV-DSzPt7hc.js → c4Diagram-LMCZKHZV-qzwldzjO.js} +1 -1
  69. package/dist/public/assets/{calendar-00bIEN9E.js → calendar-l3O6tzZO.js} +1 -1
  70. package/dist/public/assets/channel-CYdCl3nE.js +1 -0
  71. package/dist/public/assets/chunk-2Q5K7J3B-DQitAFVg.js +1 -0
  72. package/dist/public/assets/{chunk-32BRIVSS-CZmcIudv.js → chunk-32BRIVSS-B8DvWzrL.js} +1 -1
  73. package/dist/public/assets/{chunk-52WLFC77-BVOQGRZo.js → chunk-52WLFC77-DTs6cQN0.js} +1 -1
  74. package/dist/public/assets/{chunk-5FCAYU7R-Cw8swtTn.js → chunk-5FCAYU7R-Cvx7FKhp.js} +1 -1
  75. package/dist/public/assets/{chunk-5HE753X5-BcaELnEX.js → chunk-5HE753X5-DDLUoTp6.js} +1 -1
  76. package/dist/public/assets/{chunk-5JV3BV7I-CTGgCtpC.js → chunk-5JV3BV7I-CQq8YbcR.js} +1 -1
  77. package/dist/public/assets/{chunk-5TONJI2A-Bpyxou83.js → chunk-5TONJI2A-DJSumkBm.js} +1 -1
  78. package/dist/public/assets/{chunk-5VM5RSS4-DgdH1pRm.js → chunk-5VM5RSS4-DeuOm09u.js} +1 -1
  79. package/dist/public/assets/{chunk-7BUUIJ7U-ClPt7kN-.js → chunk-7BUUIJ7U-D0g-TABj.js} +1 -1
  80. package/dist/public/assets/{chunk-BIQX33UG-mS9PjbWf.js → chunk-BIQX33UG-Dr_cIS68.js} +1 -1
  81. package/dist/public/assets/{chunk-BO2N2NFS-DPS62-Wy.js → chunk-BO2N2NFS-DixEzVLo.js} +3 -3
  82. package/dist/public/assets/{chunk-C7G6YPKG-QNP-z6to.js → chunk-C7G6YPKG-BF2KLgoZ.js} +1 -1
  83. package/dist/public/assets/{chunk-CQNSW5MT-DMMvOdGr.js → chunk-CQNSW5MT-BCjEqAgz.js} +1 -1
  84. package/dist/public/assets/{chunk-CYSBUYHQ-BICcghCa.js → chunk-CYSBUYHQ-lP6dqpno.js} +1 -1
  85. package/dist/public/assets/{chunk-EMLP6XTP-BImPFoB6.js → chunk-EMLP6XTP-BxJGpKJx.js} +1 -1
  86. package/dist/public/assets/{chunk-EX3LRPZG-CBy8mV-p.js → chunk-EX3LRPZG-ZFs8Ud7F.js} +1 -1
  87. package/dist/public/assets/{chunk-FWX5IMBZ-Be7rLA4R.js → chunk-FWX5IMBZ-Bu5gMU_H.js} +2 -2
  88. package/dist/public/assets/{chunk-HOUHSVGY-BwiBKa9M.js → chunk-HOUHSVGY-DHWvdGV6.js} +1 -1
  89. package/dist/public/assets/{chunk-ICXQ74PX-D-nICoJO.js → chunk-ICXQ74PX-CvfxiLlX.js} +1 -1
  90. package/dist/public/assets/{chunk-JG7HCLWE-Cr6K5vvd.js → chunk-JG7HCLWE-CZ5MQiHc.js} +1 -1
  91. package/dist/public/assets/{chunk-JWPE2WC7-D8-kUsSG.js → chunk-JWPE2WC7-CadUqCIq.js} +1 -1
  92. package/dist/public/assets/{chunk-MOJQB5TN-DYoKyicG.js → chunk-MOJQB5TN-BVs9yOdH.js} +1 -1
  93. package/dist/public/assets/{chunk-MOZMSUNE-Dso0Z5Dr.js → chunk-MOZMSUNE-iEBeHFDC.js} +1 -1
  94. package/dist/public/assets/{chunk-OGEWGWER-CjYwkekm.js → chunk-OGEWGWER-CSCa1WYV.js} +1 -1
  95. package/dist/public/assets/{chunk-OSBZ3O6U-DO9s6SlU.js → chunk-OSBZ3O6U-BIoNhL1K.js} +1 -1
  96. package/dist/public/assets/{chunk-PUDLZKDR-Dv5A5dRj.js → chunk-PUDLZKDR-DE8eb26d.js} +1 -1
  97. package/dist/public/assets/{chunk-Q4XR5HBZ-qovh5WM_.js → chunk-Q4XR5HBZ-CqlgmKkZ.js} +1 -1
  98. package/dist/public/assets/{chunk-QBLGF6JB-DRvINlWy.js → chunk-QBLGF6JB-DFYsDo1Y.js} +1 -1
  99. package/dist/public/assets/{chunk-R7FJI6CG-B7wiPJ88.js → chunk-R7FJI6CG-BBNc_Mta.js} +1 -1
  100. package/dist/public/assets/{chunk-RYQCIY6F-CeBzmL1V.js → chunk-RYQCIY6F-ElePRdpc.js} +1 -1
  101. package/dist/public/assets/{chunk-U6XO7XAA-B3t2ZcvG.js → chunk-U6XO7XAA-Dqow2X4f.js} +1 -1
  102. package/dist/public/assets/{chunk-V7JOEXUC-BaPGIDh2.js → chunk-V7JOEXUC-dFXMASow.js} +1 -1
  103. package/dist/public/assets/chunk-VAUOI2AC-BkgtRWuc.js +1 -0
  104. package/dist/public/assets/{chunk-VR4S4FIN-BKvzLxw6.js → chunk-VR4S4FIN-DX7kgkEZ.js} +1 -1
  105. package/dist/public/assets/{chunk-WYO6CB5R-Dee3LC03.js → chunk-WYO6CB5R-ijUMlRQg.js} +1 -1
  106. package/dist/public/assets/chunk-XXDRQBXY-D8WfEEB8.js +1 -0
  107. package/dist/public/assets/{chunk-YOTPTUD7-B9Vebq-b.js → chunk-YOTPTUD7-D6Uf5sDw.js} +1 -1
  108. package/dist/public/assets/{chunk-ZGVPDNZ5-CQRStGTR.js → chunk-ZGVPDNZ5-D-_2spuk.js} +1 -1
  109. package/dist/public/assets/{chunk-ZIRB5QZD-DEufsvtD.js → chunk-ZIRB5QZD-CGyFgxgE.js} +1 -1
  110. package/dist/public/assets/classDiagram-OUVF2IWQ-hdX1EGrF.js +1 -0
  111. package/dist/public/assets/classDiagram-v2-EOCWNBFH-CVCIHjlC.js +1 -0
  112. package/dist/public/assets/client-version-DfcLXZBn.js +1 -0
  113. package/dist/public/assets/{cm-theme-CZKVXD9s.js → cm-theme-BaOqYOXq.js} +1 -1
  114. package/dist/public/assets/{comment-chips-BhzTkUdN.js → comment-chips-B3SSmsSD.js} +1 -1
  115. package/dist/public/assets/{config-context-CjIu2e9K.js → config-context-DWBFCkMr.js} +1 -1
  116. package/dist/public/assets/config-provider-Ckcik-QN.js +5 -0
  117. package/dist/public/assets/{cose-bilkent-JH36ORCC-CoZVsSg8.js → cose-bilkent-JH36ORCC-ByC8Yy0X.js} +1 -1
  118. package/dist/public/assets/cynefin-VYW2F7L2-CVj5gwTE.js +1 -0
  119. package/dist/public/assets/{cynefinDiagram-TSTJHNR4-DPvTX2wo.js → cynefinDiagram-TSTJHNR4-BFx24SiT.js} +1 -1
  120. package/dist/public/assets/{dagre-Cvkrznc5.js → dagre-Dcc_BFy9.js} +1 -1
  121. package/dist/public/assets/{dagre-VKFMJZFB-DCyCbnWk.js → dagre-VKFMJZFB-CdzPCjFy.js} +1 -1
  122. package/dist/public/assets/{diagram-FQU43EPY-DQfED2jZ.js → diagram-FQU43EPY-BRyDDNNH.js} +1 -1
  123. package/dist/public/assets/{diagram-G47NLZAW-D_tAD-CD.js → diagram-G47NLZAW-8LNSI1k8.js} +1 -1
  124. package/dist/public/assets/{diagram-NH7WQ7WH-B2WHNVdG.js → diagram-NH7WQ7WH-Dqjr2xQ4.js} +1 -1
  125. package/dist/public/assets/{diagram-OA4YK3LP-D8DlKHon.js → diagram-OA4YK3LP-CDUcwFIA.js} +1 -1
  126. package/dist/public/assets/{diagram-WEI45ONY-CWnCxk5f.js → diagram-WEI45ONY-DRnXGROs.js} +1 -1
  127. package/dist/public/assets/{dist-BrVyfPlR.js → dist-B0ot-zCg.js} +1 -1
  128. package/dist/public/assets/{dist-BDbPHHcG.js → dist-BErgrd22.js} +1 -1
  129. package/dist/public/assets/dist-BL5nD31H.js +1 -0
  130. package/dist/public/assets/dist-BOaebJ3y.js +9 -0
  131. package/dist/public/assets/dist-BnT4p1qn.js +1 -0
  132. package/dist/public/assets/{dist-BRXePA0O.js → dist-BvnuHJmQ.js} +1 -1
  133. package/dist/public/assets/dist-BzkDKzOk.js +1 -0
  134. package/dist/public/assets/dist-ClD18cXH.js +1 -0
  135. package/dist/public/assets/dist-CpbZbACh.js +1 -0
  136. package/dist/public/assets/{dist-B2sUyimR.js → dist-DEJ4wECF.js} +1 -1
  137. package/dist/public/assets/{dist-FFXyFMEP2.js → dist-DgVI4NOf2.js} +182 -182
  138. package/dist/public/assets/dist-Dhbfk1jo.js +23 -0
  139. package/dist/public/assets/{dist-Dl_Hcem_.js → dist-RbAfUwYm2.js} +1 -1
  140. package/dist/public/assets/{dist-C5hoswyZ.js → dist-qbDvR5Vm.js} +1 -1
  141. package/dist/public/assets/{doc-paths-BT16-f7r.js → doc-paths-CvSK7JNc.js} +1 -1
  142. package/dist/public/assets/{documents-events-BYhhJH8W.js → documents-events-D0Krdb7q.js} +1 -1
  143. package/dist/public/assets/{ebnfDiagram-CCIWWBDH-CZzPuk9p.js → ebnfDiagram-CCIWWBDH-BGps-Tlh.js} +1 -1
  144. package/dist/public/assets/{erDiagram-Q63AITRT-9xYB2NMy.js → erDiagram-Q63AITRT-BAZLcThH.js} +1 -1
  145. package/dist/public/assets/eventmodeling-45OFAUF4-B6vt2_IC.js +1 -0
  146. package/dist/public/assets/{file-tree-adapter-5NHUF1AU.js → file-tree-adapter-DYMUSVB5.js} +1 -1
  147. package/dist/public/assets/{file-tree-utils-Dfu7Cauy.js → file-tree-utils-U_gH0LWE.js} +1 -1
  148. package/dist/public/assets/flowDiagram-23GEKE2U-nxJZ6d_P.js +1 -0
  149. package/dist/public/assets/{folder-config-api-CgtASyeO.js → folder-config-api-C6ekp4Ky.js} +1 -1
  150. package/dist/public/assets/{follow-file-qiIw6X4h.js → follow-file-F7kwrB0K.js} +1 -1
  151. package/dist/public/assets/{ganttDiagram-NO4QXBWP-DijtRRdy.js → ganttDiagram-NO4QXBWP-CnY3tYS4.js} +1 -1
  152. package/dist/public/assets/gherkin-85A09uvl.js +1 -0
  153. package/dist/public/assets/gitGraph-TEB2WS4Q-CrRmctIi.js +1 -0
  154. package/dist/public/assets/{gitGraphDiagram-IHSO6WYX-v6F97UcV.js → gitGraphDiagram-IHSO6WYX-B8O8fZOS.js} +1 -1
  155. package/dist/public/assets/globals-CrUZfUVm.css +1 -0
  156. package/dist/public/assets/{globals-BkB_jgyG.js → globals-DktXHqb9.js} +2 -2
  157. package/dist/public/assets/{graphlib-DhNu5XTn.js → graphlib-qiycimrL.js} +1 -1
  158. package/dist/public/assets/{highlighted-body-OFNGDK62-DxF-jfal.js → highlighted-body-OFNGDK62-C_afdV86.js} +1 -1
  159. package/dist/public/assets/i18n-Ci29nkvq.js +1 -0
  160. package/dist/public/assets/index-D346rxmT.js +2097 -0
  161. package/dist/public/assets/info-DKCQHKI2-BDbq3Equ.js +1 -0
  162. package/dist/public/assets/{infoDiagram-FWYZ7A6U-CZFjeYGc.js → infoDiagram-FWYZ7A6U-Bq0Uw4YR.js} +1 -1
  163. package/dist/public/assets/{input-group-pOmI7K9l.js → input-group-DosHKmfV.js} +1 -1
  164. package/dist/public/assets/{ishikawaDiagram-FXEZZL3T-CkYYfkzy.js → ishikawaDiagram-FXEZZL3T-CLXVFxrS.js} +1 -1
  165. package/dist/public/assets/{journeyDiagram-5HDEW3XC-jznzpifp.js → journeyDiagram-5HDEW3XC-Xt4a8WCT.js} +1 -1
  166. package/dist/public/assets/{kanban-definition-HUTT4EX6-DvW7rPep.js → kanban-definition-HUTT4EX6-2N8NvoYZ.js} +1 -1
  167. package/dist/public/assets/{line-D74h8yJj.js → line-CHX77dzi.js} +1 -1
  168. package/dist/public/assets/{linear-wPQKtCnF.js → linear-CG7OsDbr.js} +1 -1
  169. package/dist/public/assets/{lint-config-client-aw9JiA9H.js → lint-config-client-DLSwD_yF.js} +1 -1
  170. package/dist/public/assets/{map-BUSC3AEl.js → map-CCFSzMRB.js} +1 -1
  171. package/dist/public/assets/{markdownlint-rule-browser-BqwmUz9N.js → markdownlint-rule-browser-DTTo6sys.js} +1 -1
  172. package/dist/public/assets/mermaid-GHXKKRXX-Cay2e487.js +1 -0
  173. package/dist/public/assets/{mermaid-parser.core-CIlXyQdh.js → mermaid-parser.core-D3_-DH8J.js} +2 -2
  174. package/dist/public/assets/{mermaid.core-DZMFZPvc.js → mermaid.core-BfTrAtoH.js} +3 -3
  175. package/dist/public/assets/messages-BAf5RiDt.js +1 -0
  176. package/dist/public/assets/messages-BNaSEGlm.js +1 -0
  177. package/dist/public/assets/messages-BZGasE0y.js +1 -0
  178. package/dist/public/assets/messages-BiaRA9eO.js +1 -0
  179. package/dist/public/assets/messages-CAxz6nlh.js +1 -0
  180. package/dist/public/assets/messages-CQ-KVdTd.js +1 -0
  181. package/dist/public/assets/messages-CT4CGdYa.js +1 -0
  182. package/dist/public/assets/messages-C_h77qzk.js +1 -0
  183. package/dist/public/assets/messages-ClPhVClm.js +1 -0
  184. package/dist/public/assets/messages-Dct80Zji.js +1 -0
  185. package/dist/public/assets/messages-EIESpA1C.js +1 -0
  186. package/dist/public/assets/{mindmap-definition-LN4V7U3C-Bm6pRarL.js → mindmap-definition-LN4V7U3C-wo5DyuZj.js} +1 -1
  187. package/dist/public/assets/{navigation-targets-BB54n_r7.js → navigation-targets-DOPPSLGO.js} +1 -1
  188. package/dist/public/assets/{now-Dj28ysYF.js → now-D_D35T9Z.js} +1 -1
  189. package/dist/public/assets/{open-managed-artifact-tab-B-SCOaEl.js → open-managed-artifact-tab-H6-v57bY.js} +1 -1
  190. package/dist/public/assets/{ordinal-DXfwmpMf.js → ordinal-i63Qg2i5.js} +1 -1
  191. package/dist/public/assets/packet-7NZHBO7P-BSel13EB.js +1 -0
  192. package/dist/public/assets/{pegDiagram-2B236MQR-U4Q3CpHD.js → pegDiagram-2B236MQR-G8WYx7hb.js} +1 -1
  193. package/dist/public/assets/{pending-receive-nav-store-CKgZuSOc.js → pending-receive-nav-store-DeqVt2UQ.js} +1 -1
  194. package/dist/public/assets/pie-RZYD4A2V-C2Tifyp2.js +1 -0
  195. package/dist/public/assets/{pieDiagram-ENE6RG2P-Y_b1t_zS.js → pieDiagram-ENE6RG2P-BAaCtGbD.js} +1 -1
  196. package/dist/public/assets/{prop-types-BlWArB_E.js → prop-types-Az_QdOEW.js} +1 -1
  197. package/dist/public/assets/{quadrantDiagram-ABIIQ3AL-9TnfTiwS.js → quadrantDiagram-ABIIQ3AL-BTya7X9H.js} +1 -1
  198. package/dist/public/assets/radar-I7S5WNFK-CcbaGPcm.js +1 -0
  199. package/dist/public/assets/railroad-3IZDKUUU-wNnjIbGG.js +1 -0
  200. package/dist/public/assets/railroad-abnf-AHOZXSZD-DlFOCLj9.js +1 -0
  201. package/dist/public/assets/railroad-ebnf-EBAXGLYW-RMzZnNf7.js +1 -0
  202. package/dist/public/assets/railroad-peg-LSFZ7HO6-ByexGK8C.js +1 -0
  203. package/dist/public/assets/{railroadDiagram-RFXS5EU6-BUV8iUi_.js → railroadDiagram-RFXS5EU6-pH4k8bdb.js} +1 -1
  204. package/dist/public/assets/receive-store-DDFCZ_zF.js +2 -0
  205. package/dist/public/assets/{requirementDiagram-TGXJPOKE-GHTFtFmR.js → requirementDiagram-TGXJPOKE-DZL8HnEm.js} +1 -1
  206. package/dist/public/assets/{sankeyDiagram-HTMAVEWB-C8cmLYHE.js → sankeyDiagram-HTMAVEWB-DCS6FztW.js} +1 -1
  207. package/dist/public/assets/{schema-fields-view-intent-YAQkuTWi.js → schema-fields-view-intent-DCPR-Ln-.js} +1 -1
  208. package/dist/public/assets/{selection-context-D_wjAabH.js → selection-context-BZairyTK.js} +1 -1
  209. package/dist/public/assets/{sequenceDiagram-DBY2YBRQ-Bt7zFhks.js → sequenceDiagram-DBY2YBRQ-B82XIxPS.js} +1 -1
  210. package/dist/public/assets/{sizeCapture-X5ZJPWSS-BU3nTQLQ.js → sizeCapture-X5ZJPWSS-BHfXXjP_.js} +1 -1
  211. package/dist/public/assets/{skill-actions-C6iaHDPS.js → skill-actions-BlQDV2hj.js} +2 -2
  212. package/dist/public/assets/{skill-scope-UBfnFDb4.js → skill-scope-aJE1TjDP.js} +1 -1
  213. package/dist/public/assets/{skills-api-9ALineK1.js → skills-api-CuoEB5QE.js} +1 -1
  214. package/dist/public/assets/{src-b2zZu8bk.js → src-BGTHc4YS.js} +2 -2
  215. package/dist/public/assets/{src-B5Uf_H4s.js → src-CO43ViIY.js} +1 -1
  216. package/dist/public/assets/{stateDiagram-2N3HPSRC-BUIZZrgp.js → stateDiagram-2N3HPSRC-Bd5fbfEF.js} +1 -1
  217. package/dist/public/assets/stateDiagram-v2-6OUMAXLB-BoLZPody.js +1 -0
  218. package/dist/public/assets/{swimlanes-5IMT3BWC-bO40Bo1P.js → swimlanes-5IMT3BWC-Ce1zs3rj.js} +2 -2
  219. package/dist/public/assets/swimlanesDiagram-G3AALYLV-CGtxrbZp.js +8 -0
  220. package/dist/public/assets/{tag-pill-input-kaP2lmgo.js → tag-pill-input-B8NePzc1.js} +1 -1
  221. package/dist/public/assets/{target-navigation-intent-CS2r1eMb.js → target-navigation-intent-DLiIAPkk.js} +1 -1
  222. package/dist/public/assets/{telemetry-impl-BsfnaFQP.js → telemetry-impl-DONiTzZ_.js} +2 -2
  223. package/dist/public/assets/{telemetry-startup-DDHLFOTt.js → telemetry-startup-BfG2Lp3W.js} +1 -1
  224. package/dist/public/assets/{terminal-launch-events-DKgbFSpL.js → terminal-launch-events--SP0Oc1n.js} +1 -1
  225. package/dist/public/assets/{terminal-telemetry-CY2tEm12.js → terminal-telemetry-FuU-LPps.js} +1 -1
  226. package/dist/public/assets/text-viewer-languages-CSk_u3CS.js +2 -0
  227. package/dist/public/assets/{timeline-definition-FHXFAJF6-BoGbaR7E.js → timeline-definition-FHXFAJF6-B8f83LnN.js} +1 -1
  228. package/dist/public/assets/treeView-QDETBFTQ-Dpmvwpjy.js +1 -0
  229. package/dist/public/assets/treemap-6X3UGDF4-coL9Lbtu.js +1 -0
  230. package/dist/public/assets/{typing-burst-detector-BOg_zjfO.js → typing-burst-detector-D84nemKz.js} +3 -3
  231. package/dist/public/assets/uninstall-DI99nm7f.js +1 -0
  232. package/dist/public/assets/{use-activity-panel-B0S1WvGg.js → use-activity-panel-BFXhDZXM.js} +1 -1
  233. package/dist/public/assets/{use-collab-url-CVs0Opja.js → use-collab-url-DksYHz7U.js} +1 -1
  234. package/dist/public/assets/{use-live-xterm-theme-sbqUOBNg.js → use-live-xterm-theme-DzoPADl1.js} +1 -1
  235. package/dist/public/assets/{use-open-skill-rBEbc_V6.js → use-open-skill-B7tHrEgg.js} +1 -1
  236. package/dist/public/assets/{use-settings-route-UI-dlJz3.js → use-settings-route-B4yac1Dy.js} +1 -1
  237. package/dist/public/assets/{use-skill-directory-D9WsFuCq.js → use-skill-directory-BZ1cvffd.js} +1 -1
  238. package/dist/public/assets/{use-skill-origin-V3GZkGVc.js → use-skill-origin-B5Z8v2uI.js} +1 -1
  239. package/dist/public/assets/{use-skills-CvHLXmrt.js → use-skills-CRf-LvEH.js} +1 -1
  240. package/dist/public/assets/{use-terminal-enabled-B1WBXw0T.js → use-terminal-enabled-U5IlfCxf.js} +1 -1
  241. package/dist/public/assets/{use-timeline-entry-diff-B9l_gpfZ.js → use-timeline-entry-diff-B5w_FXM0.js} +4 -4
  242. package/dist/public/assets/{use-workspace-D9sCUZUt.js → use-workspace-BV2GDUTP.js} +1 -1
  243. package/dist/public/assets/{vennDiagram-L72KCM5P-CAtXcJOo.js → vennDiagram-L72KCM5P-C6FxywcL.js} +1 -1
  244. package/dist/public/assets/wardley-OPB4EBWU-DvXXACDx.js +1 -0
  245. package/dist/public/assets/{wardleyDiagram-EHGQE667-mlGW_wQr.js → wardleyDiagram-EHGQE667-BDmpdoJa.js} +1 -1
  246. package/dist/public/assets/{xychartDiagram-FW5EYKEG-B_lKj_cv.js → xychartDiagram-FW5EYKEG-B-T7f0dr.js} +1 -1
  247. package/dist/public/index.html +112 -89
  248. package/dist/public/uninstall.html +9 -7
  249. package/dist/{repair-launch-json-7YVtnaAc.mjs → repair-launch-json-CyF6Yobl.mjs} +2 -2
  250. package/dist/{repair-mcp-configs-Cdf96gPC.mjs → repair-mcp-configs-Bk1NJXTE.mjs} +2 -2
  251. package/dist/{repair-skills-BAusSdNE.mjs → repair-skills-C-Uxi1F_.mjs} +2 -2
  252. package/dist/repair-skills-iaAxRm65.mjs +1 -0
  253. package/dist/schemas/v0/config.user.schema.json +21 -0
  254. package/dist/{server-lock-Dc1sKhMm.mjs → server-lock-CAxliK3N.mjs} +2 -2
  255. package/dist/server-lock-f0YUD9MT.mjs +1 -0
  256. package/dist/{skill-teardown-Civ13nQy.mjs → skill-teardown-CPU2PCBb.mjs} +2 -2
  257. package/dist/{sleep-ByqzSHar.mjs → sleep-ChnoPlNg.mjs} +5 -5
  258. package/dist/{src-CSv3k56d.mjs → src-BxACkU3c.mjs} +6 -6
  259. package/dist/{src-joEY89vd.mjs → src-CaZ8mGsw.mjs} +2 -2
  260. package/dist/{src-Cx1wkeXN.mjs → src-Dfodvsqg.mjs} +1 -1
  261. package/dist/{src-1Bl34H5k.mjs → src-Xqdqp-3u.mjs} +2 -2
  262. package/dist/{start-CtQAE6DT.mjs → start-B8YAUXgo.mjs} +3 -3
  263. package/dist/start-CU9OGOab.mjs +1 -0
  264. package/dist/{write-project-skill-DLbZanxo.mjs → write-project-skill-C7EVY5xL.mjs} +2 -2
  265. package/package.json +5 -5
  266. package/dist/constants-BG-_TaCy.mjs +0 -2
  267. package/dist/fs-traced-WMTb98_i.mjs +0 -1
  268. package/dist/git-handle-Ca0yLTy3.mjs +0 -1
  269. package/dist/init-CypeIpDY.mjs +0 -1
  270. package/dist/loader-Bl5ihPef.mjs +0 -1
  271. package/dist/md-manager-DTsQm4IH.mjs +0 -2
  272. package/dist/preview-BhLZ6TAG.mjs +0 -1
  273. package/dist/public/assets/BugReportHistory-CYOPGlVT.js +0 -1
  274. package/dist/public/assets/CodeMirrorPropInput-CnRlIy5L.js +0 -3
  275. package/dist/public/assets/DocumentContext-CUIMtHot.js +0 -38
  276. package/dist/public/assets/FeedbackForm-DwuqNU9P.js +0 -1
  277. package/dist/public/assets/ManagedArtifactProperties--55KwZ-r.js +0 -1
  278. package/dist/public/assets/ManagedArtifactProperties-Ub0g1I2w.js +0 -2
  279. package/dist/public/assets/SettingsDialogBody-CayS2Oyi.js +0 -12
  280. package/dist/public/assets/SourceEditor-JAuf0ZLh.js +0 -1
  281. package/dist/public/assets/architecture-TIHT7OUA-DFOTFBbr.js +0 -1
  282. package/dist/public/assets/auth-state-cache-48tXQsrs.js +0 -11
  283. package/dist/public/assets/channel-CTYqt4g0.js +0 -1
  284. package/dist/public/assets/chunk-2Q5K7J3B-ML0MRNMu.js +0 -1
  285. package/dist/public/assets/chunk-VAUOI2AC-BXR6IYEq.js +0 -1
  286. package/dist/public/assets/chunk-XXDRQBXY-svK-_SE4.js +0 -1
  287. package/dist/public/assets/classDiagram-OUVF2IWQ-xqPvGsM8.js +0 -1
  288. package/dist/public/assets/classDiagram-v2-EOCWNBFH-DltLtkHS.js +0 -1
  289. package/dist/public/assets/client-version-DZVDd3p2.js +0 -1
  290. package/dist/public/assets/config-provider-CNEA51rl.js +0 -4
  291. package/dist/public/assets/cynefin-VYW2F7L2-DckB7g1t.js +0 -1
  292. package/dist/public/assets/dist-4GhcOoys2.js +0 -1
  293. package/dist/public/assets/dist-BHXZ_sfW.js +0 -1
  294. package/dist/public/assets/dist-BZfOq7Dy.js +0 -9
  295. package/dist/public/assets/dist-CApADOW3.js +0 -1
  296. package/dist/public/assets/dist-CLZZzoNM.js +0 -1
  297. package/dist/public/assets/dist-D5b61U8h.js +0 -23
  298. package/dist/public/assets/dist-eB1cZ_1W.js +0 -1
  299. package/dist/public/assets/eventmodeling-45OFAUF4-BAwLtOJ-.js +0 -1
  300. package/dist/public/assets/flowDiagram-23GEKE2U-DZlqleoU.js +0 -1
  301. package/dist/public/assets/gitGraph-TEB2WS4Q-CtXzB9IZ.js +0 -1
  302. package/dist/public/assets/globals-DAsZiYWs.css +0 -1
  303. package/dist/public/assets/index-DILBplC4.js +0 -2091
  304. package/dist/public/assets/info-DKCQHKI2-aojnuX4Q.js +0 -1
  305. package/dist/public/assets/mermaid-GHXKKRXX-DA5mXckx.js +0 -1
  306. package/dist/public/assets/packet-7NZHBO7P-C8VjP4xX.js +0 -1
  307. package/dist/public/assets/pie-RZYD4A2V-D3CTWt5e.js +0 -1
  308. package/dist/public/assets/radar-I7S5WNFK-CiwvsxWN.js +0 -1
  309. package/dist/public/assets/railroad-3IZDKUUU-BiSgeyR-.js +0 -1
  310. package/dist/public/assets/railroad-abnf-AHOZXSZD-MgQ9GoYd.js +0 -1
  311. package/dist/public/assets/railroad-ebnf-EBAXGLYW-CpD9c-Np.js +0 -1
  312. package/dist/public/assets/railroad-peg-LSFZ7HO6-BkiQ4XAA.js +0 -1
  313. package/dist/public/assets/receive-store-8JT58I8W.js +0 -2
  314. package/dist/public/assets/stateDiagram-v2-6OUMAXLB-BMvTsdCm.js +0 -1
  315. package/dist/public/assets/swimlanesDiagram-G3AALYLV-Bw_QSWFE.js +0 -8
  316. package/dist/public/assets/text-viewer-languages-Cg0FdkAb.js +0 -2
  317. package/dist/public/assets/treeView-QDETBFTQ-Ccor-UCe.js +0 -1
  318. package/dist/public/assets/treemap-6X3UGDF4-ivqx2UNe.js +0 -1
  319. package/dist/public/assets/uninstall-CTlK5Oun.js +0 -1
  320. package/dist/public/assets/wardley-OPB4EBWU-D8CQEbqs.js +0 -1
  321. package/dist/repair-skills-DluI8IZ-.mjs +0 -1
  322. package/dist/server-lock-BRHlHA0v.mjs +0 -1
  323. package/dist/start-DbRUS7U-.mjs +0 -1
  324. /package/dist/public/assets/{ActivityPanelDiffView-BHV3BqCQ.js → ActivityPanelDiffView-DCP4nm4W.js} +0 -0
  325. /package/dist/public/assets/{AppMenubar-DEpF6h8q.js → AppMenubar-C4qV1iIf.js} +0 -0
  326. /package/dist/public/assets/{SkillModeBanner-C_1eHet3.js → SkillModeBanner-BOYKyVNe.js} +0 -0
  327. /package/dist/public/assets/{__vite-browser-external-o4WEX2mj.js → __vite-browser-external-Bn1sh2Cg.js} +0 -0
  328. /package/dist/public/assets/{agent-presence-cKIGljxI.js → agent-presence-DzEPID7X.js} +0 -0
  329. /package/dist/public/assets/{array-DNx71GJU.js → array-Bwq1tsYl.js} +0 -0
  330. /package/dist/public/assets/{asset-dispatch-BZz3JZpZ.js → asset-dispatch-CXdMYaob.js} +0 -0
  331. /package/dist/public/assets/{auth-prompt-store-DaAbCGBh.js → auth-prompt-store--WPFCFKX.js} +0 -0
  332. /package/dist/public/assets/{badge-CBU6CQBJ.js → badge-C9Et23R8.js} +0 -0
  333. /package/dist/public/assets/{chunk-KEIR6QF5-D_HfbxQ3.js → chunk-KEIR6QF5-cfnN9NSb.js} +0 -0
  334. /package/dist/public/assets/{chunk-Y2CYZVJY-CTUIHOWN.js → chunk-Y2CYZVJY-xoDw0I5N.js} +0 -0
  335. /package/dist/public/assets/{clike-DJzNA5uw.js → clike-BPG93dt2.js} +0 -0
  336. /package/dist/public/assets/{clipboard-adapter-jV7IP0XO.js → clipboard-adapter-a6RtqkBy.js} +0 -0
  337. /package/dist/public/assets/{colors-DY6SwyM_.js → colors-DQOebPbz.js} +0 -0
  338. /package/dist/public/assets/{copilot-QWlqAzS5.js → copilot-DyClikmk.js} +0 -0
  339. /package/dist/public/assets/{cursor-C6NZ_NjT.js → cursor-CMobJCAT.js} +0 -0
  340. /package/dist/public/assets/{cytoscape.esm-BUTyEMz2.js → cytoscape.esm-qlH0uBlY.js} +0 -0
  341. /package/dist/public/assets/{defaultLocale-4pz4GyJ6.js → defaultLocale-DeVSBSL_.js} +0 -0
  342. /package/dist/public/assets/{desktop-bridge-types-BIAMkfnk.js → desktop-bridge-types-iItooYXJ.js} +0 -0
  343. /package/dist/public/assets/{diff-UfOtcPBF.js → diff-DCsPLkjo.js} +0 -0
  344. /package/dist/public/assets/{dist-CVvcgj09.js → dist-B7yUMXxJ.js} +0 -0
  345. /package/dist/public/assets/{dist-CWy8xH6X.js → dist-DB-5PbqJ.js} +0 -0
  346. /package/dist/public/assets/{dist-B4r_A2mw.js → dist-DiSMJpcl.js} +0 -0
  347. /package/dist/public/assets/{documents-fetch-CoP66yPf.js → documents-fetch-BFEC452a.js} +0 -0
  348. /package/dist/public/assets/{external-link-DT5mGYp0.js → external-link-DDbTQGpL.js} +0 -0
  349. /package/dist/public/assets/{file-tree-rename-validation-BB1aD1Pp.js → file-tree-rename-validation-C978B2yc.js} +0 -0
  350. /package/dist/public/assets/{form-IV9p7CBQ.js → form-BUN5O-RY.js} +0 -0
  351. /package/dist/public/assets/{format-KYHSRwuS.js → format-PzvEBOT-.js} +0 -0
  352. /package/dist/public/assets/{go-CdNSAW6a.js → go-BErErolW.js} +0 -0
  353. /package/dist/public/assets/{init-D4gOVDL_.js → init--lqjo2WF.js} +0 -0
  354. /package/dist/public/assets/{isObject-CUKQpKBO.js → isObject-CnDWjgGz.js} +0 -0
  355. /package/dist/public/assets/{libesm-CbHWK9K3.js → libesm-55kviNAY.js} +0 -0
  356. /package/dist/public/assets/{lint-plugin-meta-DZaKA5-M.js → lint-plugin-meta-DG13BaAH.js} +0 -0
  357. /package/dist/public/assets/{lru-string-cache-EoEYEZ4C.js → lru-string-cache-DBeVQG4Q.js} +0 -0
  358. /package/dist/public/assets/{lua-BjC_YWX_.js → lua-CeWJy5gJ.js} +0 -0
  359. /package/dist/public/assets/{mcp-consent-store-DZN0FT4T.js → mcp-consent-store-IOrsu48j.js} +0 -0
  360. /package/dist/public/assets/{min-x3trf8Wh.js → min-Xfg-0lOG.js} +0 -0
  361. /package/dist/public/assets/{overlay-layers-Dulb79gg.js → overlay-layers-kYO2Hl8E.js} +0 -0
  362. /package/dist/public/assets/{panel-DFoqAiSq.js → panel-BqgfZ4RF.js} +0 -0
  363. /package/dist/public/assets/{panzoom.es-DKn8NuHU.js → panzoom.es-BYikisPL.js} +0 -0
  364. /package/dist/public/assets/{parse-api-error-CulWAL3N.js → parse-api-error-B1SxBFxO.js} +0 -0
  365. /package/dist/public/assets/{path-CPUiTFzQ.js → path-BeGdDfw0.js} +0 -0
  366. /package/dist/public/assets/{pdf-UdiWtmKI.js → pdf-BLosdk5g.js} +0 -0
  367. /package/dist/public/assets/{pdf.worker-CVlM3MGW.js → pdf.worker-DWcRJEtr.js} +0 -0
  368. /package/dist/public/assets/{perl-B5kh9uCS.js → perl-XkmXldY5.js} +0 -0
  369. /package/dist/public/assets/{properties-DW_pwOFE.js → properties-DKx9JIgS.js} +0 -0
  370. /package/dist/public/assets/{r-HIDEBO1S.js → r-BiwnqVvR.js} +0 -0
  371. /package/dist/public/assets/{rough.esm-Do3Mexf5.js → rough.esm-Cb5P8xvg.js} +0 -0
  372. /package/dist/public/assets/{ruby-mktTWmhU.js → ruby-xxrHyBNI.js} +0 -0
  373. /package/dist/public/assets/{share-metadata-rows-BgvfdoD5.js → share-metadata-rows-DAx7y6kC.js} +0 -0
  374. /package/dist/public/assets/{shell-DW-sch3D.js → shell-Ct18AN_z.js} +0 -0
  375. /package/dist/public/assets/{skeleton-C4vRhplG.js → skeleton-CcN1qHDt.js} +0 -0
  376. /package/dist/public/assets/{sortable.esm-Db0q_rOi.js → sortable.esm-C4qR9epO.js} +0 -0
  377. /package/dist/public/assets/{sql-BnT59v2q.js → sql-CLSfVrfA.js} +0 -0
  378. /package/dist/public/assets/{src-B5LmWD6e.js → src-drjIkPVa.js} +0 -0
  379. /package/dist/public/assets/{startup-marks-CeDK0_f3.js → startup-marks-CJaYfJio.js} +0 -0
  380. /package/dist/public/assets/{stex-dEyUgtYN.js → stex-Dxu2B0oS.js} +0 -0
  381. /package/dist/public/assets/{swift-D-oQbKZh.js → swift-D5PyBHC5.js} +0 -0
  382. /package/dist/public/assets/{textarea-Do-HJCDs.js → textarea-nj8IYW6k.js} +0 -0
  383. /package/dist/public/assets/{thread-client-BNgrlAbM.js → thread-client-C46aiMD1.js} +0 -0
  384. /package/dist/public/assets/{thread-draft-staging-DL81pG7_.js → thread-draft-staging-B-_SkQVw.js} +0 -0
  385. /package/dist/public/assets/{timeline-diff-store-Ct1wjBoU.js → timeline-diff-store-Cl3Q73PI.js} +0 -0
  386. /package/dist/public/assets/{toml-B8_D8Hcu.js → toml-DkaiECsV.js} +0 -0
  387. /package/dist/public/assets/{use-installed-clis-CA__SZ2w.js → use-installed-clis-BgGBXIKu.js} +0 -0
  388. /package/dist/public/assets/{useLintConfigViewMode-ByY6MPfT.js → useLintConfigViewMode-Bv63NPvA.js} +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 E,Z as D,_ as ne,_t as O,at as k,b as re,bt as A,ct as ie,d as ae,dt as j,et as oe,f as se,ft as ce,g as le,gt as ue,ht as de,i as fe,it as M,jt as pe,kt as me,l as he,lt as ge,mt as N,n as _e,nt as ve,ot as ye,pt as P,q as be,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 Ae}from"./sleep-ByqzSHar.mjs";import{$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,Cs as nt,Ct as rt,D as it,Da as at,Di as ot,Dn as st,Do as ct,Dr as lt,Dt as ut,E as dt,Ea as ft,Ei as pt,En as mt,Er as ht,Es as gt,Et as _t,F as vt,Fi as yt,Fn as bt,Fo as xt,Fr as eee,Ft as St,G as Ct,Ga as wt,Gi as Tt,Gn as Et,Gr as tee,Gt as Dt,H as Ot,Ha as kt,Hi as At,Hn as nee,Hr as jt,Ht as Mt,I as Nt,Ia as Pt,Ii as Ft,In as It,Io as Lt,Ir as Rt,It as zt,J as Bt,Ja as Vt,Ji as ree,Jn as iee,Jo as Ht,Jr as Ut,Jt as Wt,K as Gt,Ka as Kt,Ki as qt,Kn as Jt,Ko as Yt,Kr as aee,Kt as Xt,L as Zt,La as Qt,Li as oee,Ln as see,Lr as cee,M as $t,Ma as en,Mi as tn,Mn as nn,Mo as rn,Mr as an,Mt as on,N as sn,Na as cn,Ni as ln,Nn as un,No as dn,Nr as fn,Nt as pn,O as mn,Oa as hn,Oi as gn,On as _n,Oo as vn,Or as lee,Ot as yn,P as bn,Pa as xn,Pi as uee,Pn as Sn,Po as Cn,Pr as wn,Pt as Tn,Qa as En,Qi as Dn,Qn as On,Qo as kn,Qr as An,Qt as jn,R as Mn,Ra as Nn,Ri as Pn,Rn as Fn,Ro as In,Rr as Ln,S as Rn,Sa as zn,Si as Bn,Sn as Vn,So as Hn,Sr as Un,Ss as Wn,St as Gn,T as dee,Ta as Kn,Ti as qn,Tn as fee,To as Jn,Tr as Yn,Ts as Xn,Tt as Zn,U as Qn,Ua as $n,Ui as pee,Un as mee,Uo as er,Ur as hee,Ut as tr,V as nr,Va as gee,Vi as _ee,Vn as rr,Vo as ir,Vr as ar,Vt as or,W as sr,Wa as cr,Wi as lr,Wn as ur,Wo as dr,Wr as fr,Wt as pr,Xa as mr,Xi as hr,Xn as gr,Xo as _r,Xr as vr,Xt as yr,Y as br,Ya as xr,Yi as Sr,Yn as Cr,Yo as wr,Yr as Tr,Yt as Er,Z as Dr,Za as Or,Zi as kr,Zn as Ar,Zo as jr,Zr as Mr,Zt as Nr,_ as Pr,_a as Fr,_i as Ir,_n as Lr,_o as Rr,_r as zr,_s as Br,_t as Vr,a as Hr,aa as Ur,ai as Wr,an as Gr,ao as Kr,ar as qr,as as Jr,at as Yr,b as Xr,ba as vee,bi as Zr,bn as yee,bo as Qr,br as bee,bs as xee,bt as $r,c as ei,ca as ti,ci as ni,cn as See,co as ri,cr as Cee,cs as ii,ct as ai,d as oi,da as si,di as ci,dn as wee,do as li,dr as Tee,ds as ui,dt as di,ea as fi,ei as pi,en as mi,eo as hi,er as gi,es as _i,et as vi,f as yi,fa as bi,fi as xi,fn as Si,fo as Ci,fr as wi,fs as Ti,ft as Ei,g as Di,ga as Oi,gi as ki,gn as Ai,gr as ji,gs as Mi,gt as Ni,h as Pi,ha as Fi,hi as Ii,hn as Li,hr as Ri,hs as zi,ht as Bi,i as Vi,ia as Hi,ii as Ui,in as Wi,io as Gi,ir as Ki,is as qi,it as Ji,j as Yi,ja as Xi,ji as Zi,jn as Qi,jr as $i,jt as ea,k as ta,ka as na,ki as ra,kn as ia,ko as aa,kr as oa,ks as sa,kt as ca,l as la,la as ua,li as da,ln as fa,lr as pa,ls as ma,lt as ha,ma as ga,mi as _a,mn as va,mo as ya,mr as ba,ms as xa,mt as Sa,n as Ca,na as wa,ni as Eee,nn as Ta,no as Dee,nr as Ea,nt as Da,o as Oa,oa as ka,oi as Oee,on as kee,oo as Aee,or as jee,os as Aa,ot as ja,p as Ma,pa as Mee,pi as Nee,pn as Pee,pr as Fee,ps as Iee,pt as Na,q as Pa,qa as Lee,qi as Ree,qn as zee,qo as Fa,qr as Bee,qt as Ia,r as La,ra as Ra,ri as Vee,rn as Hee,ro as Uee,rr as za,rs as Ba,rt as Va,s as Ha,sa as Ua,si as Wee,sn as Gee,so as Wa,sr as Kee,ss as Ga,st as Ka,t as qa,ta as Ja,ti as qee,tn as Jee,to as Yee,tr as Xee,ts as Ya,tt as Xa,u as Za,ua as Qa,ui as $a,un as eo,uo as to,ur as no,us as ro,ut as io,v as ao,va as oo,vi as so,vn as co,vo as lo,vr as uo,vs as fo,vt as po,w as mo,wa as ho,wi as go,wn as _o,wr as vo,ws as yo,wt as bo,x as xo,xa as So,xi as Co,xn as wo,xr as To,xs as Eo,xt as Do,y as Oo,ya as ko,yi as Ao,yn as jo,yo as Mo,yr as No,ys as Po,yt as Fo,za as Io,zi as Lo,zn as Ro,zo,zr as Bo,zt as Vo}from"./src-1Bl34H5k.mjs";import{c as Ho,i as Uo,l as Wo,n as Go,s as Ko}from"./esm-DxvI2ZVA.mjs";import{n as qo,t as Jo}from"./md-manager-DTsQm4IH.mjs";import{A as Yo,C as Xo,D as Zo,E as Qo,F as $o,N as es,O as ts,S as ns,T as rs,_ as is,a as as,b as os,c as ss,d as cs,f as ls,g as us,h as ds,i as fs,j as ps,k as ms,l as hs,m as gs,n as _s,o as vs,p as ys,r as bs,s as xs,t as Ss,u as Cs,v as ws,w as Ts,x as Es,y as Ds}from"./fs-traced-Cq61rC8q.mjs";import{D as Os,E as ks,S as As,T as js,a as Ms,b as Ns,l as Ps,p as Fs,r as I,s as Is,x as Ls,y as Rs}from"./logger-BZPV1wv8.mjs";import{a as zs,i as Bs,o as Vs,r as Hs,s as Us,t as Ws}from"./git-handle-3e6ruSEO.mjs";import{S as Gs,a as Ks,b as Zee,c as qs,d as Js,f as Ys,g as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,r as nc,x as rc,y as ic}from"./server-lock-Dc1sKhMm.mjs";import{t as ac}from"./libesm-DzwC_yFw.mjs";import{t as oc}from"./yazl-DZr4PyKA.mjs";import{n as sc,t as cc}from"./build-CJW5ggp6.mjs";import{t as lc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as uc,c as dc,d 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,r as xc,s as Sc,t as Cc,u as wc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Tc,B as Ec,C as Dc,D as Oc,E as kc,F as Ac,H as jc,I as Mc,L as Nc,M as Pc,N as Fc,O as Ic,P as Lc,S as Rc,T as zc,V as Bc,_ as Vc,a as Hc,b as Uc,c as Wc,d as Gc,f as Kc,g as qc,h as Jc,i as Yc,j as Xc,k as Zc,l as Qc,m as $c,n as el,o as tl,p as nl,r as rl,s as il,t as al,u as ol,v as sl,w as cl,x as ll,y as ul,z as dl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as fl,c as pl,d as ml,i as hl,l as gl,n as _l,o as vl,r as yl,s as bl,t as xl,u as Sl}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Cl,r as wl,t as Tl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as El}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Dl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Ol,t as kl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Al,t as jl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Ml,r as Nl,t as Pl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Fl,t as Il}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Ll}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Rl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as zl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Bl}from"node:module";import{execFile as Vl,execFileSync as Hl,spawn as Ul,spawnSync as Wl}from"node:child_process";import*as Gl from"node:path";import{basename as Kl,delimiter as ql,dirname as L,extname as Jl,isAbsolute as Yl,join as R,normalize as Xl,posix as Zl,relative as z,resolve as B,sep as Ql,win32 as Qee}from"node:path";import{URLSearchParams as $ee,fileURLToPath as $l,pathToFileURL as ete}from"node:url";import*as eu from"node:fs";import{appendFileSync as tte,chmodSync as tu,closeSync as nu,constants as nte,createReadStream as ru,createWriteStream as iu,existsSync as V,lstatSync as au,mkdirSync as ou,mkdtempSync as su,openSync as cu,readFile as rte,readFileSync as H,readSync as ite,readdirSync as lu,readlinkSync as uu,realpathSync as U,renameSync as du,rmSync as fu,rmdirSync as pu,statSync as mu,unlinkSync as hu,writeFileSync as gu,writeSync as ate}from"node:fs";import{arch as _u,availableParallelism as ote,homedir as vu,hostname as yu,platform as bu,tmpdir as xu}from"node:os";import{access as Su,chmod as ste,constants as Cu,lstat as wu,readFile as Tu,readdir as Eu,realpath as Du,stat as Ou,writeFile as cte}from"node:fs/promises";import{Readable as ku,Transform as lte,Writable as ute}from"node:stream";import Au,{createHash as ju,randomUUID as Mu,webcrypto as Nu}from"node:crypto";import dte from"crypto";import{Readable as Pu}from"stream";import{Worker as fte}from"node:worker_threads";import{monitorEventLoopDelay as pte,performance as Fu}from"node:perf_hooks";import{createInterface as mte}from"node:readline";import{pipeline as Iu}from"node:stream/promises";import{setImmediate as hte,setTimeout as Lu}from"node:timers/promises";import{promisify as Ru}from"node:util";import{request as gte}from"node:http";import{Http2ServerRequest as zu,constants as _te}from"node:http2";import{lookup as vte}from"node:dns/promises";import{request as yte}from"node:https";import{createBrotliDecompress as Bu,createGunzip as Vu,createInflate as Hu}from"node:zlib";import{Http2ServerRequest as Uu,constants as Wu}from"http2";import{AsyncLocalStorage as Gu}from"node:async_hooks";import{lookup as Ku}from"node:dns";import qu from"node:tls";function Ju(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Yu(n)}function Yu(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 Xu=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=H(R(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Yl(t)?t:B(this.gitDir,t))}catch(e){if(!rd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(R(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return rd(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]}:od(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=H(R(t.path,`config`),`utf-8`)}catch(e){return rd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=ed(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!id(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=B(t.path,e),r=z(t.path,n);if(r.startsWith(`..`)||Yl(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=ad(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!rd(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(R(t.path,`packed-refs`),`utf-8`)}catch(e){return rd(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 od(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Zu(e){return $u(B(e),``)}function Qu(e){let t=B(e),n=B(vu());if(t===n)return{kind:`absent`};let r=$u(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=L(i);if(e===i||e===n)return{kind:`absent`};let r=$u(e,z(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function $u(e,t){let n=R(e,`.git`),r;try{r=mu(n)}catch(e){return rd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Xu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=H(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=Yl(o)?o:B(e,o);try{if(!mu(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 Xu(`linked`,e,t,n,s)}}function ed(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=td(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=nd(i[1]);if(a.length>0)return a}return null}function td(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function nd(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function rd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function id(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function ad(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?id(t[1])?{kind:`symbolic`,target:t[1]}:null:od(e)?{kind:`oid`,oid:e}:null}function od(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function sd(e){return`git-author-${_t(e.trim().toLowerCase())}`}const cd=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ld(e){let t=Qu(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 ud(e){let t=ld(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function dd(e){let t=ld(e);switch(t.kind){case`directory`:return B(t.path,fd(t.projectSubPath));case`linked`:if(!V(t.path))throw new hd(t.gitPath,t.path);return B(t.path,fd(t.projectSubPath));case`malformed-pointer`:throw new hd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new gd(t.gitPath,{cause:t.cause});case`absent`:return B(e,`.git/ok`)}}function fd(e){return e===``?`ok`:`ok-${pd(e)}`}function pd(e){let t=e.split(Ql).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=md(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function md(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var hd=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}},gd=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 _d(e){let t;try{t=dd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return V(B(t,`HEAD`))?t:null}function vd(e){return`refs/wip/${e}/`}function yd(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 E,Z as D,_ as ne,_t as O,at as k,b as re,bt as A,ct as ie,d as ae,dt as j,et as oe,f as se,ft as ce,g as le,gt as ue,ht as de,i as fe,it as M,jt as pe,kt as me,l as he,lt as ge,mt as N,n as _e,nt as ve,ot as ye,pt as P,q as be,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 Ae}from"./sleep-ChnoPlNg.mjs";import{$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,Cs as nt,Ct as rt,D as it,Da as at,Di as ot,Dn as st,Do as ct,Dr as lt,Dt as ut,E as dt,Ea as ft,Ei as pt,En as mt,Er as ht,Es as gt,Et as _t,F as vt,Fi as yt,Fn as bt,Fo as xt,Fr as eee,Ft as St,G as Ct,Ga as wt,Gi as Tt,Gn as Et,Gr as tee,Gt as Dt,H as Ot,Ha as kt,Hi as At,Hn as nee,Hr as jt,Ht as Mt,I as Nt,Ia as Pt,Ii as Ft,In as It,Io as Lt,Ir as Rt,It as zt,J as Bt,Ja as Vt,Ji as ree,Jn as iee,Jo as Ht,Jr as Ut,Jt as Wt,K as Gt,Ka as Kt,Ki as qt,Kn as Jt,Ko as Yt,Kr as aee,Kt as Xt,L as Zt,La as Qt,Li as oee,Ln as see,Lr as cee,M as $t,Ma as en,Mi as tn,Mn as nn,Mo as rn,Mr as an,Mt as on,N as sn,Na as cn,Ni as ln,Nn as un,No as dn,Nr as fn,Nt as pn,O as mn,Oa as hn,Oi as gn,On as _n,Oo as vn,Or as lee,Ot as yn,P as bn,Pa as xn,Pi as uee,Pn as Sn,Po as Cn,Pr as wn,Pt as Tn,Qa as En,Qi as Dn,Qn as On,Qo as kn,Qr as An,Qt as jn,R as Mn,Ra as Nn,Ri as Pn,Rn as Fn,Ro as In,Rr as Ln,S as Rn,Sa as zn,Si as Bn,Sn as Vn,So as Hn,Sr as Un,Ss as Wn,St as Gn,T as dee,Ta as Kn,Ti as qn,Tn as fee,To as Jn,Tr as Yn,Ts as Xn,Tt as Zn,U as Qn,Ua as $n,Ui as pee,Un as mee,Uo as er,Ur as hee,Ut as tr,V as nr,Va as gee,Vi as _ee,Vn as rr,Vo as ir,Vr as ar,Vt as or,W as sr,Wa as cr,Wi as lr,Wn as ur,Wo as dr,Wr as fr,Wt as pr,Xa as mr,Xi as hr,Xn as gr,Xo as _r,Xr as vr,Xt as yr,Y as br,Ya as xr,Yi as Sr,Yn as Cr,Yo as wr,Yr as Tr,Yt as Er,Z as Dr,Za as Or,Zi as kr,Zn as Ar,Zo as jr,Zr as Mr,Zt as Nr,_ as Pr,_a as Fr,_i as Ir,_n as Lr,_o as Rr,_r as zr,_s as Br,_t as Vr,a as Hr,aa as Ur,ai as Wr,an as Gr,ao as Kr,ar as qr,as as Jr,at as Yr,b as Xr,ba as vee,bi as Zr,bn as yee,bo as Qr,br as bee,bs as xee,bt as $r,c as ei,ca as ti,ci as ni,cn as See,co as ri,cr as Cee,cs as ii,ct as ai,d as oi,da as si,di as ci,dn as wee,do as li,dr as Tee,ds as ui,dt as di,ea as fi,ei as pi,en as mi,eo as hi,er as gi,es as _i,et as vi,f as yi,fa as bi,fi as xi,fn as Si,fo as Ci,fr as wi,fs as Ti,ft as Ei,g as Di,ga as Oi,gi as ki,gn as Ai,gr as ji,gs as Mi,gt as Ni,h as Pi,ha as Fi,hi as Ii,hn as Li,hr as Ri,hs as zi,ht as Bi,i as Vi,ia as Hi,ii as Ui,in as Wi,io as Gi,ir as Ki,is as qi,it as Ji,j as Yi,ja as Xi,ji as Zi,jn as Qi,jr as $i,jt as ea,k as ta,ka as na,ki as ra,kn as ia,ko as aa,kr as oa,ks as sa,kt as ca,l as la,la as ua,li as da,ln as fa,lr as pa,ls as ma,lt as ha,ma as ga,mi as _a,mn as va,mo as ya,mr as ba,ms as xa,mt as Sa,n as Ca,na as wa,ni as Eee,nn as Ta,no as Dee,nr as Ea,nt as Da,o as Oa,oa as ka,oi as Oee,on as kee,oo as Aee,or as jee,os as Aa,ot as ja,p as Ma,pa as Mee,pi as Nee,pn as Pee,pr as Fee,ps as Iee,pt as Na,q as Pa,qa as Lee,qi as Ree,qn as zee,qo as Fa,qr as Bee,qt as Ia,r as La,ra as Ra,ri as Vee,rn as Hee,ro as Uee,rr as za,rs as Ba,rt as Va,s as Ha,sa as Ua,si as Wee,sn as Gee,so as Wa,sr as Kee,ss as Ga,st as Ka,t as qa,ta as Ja,ti as qee,tn as Jee,to as Yee,tr as Xee,ts as Ya,tt as Xa,u as Za,ua as Qa,ui as $a,un as eo,uo as to,ur as no,us as ro,ut as io,v as ao,va as oo,vi as so,vn as co,vo as lo,vr as uo,vs as fo,vt as po,w as mo,wa as ho,wi as go,wn as _o,wr as vo,ws as yo,wt as bo,x as xo,xa as So,xi as Co,xn as wo,xr as To,xs as Eo,xt as Do,y as Oo,ya as ko,yi as Ao,yn as jo,yo as Mo,yr as No,ys as Po,yt as Fo,za as Io,zi as Lo,zn as Ro,zo,zr as Bo,zt as Vo}from"./src-Xqdqp-3u.mjs";import{c as Ho,i as Uo,l as Wo,n as Go,s as Ko}from"./esm-DxvI2ZVA.mjs";import{n as qo,t as Jo}from"./md-manager-DMhQWacM.mjs";import{A as Yo,C as Xo,D as Zo,E as Qo,F as $o,N as es,O as ts,S as ns,T as rs,_ as is,a as as,b as os,c as ss,d as cs,f as ls,g as us,h as ds,i as fs,j as ps,k as ms,l as hs,m as gs,n as _s,o as vs,p as ys,r as bs,s as xs,t as Ss,u as Cs,v as ws,w as Ts,x as Es,y as Ds}from"./fs-traced-g8Nfed1O.mjs";import{D as Os,E as ks,S as As,T as js,a as Ms,b as Ns,l as Ps,p as Fs,r as I,s as Is,x as Ls,y as Rs}from"./logger-BZPV1wv8.mjs";import{a as zs,i as Bs,o as Vs,r as Hs,s as Us,t as Ws}from"./git-handle-Pv8SU_Wy.mjs";import{S as Gs,a as Ks,b as Zee,c as qs,d as Js,f as Ys,g as Xs,h as Zs,i as Qs,l as $s,m as ec,n as tc,r as nc,x as rc,y as ic}from"./server-lock-CAxliK3N.mjs";import{t as ac}from"./libesm-DzwC_yFw.mjs";import{t as oc}from"./yazl-DZr4PyKA.mjs";import{n as sc,t as cc}from"./build-CJW5ggp6.mjs";import{t as lc}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as uc,c as dc,d 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,r as xc,s as Sc,t as Cc,u as wc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Tc,B as Ec,C as Dc,D as Oc,E as kc,F as Ac,H as jc,I as Mc,L as Nc,M as Pc,N as Fc,O as Ic,P as Lc,S as Rc,T as zc,V as Bc,_ as Vc,a as Hc,b as Uc,c as Wc,d as Gc,f as Kc,g as qc,h as Jc,i as Yc,j as Xc,k as Zc,l as Qc,m as $c,n as el,o as tl,p as nl,r as rl,s as il,t as al,u as ol,v as sl,w as cl,x as ll,y as ul,z as dl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as fl,c as pl,d as ml,i as hl,l as gl,n as _l,o as vl,r as yl,s as bl,t as xl,u as Sl}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Cl,r as wl,t as Tl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as El}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Dl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Ol,t as kl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Al,t as jl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Ml,r as Nl,t as Pl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Fl,t as Il}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Ll}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Rl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as zl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Bl}from"node:module";import{execFile as Vl,execFileSync as Hl,spawn as Ul,spawnSync as Wl}from"node:child_process";import*as Gl from"node:path";import{basename as Kl,delimiter as ql,dirname as L,extname as Jl,isAbsolute as Yl,join as R,normalize as Xl,posix as Zl,relative as z,resolve as B,sep as Ql,win32 as Qee}from"node:path";import{URLSearchParams as $ee,fileURLToPath as $l,pathToFileURL as ete}from"node:url";import*as eu from"node:fs";import{appendFileSync as tte,chmodSync as tu,closeSync as nu,constants as nte,createReadStream as ru,createWriteStream as iu,existsSync as V,lstatSync as au,mkdirSync as ou,mkdtempSync as su,openSync as cu,readFile as rte,readFileSync as H,readSync as ite,readdirSync as lu,readlinkSync as uu,realpathSync as U,renameSync as du,rmSync as fu,rmdirSync as pu,statSync as mu,unlinkSync as hu,writeFileSync as gu,writeSync as ate}from"node:fs";import{arch as _u,availableParallelism as ote,homedir as vu,hostname as yu,platform as bu,tmpdir as xu}from"node:os";import{access as Su,chmod as ste,constants as Cu,lstat as wu,readFile as Tu,readdir as Eu,realpath as Du,stat as Ou,writeFile as cte}from"node:fs/promises";import{Readable as ku,Transform as lte,Writable as ute}from"node:stream";import Au,{createHash as ju,randomUUID as Mu,webcrypto as Nu}from"node:crypto";import dte from"crypto";import{Readable as Pu}from"stream";import{Worker as fte}from"node:worker_threads";import{monitorEventLoopDelay as pte,performance as Fu}from"node:perf_hooks";import{createInterface as mte}from"node:readline";import{pipeline as Iu}from"node:stream/promises";import{setImmediate as hte,setTimeout as Lu}from"node:timers/promises";import{promisify as Ru}from"node:util";import{request as gte}from"node:http";import{Http2ServerRequest as zu,constants as _te}from"node:http2";import{lookup as vte}from"node:dns/promises";import{request as yte}from"node:https";import{createBrotliDecompress as Bu,createGunzip as Vu,createInflate as Hu}from"node:zlib";import{Http2ServerRequest as Uu,constants as Wu}from"http2";import{AsyncLocalStorage as Gu}from"node:async_hooks";import{lookup as Ku}from"node:dns";import qu from"node:tls";function Ju(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Yu(n)}function Yu(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 Xu=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=H(R(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Yl(t)?t:B(this.gitDir,t))}catch(e){if(!rd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(R(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return rd(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]}:od(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=H(R(t.path,`config`),`utf-8`)}catch(e){return rd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=ed(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!id(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=B(t.path,e),r=z(t.path,n);if(r.startsWith(`..`)||Yl(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=ad(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!rd(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(R(t.path,`packed-refs`),`utf-8`)}catch(e){return rd(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 od(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Zu(e){return $u(B(e),``)}function Qu(e){let t=B(e),n=B(vu());if(t===n)return{kind:`absent`};let r=$u(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=L(i);if(e===i||e===n)return{kind:`absent`};let r=$u(e,z(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function $u(e,t){let n=R(e,`.git`),r;try{r=mu(n)}catch(e){return rd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Xu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=H(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=Yl(o)?o:B(e,o);try{if(!mu(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 Xu(`linked`,e,t,n,s)}}function ed(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=td(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=nd(i[1]);if(a.length>0)return a}return null}function td(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function nd(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function rd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function id(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function ad(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?id(t[1])?{kind:`symbolic`,target:t[1]}:null:od(e)?{kind:`oid`,oid:e}:null}function od(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function sd(e){return`git-author-${_t(e.trim().toLowerCase())}`}const cd=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ld(e){let t=Qu(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 ud(e){let t=ld(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function dd(e){let t=ld(e);switch(t.kind){case`directory`:return B(t.path,fd(t.projectSubPath));case`linked`:if(!V(t.path))throw new hd(t.gitPath,t.path);return B(t.path,fd(t.projectSubPath));case`malformed-pointer`:throw new hd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new gd(t.gitPath,{cause:t.cause});case`absent`:return B(e,`.git/ok`)}}function fd(e){return e===``?`ok`:`ok-${pd(e)}`}function pd(e){let t=e.split(Ql).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=md(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function md(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var hd=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}},gd=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 _d(e){let t;try{t=dd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return V(B(t,`HEAD`))?t:null}function vd(e){return`refs/wip/${e}/`}function yd(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 bd=`ok-actor: `;function xd(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),`${bd}${JSON.stringify(i)}`}function Sd(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=Cd(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 Cd(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 wd(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(bd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:Sd(n)}return null}function Td(e){if(!e)return[];let t=[];for(let n of e.split(`
4
- `)){let e=n.trim();if(!e.startsWith(bd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Sd(r);i&&t.push(i)}return t}function Ed(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 Dd(e){let t=Td(e);return t.length>0?t.map(Ed):yd(e)}function Od(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function kd(e){return`reconcile: ${e}`}function Ad(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function jd(e,t){return`park: ${e} -> ${t}`}function Md(e,t){return`rename: ${e} -> ${t}`}function Nd(e){return`checkpoint: ${e}`}function Pd(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Fd=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Id(e){return e.replace(Fd,` `)}function Ld(e,t){let n=Id(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=Id(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 Rd(e){return cd.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 zd(e){let t=ld(e);if(t.kind!==`linked`)return B(e);try{let n=H(R(t.path,`commondir`),`utf-8`).trim();return n===``?B(e):B(L(B(t.path,n)),t.projectSubPath)}catch{return B(e)}}function Bd(e){return e.kind??`other`}function Vd(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Hd=class{filePath;log;grants=null;constructor(e,t){this.filePath=R(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Bd(t),i=Vd(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=Bd(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(R(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(H(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 Ud=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Wd={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Gd=`acp-agents.json`,Kd=`acp-registry-cache.json`;function qd(){let e=bu(),t=_u(),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 Jd(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 Yd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Jd):null}var Xd=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=Yd(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(R(this.localDir,Kd),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=Yd(await Tu(R(this.localDir,Kd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Zd(e,t){let n;try{n=await Tu(R(e,Gd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Gd} 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 ${Gd} entry`)}return i}const Qd={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`},$d={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`},ef={cancel_request:`$/cancel_request`},tf=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function nf(e,t){let n=e.catch(t);return A().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function rf(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function af(e,t,n){return e.superRefine((e,r)=>{let i=rf(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 of(e,t,n){return A().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=rf(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 sf(e){return M(e.catch(tf)).transform(e=>e.filter(e=>e!==tf))}const cf=Ae([P(),F()]).nullable(),lf=F(),uf=N({sessionId:lf,path:F(),content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),df=N({sessionId:lf,path:F(),line:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ff=F(),pf=Ae([j(`read`),j(`edit`),j(`delete`),j(`move`),j(`search`),j(`execute`),j(`think`),j(`fetch`),j(`switch_mode`),j(`other`)]),mf=Ae([j(`pending`),j(`in_progress`),j(`completed`),j(`failed`)]),hf=N({audience:W(sf(Ae([j(`assistant`),j(`user`)])).nullish(),()=>void 0),lastModified:W(F().nullish(),()=>void 0),priority:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),gf=N({annotations:W(hf.nullish(),()=>void 0),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_f=N({annotations:W(hf.nullish(),()=>void 0),data:F(),mimeType:F(),uri:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vf=N({annotations:W(hf.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),yf=N({annotations:W(hf.nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),mimeType:W(F().nullish(),()=>void 0),name:F(),size:W(P().nullish(),()=>void 0),title:W(F().nullish(),()=>void 0),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),bf=Ae([N({mimeType:W(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),N({blob:F(),mimeType:W(F().nullish(),()=>void 0),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)})]),xf=N({annotations:W(hf.nullish(),()=>void 0),resource:bf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sf=Ae([gf.and(N({type:j(`text`)})),_f.and(N({type:j(`image`)})),vf.and(N({type:j(`audio`)})),yf.and(N({type:j(`resource_link`)})),xf.and(N({type:j(`resource`)}))]),Cf=N({content:Sf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),wf=N({path:F(),oldText:W(F().nullish(),()=>void 0),newText:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tf=F(),Ef=N({terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Df=Ae([Cf.and(N({type:j(`content`)})),wf.and(N({type:j(`diff`)})),Ef.and(N({type:j(`terminal`)}))]),Of=N({path:F(),line:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),kf=N({toolCallId:ff,kind:W(pf.nullish(),()=>void 0),status:W(mf.nullish(),()=>void 0),title:W(F().nullish(),()=>void 0),content:W(sf(Df).nullish(),()=>void 0),locations:W(sf(Of).nullish(),()=>void 0),rawInput:W(A().optional(),()=>void 0),rawOutput:W(A().optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Af=F(),jf=Ae([j(`allow_once`),j(`allow_always`),j(`reject_once`),j(`reject_always`)]),Mf=N({sessionId:lf,toolCall:kf,options:M(N({optionId:Af,name:F(),kind:jf,_meta:W(O(F(),A()).nullish(),()=>void 0)})),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nf=N({name:F(),value:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pf=N({sessionId:lf,command:F(),args:W(sf(F()).optional(),()=>[]),env:W(sf(Nf).optional(),()=>[]),cwd:W(F().nullish(),()=>void 0),outputByteLimit:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ff=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),If=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lf=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rf=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),zf=N({sessionId:lf,toolCallId:W(ff.nullish(),()=>void 0)}),Bf=N({requestId:cf}),Vf=j(`object`),Hf=Ae([j(`email`),j(`uri`),j(`date`),j(`date-time`)]),Uf=N({const:F(),title:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minLength:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:Hf.nullish(),default:W(F().nullish(),()=>void 0),enum:M(F()).nullish(),oneOf:M(Uf).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),qf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),default:W(k().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jf=N({enum:M(F()),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yf=N({anyOf:M(Uf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xf=of(Ae([Jf.and(N({type:j(`string`)})),af(N({type:F()}),`type`,[`string`]),Yf]),`type`,[`string`]),Zf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minItems:P().nullish(),maxItems:P().nullish(),items:Xf,default:W(sf(F()).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qf=of(Ae([Wf.and(N({type:j(`string`)})),Gf.and(N({type:j(`number`)})),Kf.and(N({type:j(`integer`)})),qf.and(N({type:j(`boolean`)})),Zf.and(N({type:j(`array`)})),af(N({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),$f=N({type:W(Vf.optional().default(`object`),()=>`object`),title:W(F().nullish(),()=>void 0),properties:O(F(),Qf).optional().default({}),required:M(F()).nullish(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ep=ge(Ae([zf,Bf]),N({requestedSchema:$f})),tp=F(),np=ge(Ae([zf,Bf]),N({elicitationId:tp,url:Oe()})),rp=of(ge(Ae([ep.and(N({mode:j(`form`)})),np.and(N({mode:j(`url`)})),af(ge(Ae([zf,Bf]),N({mode:F()})),`mode`,[`form`,`url`])]),N({message:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),ip=F(),ap=N({serverId:ip,_meta:W(O(F(),A()).nullish(),()=>void 0)}),op=F(),sp=N({connectionId:op,method:F(),params:O(F(),A()).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cp=N({connectionId:op,_meta:W(O(F(),A()).nullish(),()=>void 0)}),lp=A();N({id:cf,method:F(),params:Ae([uf,df,Mf,Pf,Ff,If,Lf,Rf,rp,ap,sp,cp,lp]).nullish()});const up=ie().gte(0).lte(65535),bte=N({image:W(k().optional().default(!1),()=>!1),audio:W(k().optional().default(!1),()=>!1),embeddedContext:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xte=N({http:W(k().optional().default(!1),()=>!1),sse:W(k().optional().default(!1),()=>!1),acp:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ste=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),wte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ete=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Dte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ote=N({list:W(Ste.nullish(),()=>void 0),delete:W(Cte.nullish(),()=>void 0),additionalDirectories:W(wte.nullish(),()=>void 0),fork:W(Tte.nullish(),()=>void 0),resume:W(Ete.nullish(),()=>void 0),close:W(Dte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),kte=N({logout:W(N({_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ate=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),jte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mte=N({syncKind:Ae([j(`full`),j(`incremental`)]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ite=N({document:W(N({didOpen:W(jte.nullish(),()=>void 0),didChange:W(Mte.nullish(),()=>void 0),didClose:W(Nte.nullish(),()=>void 0),didSave:W(Pte.nullish(),()=>void 0),didFocus:W(Fte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),zte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Hte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ute=N({recentFiles:W(Lte.nullish(),()=>void 0),relatedSnippets:W(Rte.nullish(),()=>void 0),editHistory:W(zte.nullish(),()=>void 0),userActions:W(Bte.nullish(),()=>void 0),openFiles:W(Vte.nullish(),()=>void 0),diagnostics:W(Hte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wte=N({events:W(Ite.nullish(),()=>void 0),context:W(Ute.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dp=Ae([j(`utf-16`),j(`utf-32`),j(`utf-8`)]),Gte=N({loadSession:W(k().optional().default(!1),()=>!1),promptCapabilities:W(bte.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(xte.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(Ote.optional().default({}),()=>({})),auth:W(kte.optional().default({}),()=>({})),providers:W(Ate.nullish(),()=>void 0),nes:W(Wte.nullish(),()=>void 0),positionEncoding:W(dp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),fp=F(),Kte=N({name:F(),label:W(F().nullish(),()=>void 0),secret:W(k().optional().default(!0),()=>!0),optional:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),qte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),vars:nf(sf(Kte),()=>[]),link:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),args:W(sf(F()).optional(),()=>[]),env:W(O(F(),F()).optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xte=Ae([qte.and(N({type:j(`env_var`)})),Jte.and(N({type:j(`terminal`)})),Yte]),pp=N({name:F(),title:W(F().nullish(),()=>void 0),version:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zte=N({protocolVersion:up,agentCapabilities:W(Gte.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:W(sf(Xte).optional().default([]),()=>[]),agentInfo:W(pp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),mp=F(),hp=Ae([j(`anthropic`),j(`openai`),j(`azure`),j(`vertex`),j(`bedrock`),F()]),$te=N({apiType:hp,baseUrl:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ene=N({providers:M(N({providerId:mp,supported:nf(sf(hp),()=>[]),required:k(),current:$te.nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)})),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),nne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),rne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gp=F(),_p=N({currentModeId:gp,availableModes:nf(sf(N({id:gp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vp=F(),ine=Ae([j(`mode`),j(`model`),j(`model_config`),j(`thought_level`),F()]),yp=F(),bp=N({value:yp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ane=N({group:F(),name:F(),options:nf(sf(bp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),one=N({currentValue:yp,options:Ae([M(bp),M(ane)])}),sne=N({currentValue:k()}),xp=ge(Ae([one.and(N({type:j(`select`)})),sne.and(N({type:j(`boolean`)}))]),N({id:vp,name:F(),description:W(F().nullish(),()=>void 0),category:W(ine.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),cne=N({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),lne=N({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),une=N({sessions:nf(sf(N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),title:W(F().nullish(),()=>void 0),updatedAt:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),fne=N({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),pne=N({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),mne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),hne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gne=N({configOptions:nf(sf(xp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_ne=N({stopReason:Ae([j(`end_turn`),j(`max_tokens`),j(`max_turn_requests`),j(`refusal`),j(`cancelled`)]),usage:W(N({totalTokens:P(),inputTokens:P(),outputTokens:P(),thoughtTokens:W(P().nullish(),()=>void 0),cachedReadTokens:W(P().nullish(),()=>void 0),cachedWriteTokens:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vne=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sp=F(),Cp=N({line:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wp=N({start:Cp,end:Cp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),yne=N({range:wp,newText:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),bne=N({id:Sp,uri:F(),edits:M(yne),cursorPosition:W(Cp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xne=N({id:Sp,uri:F(),position:Cp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sne=N({id:Sp,uri:F(),position:Cp,newName:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cne=N({id:Sp,uri:F(),search:F(),replace:F(),isRegex:k().nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wne=N({suggestions:M(Ae([bne.and(N({kind:j(`edit`)})),xne.and(N({kind:j(`jump`)})),Sne.and(N({kind:j(`rename`)})),Cne.and(N({kind:j(`searchAndReplace`)}))])),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tp=A(),Ep=A(),Dp=N({code:Ae([j(-32700),j(-32600),j(-32601),j(-32602),j(-32603),j(-32800),j(-32e3),j(-32002),ie().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:W(A().optional(),()=>void 0)});Ae([N({id:cf,result:Ae([Zte,Qte,ene,tne,nne,rne,cne,lne,une,dne,fne,pne,mne,hne,gne,_ne,vne,wne,Tne,Tp,Ep])}),N({id:cf,error:Dp})]);const Op=N({content:Sf,messageId:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ene=N({toolCallId:ff,title:F(),kind:W(pf.optional(),()=>void 0),status:W(mf.optional(),()=>void 0),content:W(sf(Df).optional(),()=>[]),locations:W(sf(Of).optional(),()=>[]),rawInput:W(A().optional(),()=>void 0),rawOutput:W(A().optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Dne=Ae([j(`high`),j(`medium`),j(`low`)]),One=Ae([j(`pending`),j(`in_progress`),j(`completed`)]),kp=N({content:F(),priority:Dne,status:One,_meta:W(O(F(),A()).nullish(),()=>void 0)}),kne=N({entries:nf(sf(kp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ap=F(),Ane=N({planId:Ap,entries:nf(sf(kp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),jne=N({planId:Ap,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mne=N({planId:Ap,content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nne=N({plan:Ae([Ane.and(N({type:j(`items`)})),jne.and(N({type:j(`file`)})),Mne.and(N({type:j(`markdown`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pne=N({planId:Ap,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fne=N({hint:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ine=N({availableCommands:nf(sf(N({name:F(),description:F(),input:W(Fne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lne=N({currentModeId:gp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rne=N({configOptions:nf(sf(xp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),zne=N({title:W(F().nullish(),()=>void 0),updatedAt:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bne=N({amount:P(),currency:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vne=N({used:P(),size:P(),cost:W(Bne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),jp=N({sessionId:lf,update:Ae([Op.and(N({sessionUpdate:j(`user_message_chunk`)})),Op.and(N({sessionUpdate:j(`agent_message_chunk`)})),Op.and(N({sessionUpdate:j(`agent_thought_chunk`)})),Ene.and(N({sessionUpdate:j(`tool_call`)})),kf.and(N({sessionUpdate:j(`tool_call_update`)})),kne.and(N({sessionUpdate:j(`plan`)})),Nne.and(N({sessionUpdate:j(`plan_update`)})),Pne.and(N({sessionUpdate:j(`plan_removed`)})),Ine.and(N({sessionUpdate:j(`available_commands_update`)})),Lne.and(N({sessionUpdate:j(`current_mode_update`)})),Rne.and(N({sessionUpdate:j(`config_option_update`)})),zne.and(N({sessionUpdate:j(`session_info_update`)})),Vne.and(N({sessionUpdate:j(`usage_update`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mp=N({elicitationId:tp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Np=N({connectionId:op,method:F(),params:W(O(F(),A()).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pp=A();N({method:F(),params:Ae([jp,Mp,Np,Pp]).nullish()});const Hne=N({readTextFile:W(k().optional().default(!1),()=>!1),writeTextFile:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Une=N({configOptions:W(N({boolean:W(N({_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gne=N({terminal:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),qne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jne=N({form:W(Kne.nullish(),()=>void 0),url:W(qne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qne=N({jump:W(Yne.nullish(),()=>void 0),rename:W(Xne.nullish(),()=>void 0),searchAndReplace:W(Zne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fp=N({protocolVersion:up,clientCapabilities:W(N({fs:W(Hne.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(k().optional().default(!1),()=>!1),session:W(Une.nullish(),()=>void 0),plan:W(Wne.nullish(),()=>void 0),auth:W(Gne.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(Jne.nullish(),()=>void 0),nes:W(Qne.nullish(),()=>void 0),positionEncodings:W(sf(dp).optional(),()=>[]),_meta:W(O(F(),A()).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:W(pp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ip=N({methodId:fp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lp=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rp=N({providerId:mp,apiType:hp,baseUrl:F(),headers:O(F(),F()).optional(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),zp=N({providerId:mp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bp=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vp=N({name:F(),value:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),$ne=N({name:F(),url:F(),headers:M(Vp),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ere=N({name:F(),url:F(),headers:M(Vp),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tre=N({name:F(),serverId:ip,_meta:W(O(F(),A()).nullish(),()=>void 0)}),nre=N({name:F(),command:F(),args:M(F()),env:M(Nf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Hp=Ae([$ne.and(N({type:j(`http`)})),ere.and(N({type:j(`sse`)})),tre.and(N({type:j(`acp`)})),nre]),Up=N({cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:nf(sf(Hp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wp=N({mcpServers:nf(sf(Hp),()=>[]),cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gp=N({cwd:F().nullish(),cursor:F().nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kp=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),qp=N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:W(sf(Hp).optional(),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jp=N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:W(sf(Hp).optional(),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yp=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xp=N({sessionId:lf,modeId:gp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zp=ge(Ae([N({value:k(),type:j(`boolean`)}),N({value:yp})]),N({sessionId:lf,configId:vp,_meta:W(O(F(),A()).nullish(),()=>void 0)})),Qp=N({sessionId:lf,prompt:M(Sf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),rre=N({uri:F(),name:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ire=N({name:F(),owner:F(),remoteUrl:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),$p=N({workspaceUri:W(F().nullish(),()=>void 0),workspaceFolders:M(rre).nullish(),repository:W(ire.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),are=Ae([j(`automatic`),j(`diagnostic`),j(`manual`)]),ore=N({uri:F(),languageId:F(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),sre=N({startLine:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cre=N({uri:F(),excerpts:M(sre),_meta:W(O(F(),A()).nullish(),()=>void 0)}),lre=N({uri:F(),diff:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ure=N({action:F(),uri:F(),position:Cp,timestampMs:P(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dre=N({uri:F(),languageId:F(),visibleRange:W(wp.nullish(),()=>void 0),lastFocusedMs:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),fre=Ae([j(`error`),j(`warning`),j(`information`),j(`hint`)]),pre=N({uri:F(),range:wp,severity:fre,message:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),mre=N({recentFiles:M(ore).nullish(),relatedSnippets:M(cre).nullish(),editHistory:M(lre).nullish(),userActions:M(ure).nullish(),openFiles:M(dre).nullish(),diagnostics:M(pre).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),em=N({sessionId:lf,uri:F(),version:P(),position:Cp,selection:wp.nullish(),triggerKind:are,context:mre.nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tm=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)});N({id:cf,method:F(),params:Ae([Fp,Ip,Lp,Rp,zp,Bp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,sp,lp]).nullish()});const hre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gre=N({content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_re=N({optionId:Af,_meta:W(O(F(),A()).nullish(),()=>void 0)}),vre=N({outcome:Ae([N({outcome:j(`cancelled`)}),_re.and(N({outcome:j(`selected`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),yre=N({terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),bre=N({exitCode:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xre=N({output:F(),truncated:k(),exitStatus:W(bre.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cre=N({exitCode:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tre=Ae([F(),P(),P(),k(),M(F())]),nm=N({content:O(F(),Tre).nullish()});Ae([N({id:cf,result:Ae([hre,gre,vre,yre,xre,Sre,Cre,wre,of(ge(Ae([nm.and(N({action:j(`accept`)})),N({action:j(`decline`)}),N({action:j(`cancel`)}),af(N({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),N({_meta:W(O(F(),A()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),N({connectionId:op,_meta:W(O(F(),A()).nullish(),()=>void 0)}),N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ep,Tp])}),N({id:cf,error:Dp})]);const rm=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),im=N({sessionId:lf,uri:F(),languageId:F(),version:P(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ere=N({range:wp.nullish(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),am=N({sessionId:lf,uri:F(),version:P(),contentChanges:nf(sf(Ere),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),om=N({sessionId:lf,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),sm=N({sessionId:lf,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cm=N({sessionId:lf,uri:F(),version:P(),position:Cp,visibleRange:wp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),lm=N({sessionId:lf,id:Sp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),um=N({sessionId:lf,id:Sp,reason:W(Ae([j(`rejected`),j(`ignored`),j(`replaced`),j(`cancelled`)]).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)});N({method:F(),params:Ae([rm,im,am,om,sm,cm,lm,um,Np,Pp]).nullish()}),N({requestId:cf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),ep.and(N({mode:j(`form`)})).and(N({message:F()})),np.and(N({mode:j(`url`)})).and(N({message:F()})),Ae([zf,Bf]).and(N({message:F()})),Wf.and(N({type:j(`string`)})),Gf.and(N({type:j(`number`)})),Kf.and(N({type:j(`integer`)})),qf.and(N({type:j(`boolean`)})),Zf.and(N({type:j(`array`)})),Jf.and(N({type:j(`string`)})),nm.and(N({action:j(`accept`)})),N({action:j(`decline`)}),N({action:j(`cancel`)});const dm=`$/cancel_request`;function fm(e){return typeof e==`object`&&!!e}function Dre(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Ore(e){if(!(!fm(e)||!Dre(e.requestId)))return e.requestId}const pm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function mm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function kre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Are(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 hm(e){if(e instanceof vm)return e.toResult();if(Are(e))return vm.invalidParams(e.format()).toResult();let t=kre(e);try{return vm.internalError(t?JSON.parse(t):{}).toResult()}catch{return vm.internalError({details:t}).toResult()}}function jre(e){return e instanceof vm&&e.code===-32800?e:vm.requestCancelled(e)}function Mre(e,t){let n=Nre(e,t);return n?n.toResult():hm(e)}function Nre(e,t){if(!(!t.aborted||!Pre(e)))return jre(t.reason)}function Pre(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Fre=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 vm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?mm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},gm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Ire=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}},_m=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Ire(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 Lre}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 gm(()=>{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 mm(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(dm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?mm(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 pm.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(!fm(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(vm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Mre(n,t.responder.signal));else{let t=hm(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 Fre(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&&fm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new vm(n,r,i))}else t.reject(vm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==dm)return;let t=Ore(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(vm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?mm(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)}},Lre=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)??pm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?pm.no(r):await n(t(r.params),r.responder,i)??pm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?pm.no(r):await n(t(r.params),i)??pm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new _m(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},vm=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}}},Rre=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 zre(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Rre,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);fm(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(bd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Sd(r);i&&t.push(i)}return t}function Ed(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 Dd(e){let t=Td(e);return t.length>0?t.map(Ed):yd(e)}function Od(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function kd(e){return`reconcile: ${e}`}function Ad(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function jd(e,t){return`park: ${e} -> ${t}`}function Md(e,t){return`rename: ${e} -> ${t}`}function Nd(e){return`checkpoint: ${e}`}function Pd(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Fd=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Id(e){return e.replace(Fd,` `)}function Ld(e,t){let n=Id(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=Id(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 Rd(e){return cd.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 zd(e){let t=ld(e);if(t.kind!==`linked`)return B(e);try{let n=H(R(t.path,`commondir`),`utf-8`).trim();return n===``?B(e):B(L(B(t.path,n)),t.projectSubPath)}catch{return B(e)}}function Bd(e){return e.kind??`other`}function Vd(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Hd=class{filePath;log;grants=null;constructor(e,t){this.filePath=R(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Bd(t),i=Vd(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=Bd(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-BLumSmkJ.mjs`);await e(R(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(H(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 Ud=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Wd={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Gd=`acp-agents.json`,Kd=`acp-registry-cache.json`;function qd(){let e=bu(),t=_u(),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 Jd(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 Yd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Jd):null}var Xd=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=Yd(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-BLumSmkJ.mjs`);await e(this.localDir,{recursive:!0}),await n(R(this.localDir,Kd),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=Yd(await Tu(R(this.localDir,Kd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Zd(e,t){let n;try{n=await Tu(R(e,Gd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Gd} 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 ${Gd} entry`)}return i}const Qd={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`},$d={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`},ef={cancel_request:`$/cancel_request`},tf=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function nf(e,t){let n=e.catch(t);return A().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function rf(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function af(e,t,n){return e.superRefine((e,r)=>{let i=rf(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 of(e,t,n){return A().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=rf(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 sf(e){return M(e.catch(tf)).transform(e=>e.filter(e=>e!==tf))}const cf=Ae([P(),F()]).nullable(),lf=F(),uf=N({sessionId:lf,path:F(),content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),df=N({sessionId:lf,path:F(),line:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ff=F(),pf=Ae([j(`read`),j(`edit`),j(`delete`),j(`move`),j(`search`),j(`execute`),j(`think`),j(`fetch`),j(`switch_mode`),j(`other`)]),mf=Ae([j(`pending`),j(`in_progress`),j(`completed`),j(`failed`)]),hf=N({audience:W(sf(Ae([j(`assistant`),j(`user`)])).nullish(),()=>void 0),lastModified:W(F().nullish(),()=>void 0),priority:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),gf=N({annotations:W(hf.nullish(),()=>void 0),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_f=N({annotations:W(hf.nullish(),()=>void 0),data:F(),mimeType:F(),uri:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vf=N({annotations:W(hf.nullish(),()=>void 0),data:F(),mimeType:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),yf=N({annotations:W(hf.nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),mimeType:W(F().nullish(),()=>void 0),name:F(),size:W(P().nullish(),()=>void 0),title:W(F().nullish(),()=>void 0),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),bf=Ae([N({mimeType:W(F().nullish(),()=>void 0),text:F(),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),N({blob:F(),mimeType:W(F().nullish(),()=>void 0),uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)})]),xf=N({annotations:W(hf.nullish(),()=>void 0),resource:bf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sf=Ae([gf.and(N({type:j(`text`)})),_f.and(N({type:j(`image`)})),vf.and(N({type:j(`audio`)})),yf.and(N({type:j(`resource_link`)})),xf.and(N({type:j(`resource`)}))]),Cf=N({content:Sf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),wf=N({path:F(),oldText:W(F().nullish(),()=>void 0),newText:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tf=F(),Ef=N({terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Df=Ae([Cf.and(N({type:j(`content`)})),wf.and(N({type:j(`diff`)})),Ef.and(N({type:j(`terminal`)}))]),Of=N({path:F(),line:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),kf=N({toolCallId:ff,kind:W(pf.nullish(),()=>void 0),status:W(mf.nullish(),()=>void 0),title:W(F().nullish(),()=>void 0),content:W(sf(Df).nullish(),()=>void 0),locations:W(sf(Of).nullish(),()=>void 0),rawInput:W(A().optional(),()=>void 0),rawOutput:W(A().optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Af=F(),jf=Ae([j(`allow_once`),j(`allow_always`),j(`reject_once`),j(`reject_always`)]),Mf=N({sessionId:lf,toolCall:kf,options:M(N({optionId:Af,name:F(),kind:jf,_meta:W(O(F(),A()).nullish(),()=>void 0)})),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nf=N({name:F(),value:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pf=N({sessionId:lf,command:F(),args:W(sf(F()).optional(),()=>[]),env:W(sf(Nf).optional(),()=>[]),cwd:W(F().nullish(),()=>void 0),outputByteLimit:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ff=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),If=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lf=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rf=N({sessionId:lf,terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),zf=N({sessionId:lf,toolCallId:W(ff.nullish(),()=>void 0)}),Bf=N({requestId:cf}),Vf=j(`object`),Hf=Ae([j(`email`),j(`uri`),j(`date`),j(`date-time`)]),Uf=N({const:F(),title:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minLength:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:F().nullish(),format:Hf.nullish(),default:W(F().nullish(),()=>void 0),enum:M(F()).nullish(),oneOf:M(Uf).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),qf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),default:W(k().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jf=N({enum:M(F()),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yf=N({anyOf:M(Uf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xf=of(Ae([Jf.and(N({type:j(`string`)})),af(N({type:F()}),`type`,[`string`]),Yf]),`type`,[`string`]),Zf=N({title:W(F().nullish(),()=>void 0),description:W(F().nullish(),()=>void 0),minItems:P().nullish(),maxItems:P().nullish(),items:Xf,default:W(sf(F()).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qf=of(Ae([Wf.and(N({type:j(`string`)})),Gf.and(N({type:j(`number`)})),Kf.and(N({type:j(`integer`)})),qf.and(N({type:j(`boolean`)})),Zf.and(N({type:j(`array`)})),af(N({type:F()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),$f=N({type:W(Vf.optional().default(`object`),()=>`object`),title:W(F().nullish(),()=>void 0),properties:O(F(),Qf).optional().default({}),required:M(F()).nullish(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ep=ge(Ae([zf,Bf]),N({requestedSchema:$f})),tp=F(),np=ge(Ae([zf,Bf]),N({elicitationId:tp,url:Oe()})),rp=of(ge(Ae([ep.and(N({mode:j(`form`)})),np.and(N({mode:j(`url`)})),af(ge(Ae([zf,Bf]),N({mode:F()})),`mode`,[`form`,`url`])]),N({message:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),ip=F(),ap=N({serverId:ip,_meta:W(O(F(),A()).nullish(),()=>void 0)}),op=F(),sp=N({connectionId:op,method:F(),params:O(F(),A()).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cp=N({connectionId:op,_meta:W(O(F(),A()).nullish(),()=>void 0)}),lp=A();N({id:cf,method:F(),params:Ae([uf,df,Mf,Pf,Ff,If,Lf,Rf,rp,ap,sp,cp,lp]).nullish()});const up=ie().gte(0).lte(65535),bte=N({image:W(k().optional().default(!1),()=>!1),audio:W(k().optional().default(!1),()=>!1),embeddedContext:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xte=N({http:W(k().optional().default(!1),()=>!1),sse:W(k().optional().default(!1),()=>!1),acp:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ste=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),wte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ete=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Dte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ote=N({list:W(Ste.nullish(),()=>void 0),delete:W(Cte.nullish(),()=>void 0),additionalDirectories:W(wte.nullish(),()=>void 0),fork:W(Tte.nullish(),()=>void 0),resume:W(Ete.nullish(),()=>void 0),close:W(Dte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),kte=N({logout:W(N({_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ate=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),jte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mte=N({syncKind:Ae([j(`full`),j(`incremental`)]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ite=N({document:W(N({didOpen:W(jte.nullish(),()=>void 0),didChange:W(Mte.nullish(),()=>void 0),didClose:W(Nte.nullish(),()=>void 0),didSave:W(Pte.nullish(),()=>void 0),didFocus:W(Fte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),zte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bte=N({maxCount:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Hte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ute=N({recentFiles:W(Lte.nullish(),()=>void 0),relatedSnippets:W(Rte.nullish(),()=>void 0),editHistory:W(zte.nullish(),()=>void 0),userActions:W(Bte.nullish(),()=>void 0),openFiles:W(Vte.nullish(),()=>void 0),diagnostics:W(Hte.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wte=N({events:W(Ite.nullish(),()=>void 0),context:W(Ute.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dp=Ae([j(`utf-16`),j(`utf-32`),j(`utf-8`)]),Gte=N({loadSession:W(k().optional().default(!1),()=>!1),promptCapabilities:W(bte.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(xte.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(Ote.optional().default({}),()=>({})),auth:W(kte.optional().default({}),()=>({})),providers:W(Ate.nullish(),()=>void 0),nes:W(Wte.nullish(),()=>void 0),positionEncoding:W(dp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),fp=F(),Kte=N({name:F(),label:W(F().nullish(),()=>void 0),secret:W(k().optional().default(!0),()=>!0),optional:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),qte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),vars:nf(sf(Kte),()=>[]),link:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),args:W(sf(F()).optional(),()=>[]),env:W(O(F(),F()).optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yte=N({id:fp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xte=Ae([qte.and(N({type:j(`env_var`)})),Jte.and(N({type:j(`terminal`)})),Yte]),pp=N({name:F(),title:W(F().nullish(),()=>void 0),version:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zte=N({protocolVersion:up,agentCapabilities:W(Gte.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:W(sf(Xte).optional().default([]),()=>[]),agentInfo:W(pp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qte=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),mp=F(),hp=Ae([j(`anthropic`),j(`openai`),j(`azure`),j(`vertex`),j(`bedrock`),F()]),$te=N({apiType:hp,baseUrl:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ene=N({providers:M(N({providerId:mp,supported:nf(sf(hp),()=>[]),required:k(),current:$te.nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)})),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),nne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),rne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gp=F(),_p=N({currentModeId:gp,availableModes:nf(sf(N({id:gp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vp=F(),ine=Ae([j(`mode`),j(`model`),j(`model_config`),j(`thought_level`),F()]),yp=F(),bp=N({value:yp,name:F(),description:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ane=N({group:F(),name:F(),options:nf(sf(bp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),one=N({currentValue:yp,options:Ae([M(bp),M(ane)])}),sne=N({currentValue:k()}),xp=ge(Ae([one.and(N({type:j(`select`)})),sne.and(N({type:j(`boolean`)}))]),N({id:vp,name:F(),description:W(F().nullish(),()=>void 0),category:W(ine.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),cne=N({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),lne=N({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),une=N({sessions:nf(sf(N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),title:W(F().nullish(),()=>void 0),updatedAt:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),fne=N({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),pne=N({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(xp).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),mne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),hne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gne=N({configOptions:nf(sf(xp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_ne=N({stopReason:Ae([j(`end_turn`),j(`max_tokens`),j(`max_turn_requests`),j(`refusal`),j(`cancelled`)]),usage:W(N({totalTokens:P(),inputTokens:P(),outputTokens:P(),thoughtTokens:W(P().nullish(),()=>void 0),cachedReadTokens:W(P().nullish(),()=>void 0),cachedWriteTokens:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),vne=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sp=F(),Cp=N({line:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wp=N({start:Cp,end:Cp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),yne=N({range:wp,newText:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),bne=N({id:Sp,uri:F(),edits:M(yne),cursorPosition:W(Cp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xne=N({id:Sp,uri:F(),position:Cp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sne=N({id:Sp,uri:F(),position:Cp,newName:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cne=N({id:Sp,uri:F(),search:F(),replace:F(),isRegex:k().nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wne=N({suggestions:M(Ae([bne.and(N({kind:j(`edit`)})),xne.and(N({kind:j(`jump`)})),Sne.and(N({kind:j(`rename`)})),Cne.and(N({kind:j(`searchAndReplace`)}))])),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tp=A(),Ep=A(),Dp=N({code:Ae([j(-32700),j(-32600),j(-32601),j(-32602),j(-32603),j(-32800),j(-32e3),j(-32002),ie().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:F(),data:W(A().optional(),()=>void 0)});Ae([N({id:cf,result:Ae([Zte,Qte,ene,tne,nne,rne,cne,lne,une,dne,fne,pne,mne,hne,gne,_ne,vne,wne,Tne,Tp,Ep])}),N({id:cf,error:Dp})]);const Op=N({content:Sf,messageId:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ene=N({toolCallId:ff,title:F(),kind:W(pf.optional(),()=>void 0),status:W(mf.optional(),()=>void 0),content:W(sf(Df).optional(),()=>[]),locations:W(sf(Of).optional(),()=>[]),rawInput:W(A().optional(),()=>void 0),rawOutput:W(A().optional(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Dne=Ae([j(`high`),j(`medium`),j(`low`)]),One=Ae([j(`pending`),j(`in_progress`),j(`completed`)]),kp=N({content:F(),priority:Dne,status:One,_meta:W(O(F(),A()).nullish(),()=>void 0)}),kne=N({entries:nf(sf(kp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ap=F(),Ane=N({planId:Ap,entries:nf(sf(kp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),jne=N({planId:Ap,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mne=N({planId:Ap,content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Nne=N({plan:Ae([Ane.and(N({type:j(`items`)})),jne.and(N({type:j(`file`)})),Mne.and(N({type:j(`markdown`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pne=N({planId:Ap,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fne=N({hint:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ine=N({availableCommands:nf(sf(N({name:F(),description:F(),input:W(Fne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)})),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lne=N({currentModeId:gp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rne=N({configOptions:nf(sf(xp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),zne=N({title:W(F().nullish(),()=>void 0),updatedAt:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bne=N({amount:P(),currency:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vne=N({used:P(),size:P(),cost:W(Bne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),jp=N({sessionId:lf,update:Ae([Op.and(N({sessionUpdate:j(`user_message_chunk`)})),Op.and(N({sessionUpdate:j(`agent_message_chunk`)})),Op.and(N({sessionUpdate:j(`agent_thought_chunk`)})),Ene.and(N({sessionUpdate:j(`tool_call`)})),kf.and(N({sessionUpdate:j(`tool_call_update`)})),kne.and(N({sessionUpdate:j(`plan`)})),Nne.and(N({sessionUpdate:j(`plan_update`)})),Pne.and(N({sessionUpdate:j(`plan_removed`)})),Ine.and(N({sessionUpdate:j(`available_commands_update`)})),Lne.and(N({sessionUpdate:j(`current_mode_update`)})),Rne.and(N({sessionUpdate:j(`config_option_update`)})),zne.and(N({sessionUpdate:j(`session_info_update`)})),Vne.and(N({sessionUpdate:j(`usage_update`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Mp=N({elicitationId:tp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Np=N({connectionId:op,method:F(),params:W(O(F(),A()).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Pp=A();N({method:F(),params:Ae([jp,Mp,Np,Pp]).nullish()});const Hne=N({readTextFile:W(k().optional().default(!1),()=>!1),writeTextFile:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Une=N({configOptions:W(N({boolean:W(N({_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gne=N({terminal:W(k().optional().default(!1),()=>!1),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),qne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jne=N({form:W(Kne.nullish(),()=>void 0),url:W(qne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zne=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Qne=N({jump:W(Yne.nullish(),()=>void 0),rename:W(Xne.nullish(),()=>void 0),searchAndReplace:W(Zne.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Fp=N({protocolVersion:up,clientCapabilities:W(N({fs:W(Hne.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(k().optional().default(!1),()=>!1),session:W(Une.nullish(),()=>void 0),plan:W(Wne.nullish(),()=>void 0),auth:W(Gne.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(Jne.nullish(),()=>void 0),nes:W(Qne.nullish(),()=>void 0),positionEncodings:W(sf(dp).optional(),()=>[]),_meta:W(O(F(),A()).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:W(pp.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ip=N({methodId:fp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Lp=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Rp=N({providerId:mp,apiType:hp,baseUrl:F(),headers:O(F(),F()).optional(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),zp=N({providerId:mp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Bp=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Vp=N({name:F(),value:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),$ne=N({name:F(),url:F(),headers:M(Vp),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ere=N({name:F(),url:F(),headers:M(Vp),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tre=N({name:F(),serverId:ip,_meta:W(O(F(),A()).nullish(),()=>void 0)}),nre=N({name:F(),command:F(),args:M(F()),env:M(Nf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Hp=Ae([$ne.and(N({type:j(`http`)})),ere.and(N({type:j(`sse`)})),tre.and(N({type:j(`acp`)})),nre]),Up=N({cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:nf(sf(Hp),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Wp=N({mcpServers:nf(sf(Hp),()=>[]),cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Gp=N({cwd:F().nullish(),cursor:F().nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Kp=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),qp=N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:W(sf(Hp).optional(),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Jp=N({sessionId:lf,cwd:F(),additionalDirectories:W(sf(F()).optional(),()=>[]),mcpServers:W(sf(Hp).optional(),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Yp=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Xp=N({sessionId:lf,modeId:gp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),Zp=ge(Ae([N({value:k(),type:j(`boolean`)}),N({value:yp})]),N({sessionId:lf,configId:vp,_meta:W(O(F(),A()).nullish(),()=>void 0)})),Qp=N({sessionId:lf,prompt:M(Sf),_meta:W(O(F(),A()).nullish(),()=>void 0)}),rre=N({uri:F(),name:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ire=N({name:F(),owner:F(),remoteUrl:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),$p=N({workspaceUri:W(F().nullish(),()=>void 0),workspaceFolders:M(rre).nullish(),repository:W(ire.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),are=Ae([j(`automatic`),j(`diagnostic`),j(`manual`)]),ore=N({uri:F(),languageId:F(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),sre=N({startLine:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cre=N({uri:F(),excerpts:M(sre),_meta:W(O(F(),A()).nullish(),()=>void 0)}),lre=N({uri:F(),diff:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),ure=N({action:F(),uri:F(),position:Cp,timestampMs:P(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),dre=N({uri:F(),languageId:F(),visibleRange:W(wp.nullish(),()=>void 0),lastFocusedMs:W(P().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),fre=Ae([j(`error`),j(`warning`),j(`information`),j(`hint`)]),pre=N({uri:F(),range:wp,severity:fre,message:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),mre=N({recentFiles:M(ore).nullish(),relatedSnippets:M(cre).nullish(),editHistory:M(lre).nullish(),userActions:M(ure).nullish(),openFiles:M(dre).nullish(),diagnostics:M(pre).nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),em=N({sessionId:lf,uri:F(),version:P(),position:Cp,selection:wp.nullish(),triggerKind:are,context:mre.nullish(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),tm=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)});N({id:cf,method:F(),params:Ae([Fp,Ip,Lp,Rp,zp,Bp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,sp,lp]).nullish()});const hre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),gre=N({content:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),_re=N({optionId:Af,_meta:W(O(F(),A()).nullish(),()=>void 0)}),vre=N({outcome:Ae([N({outcome:j(`cancelled`)}),_re.and(N({outcome:j(`selected`)}))]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),yre=N({terminalId:Tf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),bre=N({exitCode:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),xre=N({output:F(),truncated:k(),exitStatus:W(bre.nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Sre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Cre=N({exitCode:W(ie().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(F().nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)}),wre=N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Tre=Ae([F(),P(),P(),k(),M(F())]),nm=N({content:O(F(),Tre).nullish()});Ae([N({id:cf,result:Ae([hre,gre,vre,yre,xre,Sre,Cre,wre,of(ge(Ae([nm.and(N({action:j(`accept`)})),N({action:j(`decline`)}),N({action:j(`cancel`)}),af(N({action:F()}),`action`,[`accept`,`cancel`,`decline`])]),N({_meta:W(O(F(),A()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),N({connectionId:op,_meta:W(O(F(),A()).nullish(),()=>void 0)}),N({_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ep,Tp])}),N({id:cf,error:Dp})]);const rm=N({sessionId:lf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),im=N({sessionId:lf,uri:F(),languageId:F(),version:P(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),Ere=N({range:wp.nullish(),text:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),am=N({sessionId:lf,uri:F(),version:P(),contentChanges:nf(sf(Ere),()=>[]),_meta:W(O(F(),A()).nullish(),()=>void 0)}),om=N({sessionId:lf,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),sm=N({sessionId:lf,uri:F(),_meta:W(O(F(),A()).nullish(),()=>void 0)}),cm=N({sessionId:lf,uri:F(),version:P(),position:Cp,visibleRange:wp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),lm=N({sessionId:lf,id:Sp,_meta:W(O(F(),A()).nullish(),()=>void 0)}),um=N({sessionId:lf,id:Sp,reason:W(Ae([j(`rejected`),j(`ignored`),j(`replaced`),j(`cancelled`)]).nullish(),()=>void 0),_meta:W(O(F(),A()).nullish(),()=>void 0)});N({method:F(),params:Ae([rm,im,am,om,sm,cm,lm,um,Np,Pp]).nullish()}),N({requestId:cf,_meta:W(O(F(),A()).nullish(),()=>void 0)}),ep.and(N({mode:j(`form`)})).and(N({message:F()})),np.and(N({mode:j(`url`)})).and(N({message:F()})),Ae([zf,Bf]).and(N({message:F()})),Wf.and(N({type:j(`string`)})),Gf.and(N({type:j(`number`)})),Kf.and(N({type:j(`integer`)})),qf.and(N({type:j(`boolean`)})),Zf.and(N({type:j(`array`)})),Jf.and(N({type:j(`string`)})),nm.and(N({action:j(`accept`)})),N({action:j(`decline`)}),N({action:j(`cancel`)});const dm=`$/cancel_request`;function fm(e){return typeof e==`object`&&!!e}function Dre(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Ore(e){if(!(!fm(e)||!Dre(e.requestId)))return e.requestId}const pm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function mm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function kre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Are(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 hm(e){if(e instanceof vm)return e.toResult();if(Are(e))return vm.invalidParams(e.format()).toResult();let t=kre(e);try{return vm.internalError(t?JSON.parse(t):{}).toResult()}catch{return vm.internalError({details:t}).toResult()}}function jre(e){return e instanceof vm&&e.code===-32800?e:vm.requestCancelled(e)}function Mre(e,t){let n=Nre(e,t);return n?n.toResult():hm(e)}function Nre(e,t){if(!(!t.aborted||!Pre(e)))return jre(t.reason)}function Pre(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Fre=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 vm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?mm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},gm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Ire=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}},_m=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Ire(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 Lre}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 gm(()=>{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 mm(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(dm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?mm(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 pm.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(!fm(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(vm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Mre(n,t.responder.signal));else{let t=hm(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 Fre(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&&fm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new vm(n,r,i))}else t.reject(vm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==dm)return;let t=Ore(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(vm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?mm(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)}},Lre=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)??pm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?pm.no(r):await n(t(r.params),r.responder,i)??pm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?pm.no(r):await n(t(r.params),i)??pm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new _m(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},vm=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}}},Rre=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 zre(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Rre,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);fm(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 ym(e){return e??{}}function Bre(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function Vre(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}const bm={agent:{initialize:Qd.initialize,authenticate:Qd.authenticate,logout:Qd.logout,providers:{list:Qd.providers_list,set:Qd.providers_set,disable:Qd.providers_disable},session:{new:Qd.session_new,load:Qd.session_load,list:Qd.session_list,delete:Qd.session_delete,fork:Qd.session_fork,resume:Qd.session_resume,close:Qd.session_close,setMode:Qd.session_set_mode,setConfigOption:Qd.session_set_config_option,prompt:Qd.session_prompt,cancel:Qd.session_cancel},nes:{start:Qd.nes_start,suggest:Qd.nes_suggest,accept:Qd.nes_accept,reject:Qd.nes_reject,close:Qd.nes_close},document:{didOpen:Qd.document_did_open,didChange:Qd.document_did_change,didClose:Qd.document_did_close,didSave:Qd.document_did_save,didFocus:Qd.document_did_focus}},client:{session:{requestPermission:$d.session_request_permission,update:$d.session_update},fs:{writeTextFile:$d.fs_write_text_file,readTextFile:$d.fs_read_text_file},terminal:{create:$d.terminal_create,output:$d.terminal_output,release:$d.terminal_release,waitForExit:$d.terminal_wait_for_exit,kill:$d.terminal_kill},elicitation:{create:$d.elicitation_create,complete:$d.elicitation_complete}},protocol:{cancelRequest:ef.cancel_request}},xm=Symbol(`startActiveSession`);var Sm=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)}},Hre=class e extends Sm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){let r=Rm[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},Cm=class e extends Sm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}[xm](e,t){return this.sendRequest(Qd.session_new,e,e=>this.attachSession(e),t)}buildSession(e){return typeof e==`string`?Em.create(this,{cwd:e,mcpServers:[]}):Em.create(this,e)}attachSession(e){let t=new qre,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=Wm(this.connectionContext).attach(e,t),a=new gm(()=>{n.removeEventListener(`abort`,r)});return Jre.create(this,e,t,[i,a])}request(e,t,n){let r=Lm[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},wm=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)}},Ure=class extends wm{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=Hre.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Gm(this,this.connectHandlers))}},Wre=class extends wm{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=Cm.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Gm(this,this.connectHandlers))}};function Gre(e,t=[]){return new Ure(e,t)}function Kre(e,t=[]){return new Wre(e,t)}var qre=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 Tm(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var Em=class e{cx;request;constructor(e,t){this.cx=e,this.request=Tm(t)}static create(t,n){return new e(t,n)}toRequest(){return Tm(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[xm](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},Jre=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(Qd.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 Dm(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function Om(e,t,n){return{method:e,params:t,mapResponse:n}}function km(e,t){return{method:e,params:t}}function Am(e,t,n,r){e.onReceiveRequest(t.method,e=>Dm(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 jm(e,t,n,r){e.onReceiveNotification(t.method,e=>Dm(t.params,e),(e,t)=>r(n(e,t,t.signal)))}function Mm(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const Nm={initialize:Om(Qd.initialize,Fp),newSession:Om(Qd.session_new,Up),loadSession:Om(Qd.session_load,Wp,ym),unstable_forkSession:Om(Qd.session_fork,qp),listSessions:Om(Qd.session_list,Gp),deleteSession:Om(Qd.session_delete,Kp,ym),resumeSession:Om(Qd.session_resume,Jp),closeSession:Om(Qd.session_close,Yp,ym),setSessionMode:Om(Qd.session_set_mode,Xp,ym),setSessionConfigOption:Om(Qd.session_set_config_option,Zp),authenticate:Om(Qd.authenticate,Ip,ym),unstable_listProviders:Om(Qd.providers_list,Lp),unstable_setProvider:Om(Qd.providers_set,Rp,ym),unstable_disableProvider:Om(Qd.providers_disable,zp,ym),logout:Om(Qd.logout,Bp,ym),prompt:Om(Qd.session_prompt,Qp),unstable_startNes:Om(Qd.nes_start,$p),unstable_suggestNes:Om(Qd.nes_suggest,em),unstable_closeNes:Om(Qd.nes_close,tm,ym)},Pm={cancel:km(Qd.session_cancel,rm),unstable_didOpenDocument:km(Qd.document_did_open,im),unstable_didChangeDocument:km(Qd.document_did_change,am),unstable_didCloseDocument:km(Qd.document_did_close,om),unstable_didSaveDocument:km(Qd.document_did_save,sm),unstable_didFocusDocument:km(Qd.document_did_focus,cm),unstable_acceptNes:km(Qd.nes_accept,lm),unstable_rejectNes:km(Qd.nes_reject,um)},Fm={requestPermission:Om($d.session_request_permission,Mf),writeTextFile:Om($d.fs_write_text_file,uf,ym),readTextFile:Om($d.fs_read_text_file,df),createTerminal:Om($d.terminal_create,Pf),terminalOutput:Om($d.terminal_output,Ff),releaseTerminal:Om($d.terminal_release,If,ym),waitForTerminalExit:Om($d.terminal_wait_for_exit,Lf),killTerminal:Om($d.terminal_kill,Rf,ym),unstable_createElicitation:Om($d.elicitation_create,rp)},Im={sessionUpdate:km($d.session_update,jp),unstable_completeElicitation:km($d.elicitation_complete,Mp)},Lm=Mm(Nm);Mm(Pm);const Rm=Mm(Fm),zm=Mm(Im);function Bm(e,t,n,r){return{params:e,requestId:r,signal:n,agent:t}}function Vm(e,t,n){return{params:e,signal:n,agent:t}}var Hm=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==$d.session_update)return pm.no(e);let t=jp.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 pm.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 gm(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}};const Um=new WeakMap;function Wm(e){let t=Um.get(e);return t||(t=new Hm,Um.set(e,t)),t}function Gm(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 Km=Symbol(`appBuilder`),qm=Symbol(`runAgentConnectHandlers`),Jm=Symbol(`runClientConnectHandlers`);function Ym(e){return new Xm(e)}var Xm=class{builder=_m.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(e,t)=>Wm(t).handleMessage(e),describe:()=>`client-session-update-router`})}[Km](){return this.builder}[Jm](e){Gm(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=Rm[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=zm[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 Am(this.builder,e,(e,t,n,r)=>Bm(e,Cm.create(t,r),n,r),t),this}notification(e,t){return jm(this.builder,e,(e,t,n)=>Vm(e,Cm.create(t),n),t),this}connectConnection(e){if(Bre(e)){let t=this.openStreamConnection(e);return this[Jm](t.connection),t}let[t,n]=Vre(),r=e[Km]().connect(n),i=Gre(r),a=this.openStreamConnection(t);a.rawConnection.closed.then(()=>i.close()),r.closed.then(()=>a.connection.close());try{e[qm](i),this[Jm](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:Kre(t,this.connectHandlers)}}};new Set([Qd.initialize,Qd.authenticate,Qd.providers_list,Qd.providers_set,Qd.providers_disable,Qd.session_new,Qd.session_load,Qd.session_set_mode,Qd.session_set_config_option,Qd.session_prompt,Qd.session_list,Qd.session_delete,Qd.session_fork,Qd.session_resume,Qd.session_close,Qd.logout,Qd.nes_start,Qd.nes_suggest,Qd.nes_close]),new Set([Qd.session_cancel,Qd.nes_accept,Qd.nes_reject,Qd.document_did_open,Qd.document_did_change,Qd.document_did_close,Qd.document_did_save,Qd.document_did_focus]),new Set([$d.session_request_permission,$d.fs_write_text_file,$d.fs_read_text_file,$d.terminal_create,$d.terminal_output,$d.terminal_release,$d.terminal_wait_for_exit,$d.terminal_kill,$d.elicitation_create]),new Set([$d.session_update,$d.elicitation_complete]);function Zm(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const Qm=/^[a-zA-Z0-9_-]+$/,$m=64;function eh(e){return typeof e!=`string`||e.length===0||e.length>64||!Qm.test(e)?null:e}function th(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function nh(e){return!e.startsWith(`principal-`)}function rh(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 ih(e){let t=eh(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:th(t),displayName:typeof e.agentName==`string`?Zm(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?Zm(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?Zm(e.clientVersion):void 0,label:typeof e.label==`string`?Zm(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}const ah=()=>new Map,oh=e=>{let t=ah();return e.forEach((e,n)=>{t.set(n,e)}),t},sh=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},ch=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},lh=()=>new Set,uh=e=>e[e.length-1],dh=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},fh=Array.from,ph=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},mh=Array.isArray;var hh=class{constructor(){this._observers=ah()}on(e,t){return sh(this._observers,e,lh).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 fh((this._observers.get(e)||ah()).values()).forEach(e=>e(...t))}destroy(){this._observers=ah()}};const gh=Math.floor,_h=Math.abs,vh=(e,t)=>e<t?e:t,yh=(e,t)=>e>t?e:t;Number.isNaN;const bh=e=>e===0?1/e<0:e<0,xh=2**53-1,Sh=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&gh(e)===e);Number.isNaN,Number.parseInt;const Ch=String.fromCharCode;String.fromCodePoint,Ch(65535);const wh=e=>e.toLowerCase(),Th=/^\s*/g,Eh=e=>e.replace(Th,``),Dh=/([A-Z])/g,Oh=(e,t)=>Eh(e.replace(Dh,e=>`${t}${wh(e)}`)),kh=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},Ah=typeof TextEncoder<`u`?new TextEncoder:null,jh=Ah?e=>Ah.encode(e):kh;let Mh=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Mh&&Mh.decode(new Uint8Array).length===1&&(Mh=null);var Nh=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Ph=()=>new Nh,Fh=e=>{let t=Ph();return e(t),Lh(t)},Ih=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Lh=e=>{let t=new Uint8Array(Ih(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},Rh=(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(yh(n,t)*2),e.cpos=0)},zh=(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},Bh=zh,Vh=(e,t)=>{for(;t>127;)zh(e,128|127&t),t=gh(t/128);zh(e,127&t)},Hh=(e,t)=>{let n=bh(t);for(n&&(t=-t),zh(e,(t>63?128:0)|(n?64:0)|63&t),t=gh(t/64);t>0;)zh(e,(t>127?128:0)|127&t),t=gh(t/128)},Uh=new Uint8Array(3e4),Wh=Uh.length/3,Gh=Ah&&Ah.encodeInto?(e,t)=>{if(t.length<Wh){let n=Ah.encodeInto(t,Uh).written||0;Vh(e,n);for(let t=0;t<n;t++)zh(e,Uh[t])}else qh(e,jh(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Vh(e,r);for(let t=0;t<r;t++)zh(e,n.codePointAt(t))},Kh=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=vh(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(yh(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},qh=(e,t)=>{Vh(e,t.byteLength),Kh(e,t)},Jh=(e,t)=>{Rh(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Yh=(e,t)=>Jh(e,4).setFloat32(0,t,!1),Xh=(e,t)=>Jh(e,8).setFloat64(0,t,!1),Zh=(e,t)=>Jh(e,8).setBigInt64(0,t,!1),Qh=new DataView(new ArrayBuffer(4)),$h=e=>(Qh.setFloat32(0,e),Qh.getFloat32(0)===e),eg=(e,t)=>{switch(typeof t){case`string`:zh(e,119),Gh(e,t);break;case`number`:Sh(t)&&_h(t)<=2147483647?(zh(e,125),Hh(e,t)):$h(t)?(zh(e,124),Yh(e,t)):(zh(e,123),Xh(e,t));break;case`bigint`:zh(e,122),Zh(e,t);break;case`object`:if(t===null)zh(e,126);else if(mh(t)){zh(e,117),Vh(e,t.length);for(let n=0;n<t.length;n++)eg(e,t[n])}else if(t instanceof Uint8Array)zh(e,116),qh(e,t);else{zh(e,118);let n=Object.keys(t);Vh(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Gh(e,i),eg(e,t[i])}}break;case`boolean`:zh(e,t?120:121);break;default:zh(e,127)}};var tg=class extends Nh{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Vh(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const ng=e=>{e.count>0&&(Hh(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Vh(e.encoder,e.count-2))};var rg=class{constructor(){this.encoder=new Nh,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ng(this),this.count=1,this.s=e)}toUint8Array(){return ng(this),Lh(this.encoder)}};const ig=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Hh(e.encoder,t),e.count>1&&Vh(e.encoder,e.count-2)}};var ag=class{constructor(){this.encoder=new Nh,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ig(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ig(this),Lh(this.encoder)}},og=class{constructor(){this.sarr=[],this.s=``,this.lensE=new rg}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 Nh;return this.sarr.push(this.s),this.s=``,Gh(e,this.sarr.join(``)),Kh(e,this.lensE.toUint8Array()),Lh(e)}};const sg=e=>Error(e),cg=()=>{throw sg(`Method unimplemented`)},lg=()=>{throw sg(`Unexpected case`)},ug=sg(`Unexpected end of array`),dg=sg(`Integer out of Range`);var fg=class{constructor(e){this.arr=e,this.pos=0}};const pg=e=>new fg(e),mg=e=>e.pos!==e.arr.length,hg=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},gg=e=>hg(e,vg(e)),_g=e=>e.arr[e.pos++],vg=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>xh)throw dg}throw ug},yg=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>xh)throw dg}throw ug},bg=Mh?e=>Mh.decode(gg(e)):e=>{let t=vg(e);if(t===0)return``;{let n=String.fromCodePoint(_g(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(_g(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))}},xg=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Sg=[e=>void 0,e=>null,yg,e=>xg(e,4).getFloat32(0,!1),e=>xg(e,8).getFloat64(0,!1),e=>xg(e,8).getBigInt64(0,!1),e=>!1,e=>!0,bg,e=>{let t=vg(e),n={};for(let r=0;r<t;r++){let t=bg(e);n[t]=Cg(e)}return n},e=>{let t=vg(e),n=[];for(let r=0;r<t;r++)n.push(Cg(e));return n},gg],Cg=e=>Sg[127-_g(e)](e);var wg=class extends fg{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),mg(this)?this.count=vg(this)+1:this.count=-1),this.count--,this.s}},Tg=class extends fg{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=yg(this);let e=bh(this.s);this.count=1,e&&(this.s=-this.s,this.count=vg(this)+2)}return this.count--,this.s}},Eg=class extends fg{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=yg(this),t=e&1;this.diff=gh(e/2),this.count=1,t&&(this.count=vg(this)+2)}return this.s+=this.diff,this.count--,this.s}},Dg=class{constructor(e){this.decoder=new Tg(e),this.str=bg(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}};Nu.subtle;const Og=Nu.getRandomValues.bind(Nu),kg=()=>Og(new Uint32Array(1))[0],Ag=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^kg()&15>>e/4).toString(16)),jg=Date.now,Mg=e=>new Promise(e);Promise.all.bind(Promise);const Ng=e=>e===void 0?null:e;let Pg=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&&(Pg=localStorage)}catch{}const Fg=Pg,Ig=Symbol(`Equality`),Lg=(e,t)=>e===t||!!e?.[Ig]?.(t)||!1,Rg=Object.assign,zg=Object.keys,Bg=(e,t)=>{for(let n in e)t(e[n],n)},Vg=e=>zg(e).length,Hg=e=>{for(let t in e)return!1;return!0},Ug=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Wg=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Gg=(e,t)=>e===t||Vg(e)===Vg(t)&&Ug(e,(e,n)=>(e!==void 0||Wg(t,n))&&Lg(t[n],e)),Kg=Object.freeze,qg=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&qg(e[t])}return Kg(e)},Jg=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Jg(e,t,n+1)}},Yg=e=>e,Xg=(e,t)=>t.includes(e),Zg=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,Qg=typeof window<`u`&&typeof document<`u`&&!Zg;typeof navigator<`u`&&/Mac/.test(navigator.platform);let $g;const e_=[],t_=()=>{if($g===void 0)if(Zg){$g=ah();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&$g.set(t,``),t=r):t===null?e_.push(r):($g.set(t,r),t=null)}t!==null&&$g.set(t,``)}else typeof location==`object`?($g=ah(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);$g.set(`--${Oh(t,`-`)}`,n),$g.set(`-${Oh(t,`-`)}`,n)}})):$g=ah();return $g},n_=e=>t_().has(e),r_=e=>Ng(Zg?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:Fg.getItem(e)),i_=e=>n_(`--`+e)||r_(e)!==null;i_(`production`);const a_=Zg&&Xg(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!n_(`--no-colors`)&&!i_(`no-color`)&&(!Zg||process.stdout.isTTY)&&(!Zg||n_(`--color`)||r_(`COLORTERM`)!==null||(r_(`TERM`)||``).includes(`color`)),o_=e=>new Uint8Array(e),s_=Qg?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=Ch(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),c_=e=>{let t=o_(e.byteLength);return t.set(e),t},l_=e=>Fh(t=>eg(t,e)),u_=Symbol,d_=u_(),f_=u_(),p_=u_(),m_=u_(),h_=u_(),g_=u_(),__=u_(),v_=u_(),y_=u_(),b_=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};jg();const x_={[d_]:`\x1B[1m`,[f_]:`\x1B[2m`,[p_]:`\x1B[34m`,[h_]:`\x1B[32m`,[m_]:`\x1B[37m`,[g_]:`\x1B[31m`,[__]:`\x1B[35m`,[v_]:`\x1B[38;5;208m`,[y_]:`\x1B[0m`},S_=a_?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=x_[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}:b_,C_=(...e)=>{console.log(...S_(e))},w_=(...e)=>{console.warn(...S_(e))},T_=e=>({[Symbol.iterator](){return this},next:e}),E_=(e,t)=>T_(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),D_=(e,t)=>T_(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var O_=class{constructor(e,t){this.clock=e,this.len=t}},k_=class{constructor(){this.clients=new Map}};const A_=(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])zv(e,i,o.clock,o.len,n)}}),j_=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=gh((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},M_=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&j_(n,t.clock)!==null},N_=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 O_(r.clock,yh(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},P_=e=>{let t=new k_;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++)dh(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return N_(t),t},F_=(e,t,n,r)=>{sh(e.clients,t,()=>[]).push(new O_(n,r))},I_=()=>new k_,L_=e=>{let t=I_();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 O_(i,a))}}r.length>0&&t.clients.set(n,r)}),t},R_=(e,t)=>{Vh(e.restEncoder,t.clients.size),fh(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Vh(e.restEncoder,t);let r=n.length;Vh(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},z_=e=>{let t=new k_,n=vg(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=vg(e.restDecoder),r=vg(e.restDecoder);if(r>0){let i=sh(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new O_(e.readDsClock(),e.readDsLen()))}}return t},B_=(e,t,n)=>{let r=new k_,i=vg(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=vg(e.restDecoder),a=vg(e.restDecoder),o=n.clients.get(i)||[],s=Mv(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&F_(r,i,s,a-s);let e=Pv(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,eb(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,eb(t,c,a-c.id.clock)),c.delete(t))}else F_(r,i,n,a-n)}}if(r.clients.size>0){let e=new Z_;return Vh(e.restEncoder,0),R_(e,r),e.toUint8Array()}return null},V_=(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},H_=kg;var U_=class e extends hh{constructor({guid:e=Ag(),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=H_(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Av,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=Mg(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>Mg(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&&Wv(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(fh(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Wv(this,e,t)}get(e,t=sy){let n=sh(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==sy&&r!==t)if(r===sy){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,Cy)}getText(e=``){return this.get(e,Ly)}getMap(e=``){return this.get(e,wy)}getXmlElement(e=``){return this.get(e,By)}getXmlFragment(e=``){return this.get(e,zy)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,fh(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,Wv(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()}},W_=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return vg(this.restDecoder)}readDsLen(){return vg(this.restDecoder)}},G_=class extends W_{readLeftID(){return Sv(vg(this.restDecoder),vg(this.restDecoder))}readRightID(){return Sv(vg(this.restDecoder),vg(this.restDecoder))}readClient(){return vg(this.restDecoder)}readInfo(){return _g(this.restDecoder)}readString(){return bg(this.restDecoder)}readParentInfo(){return vg(this.restDecoder)===1}readTypeRef(){return vg(this.restDecoder)}readLen(){return vg(this.restDecoder)}readAny(){return Cg(this.restDecoder)}readBuf(){return c_(gg(this.restDecoder))}readJSON(){return JSON.parse(bg(this.restDecoder))}readKey(){return bg(this.restDecoder)}},K_=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=vg(this.restDecoder),this.dsCurrVal}readDsLen(){let e=vg(this.restDecoder)+1;return this.dsCurrVal+=e,e}},q_=class extends K_{constructor(e){super(e),this.keys=[],vg(e),this.keyClockDecoder=new Eg(gg(e)),this.clientDecoder=new Tg(gg(e)),this.leftClockDecoder=new Eg(gg(e)),this.rightClockDecoder=new Eg(gg(e)),this.infoDecoder=new wg(gg(e),_g),this.stringDecoder=new Dg(gg(e)),this.parentInfoDecoder=new wg(gg(e),_g),this.typeRefDecoder=new Tg(gg(e)),this.lenDecoder=new Tg(gg(e))}readLeftID(){return new bv(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new bv(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 Cg(this.restDecoder)}readBuf(){return gg(this.restDecoder)}readJSON(){return Cg(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}}},J_=class{constructor(){this.restEncoder=Ph()}toUint8Array(){return Lh(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Vh(this.restEncoder,e)}writeDsLen(e){Vh(this.restEncoder,e)}},Y_=class extends J_{writeLeftID(e){Vh(this.restEncoder,e.client),Vh(this.restEncoder,e.clock)}writeRightID(e){Vh(this.restEncoder,e.client),Vh(this.restEncoder,e.clock)}writeClient(e){Vh(this.restEncoder,e)}writeInfo(e){Bh(this.restEncoder,e)}writeString(e){Gh(this.restEncoder,e)}writeParentInfo(e){Vh(this.restEncoder,+!!e)}writeTypeRef(e){Vh(this.restEncoder,e)}writeLen(e){Vh(this.restEncoder,e)}writeAny(e){eg(this.restEncoder,e)}writeBuf(e){qh(this.restEncoder,e)}writeJSON(e){Gh(this.restEncoder,JSON.stringify(e))}writeKey(e){Gh(this.restEncoder,e)}},X_=class{constructor(){this.restEncoder=Ph(),this.dsCurrVal=0}toUint8Array(){return Lh(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Vh(this.restEncoder,t)}writeDsLen(e){e===0&&lg(),Vh(this.restEncoder,e-1),this.dsCurrVal+=e}},Z_=class extends X_{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new ag,this.clientEncoder=new rg,this.leftClockEncoder=new ag,this.rightClockEncoder=new ag,this.infoEncoder=new tg(Bh),this.stringEncoder=new og,this.parentInfoEncoder=new tg(Bh),this.typeRefEncoder=new rg,this.lenEncoder=new rg}toUint8Array(){let e=Ph();return Vh(e,0),qh(e,this.keyClockEncoder.toUint8Array()),qh(e,this.clientEncoder.toUint8Array()),qh(e,this.leftClockEncoder.toUint8Array()),qh(e,this.rightClockEncoder.toUint8Array()),qh(e,Lh(this.infoEncoder)),qh(e,this.stringEncoder.toUint8Array()),qh(e,Lh(this.parentInfoEncoder)),qh(e,this.typeRefEncoder.toUint8Array()),qh(e,this.lenEncoder.toUint8Array()),Kh(e,Lh(this.restEncoder)),Lh(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){eg(this.restEncoder,e)}writeBuf(e){qh(this.restEncoder,e)}writeJSON(e){eg(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 Q_=(e,t,n,r)=>{r=yh(r,t[0].id.clock);let i=Pv(t,r);Vh(e.restEncoder,t.length-i),e.writeClient(n),Vh(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)},$_=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Mv(t,n)>e&&r.set(n,e)}),jv(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Vh(e.restEncoder,r.size),fh(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{Q_(e,t.clients.get(n),n,r)})},ev=(e,t)=>{let n=ah(),r=vg(e.restDecoder);for(let i=0;i<r;i++){let r=vg(e.restDecoder),i=Array(r),a=e.readClient(),o=vg(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 Uy(Sv(a,o),t),o+=t;break}case 10:{let t=vg(e.restDecoder);i[n]=new ab(Sv(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new rb(Sv(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,ib(e,r));i[n]=c,o+=c.length}}}}return n},tv=(e,t,n)=>{let r=[],i=fh(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 Av,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!==ab){let i=sh(d,u.id.client,()=>Mv(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,Mv(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 Z_;return $_(e,s,new Map),Vh(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},nv=(e,t)=>$_(e,t.doc.store,t.beforeState),rv=(e,t,n,r=new q_(e))=>Wv(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=tv(e,i,ev(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Mv(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=Yv([o.update,a.update])}}else i.pendingStructs=a;let s=B_(r,e,i);if(i.pendingDs){let t=new q_(pg(i.pendingDs));vg(t.restDecoder);let n=B_(t,e,i);s&&n?i.pendingDs=Yv([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,iv(e.doc,t)}},n,!1),iv=(e,t,n,r=q_)=>{let i=pg(t);rv(i,e,n,new r(i))},av=(e,t,n)=>iv(e,t,n,G_),ov=(e,t,n=new Map)=>{$_(e,t.store,n),R_(e,L_(t.store))},sv=(e,t=new Uint8Array([0]),n=new Z_)=>{ov(n,e,uv(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(oie(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===Y_)return iie(r.map((e,t)=>t===0?e:cie(e)));if(n.constructor===Z_)return Yv(r)}return r[0]},cv=(e,t)=>sv(e,t,new Y_),lv=e=>{let t=new Map,n=vg(e.restDecoder);for(let r=0;r<n;r++){let n=vg(e.restDecoder),r=vg(e.restDecoder);t.set(n,r)}return t},uv=e=>lv(new W_(pg(e))),dv=(e,t)=>(Vh(e.restEncoder,t.size),fh(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Vh(e.restEncoder,t),Vh(e.restEncoder,n)}),e),fv=(e,t)=>dv(e,jv(t.store)),pv=(e,t=new X_)=>(e instanceof Map?dv(t,e):fv(t,e),t.toUint8Array()),mv=e=>pv(e,new J_);var hv=class{constructor(){this.l=[]}};const gv=()=>new hv,_v=(e,t)=>e.l.push(t),vv=(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.`)},yv=(e,t,n)=>Jg(e.l,[t,n]);var bv=class{constructor(e,t){this.client=e,this.clock=t}};const xv=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,Sv=(e,t)=>new bv(e,t),Cv=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw lg()},wv=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var Tv=class{constructor(e,t){this.ds=e,this.sv=t}};const Ev=(e,t)=>new Tv(e,t);Ev(I_(),new Map);const Dv=e=>Ev(L_(e.store),jv(e.store)),Ov=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!M_(t.ds,e.id),kv=(e,t)=>{let n=sh(e.meta,kv,lh),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Mv(r,n)&&Lv(e,Sv(n,t))}),A_(e,t.ds,e=>{}),n.add(t))},Yre=(e,t,n=q_)=>{let r=new n(pg(t)),i=new qv(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=P_([e.ds,z_(r)]);return V_(e.ds,a)},Xre=(e,t)=>Yre(e,t,G_);var Av=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const jv=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},Mv=(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},Nv=(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 lg()}n.push(t)},Pv=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=gh(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=gh((n+r)/2)}throw lg()},Fv=(e,t)=>{let n=e.clients.get(t.client);return n[Pv(n,t.clock)]},Iv=(e,t,n)=>{let r=Pv(t,n),i=t[r];return i.id.clock<n&&i instanceof rb?(t.splice(r+1,0,eb(e,i,n-i.id.clock)),r+1):r},Lv=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Iv(e,n,t.clock)]},Rv=(e,t,n)=>{let r=t.clients.get(n.client),i=Pv(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==Uy&&r.splice(i+1,0,eb(e,a,n.clock-a.id.clock+1)),a},Zre=(e,t,n)=>{let r=e.clients.get(t.id.client);r[Pv(r,t.id.clock)]=n},zv=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Iv(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Iv(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Qre=class{constructor(e,t,n){this.doc=e,this.deleteSet=new k_,this.beforeState=jv(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 Bv=(e,t)=>t.deleteSet.clients.size===0&&!ch(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(N_(t.deleteSet),nv(e,t),R_(e,t.deleteSet),!0),Vv=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&sh(e.changed,t,lh).add(n)},Hv=(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 rb&&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},$re=(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=Pv(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 rb&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},eie=(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=vh(r.length-1,1+Pv(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+Hv(r,e)}})},Uv=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{N_(a),n.afterState=jv(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(()=>{yv(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&Cie(n)})}),Jg(e,[])}finally{r.gc&&$re(a,i,r.gcFilter),eie(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=yh(Pv(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Hv(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=Pv(r,n);a+1<r.length&&Hv(r,a+1)>1||a>0&&Hv(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(C_(v_,d_,`[yjs] `,f_,g_,`Changed the client-id because another client seems to be using it.`),r.clientID=H_()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new Y_;Bv(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new Z_;Bv(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])):Uv(e,t+1)}}},Wv=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Qre(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&&Uv(i,0)}}return o};var tie=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const Gv=(e,t,n)=>{A_(e,n.deletions,n=>{n instanceof rb&&t.scope.some(t=>t===e.doc||wv(t,n))&&$y(n,!1)})},Kv=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Wv(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;A_(n,o.insertions,e=>{if(e instanceof rb){if(e.redone!==null){let{item:t,diff:i}=Zie(r,e.id);i>0&&(t=Lv(n,Sv(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||wv(t,e))&&c.push(e)}}),A_(n,o.deletions,e=>{e instanceof rb&&a.some(t=>t===n.doc||wv(t,e))&&!M_(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=nb(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 nie=class extends hh{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=mh(e)?e[0].doc:e instanceof U_?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 k_;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&F_(i,n,r,a)});let a=jg(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=P_([t.deletions,e.deleteSet]),t.insertions=P_([t.insertions,i])}else r.push(new tie(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),A_(e,e.deleteSet,t=>{t instanceof rb&&this.scope.some(n=>n===e.doc||wv(n,t))&&$y(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=mh(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof sy?e.doc!==this.doc:e!==this.doc)&&w_(`[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=>Gv(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>Gv(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=Kv(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Kv(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*rie(e){let t=vg(e.restDecoder);for(let n=0;n<t;n++){let t=vg(e.restDecoder),n=e.readClient(),r=vg(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=vg(e.restDecoder);yield new ab(Sv(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new rb(Sv(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,ib(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new Uy(Sv(n,r),t),r+=t}}}}var qv=class{constructor(e,t){this.gen=rie(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===ab);return this.curr}},Jv=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const iie=e=>Yv(e,G_,Y_),aie=(e,t)=>{if(e.constructor===Uy){let{client:n,clock:r}=e.id;return new Uy(Sv(n,r+t),e.length-t)}else if(e.constructor===ab){let{client:n,clock:r}=e.id;return new ab(Sv(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new rb(Sv(r,i+t),null,Sv(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Yv=(e,t=q_,n=Z_)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(pg(e))),i=r.map(e=>new qv(e,!0)),a=null,o=new n,s=new Jv(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===ab?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)Zv(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===ab)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{Zv(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new ab(Sv(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===ab?a.struct.length-=t:n=aie(n,t)),a.struct.mergeWith(n)||(Zv(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!==ab;n=e.next())Zv(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(Zv(s,a.struct,a.offset),a=null),Qv(s),R_(o,P_(r.map(e=>z_(e)))),o.toUint8Array()},oie=(e,t,n=q_,r=Z_)=>{let i=uv(t),a=new r,o=new Jv(a),s=new n(pg(e)),c=new qv(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===ab){c.next();continue}if(e.id.clock+e.length>n)for(Zv(o,e,yh(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)Zv(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 Qv(o),R_(a,z_(s)),a.toUint8Array()},Xv=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Lh(e.encoder.restEncoder)}),e.encoder.restEncoder=Ph(),e.written=0)},Zv=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Xv(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Vh(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Qv=e=>{Xv(e);let t=e.encoder.restEncoder;Vh(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Vh(t,r.written),Kh(t,r.restEncoder)}},sie=(e,t,n,r)=>{let i=new n(pg(e)),a=new qv(i,!1),o=new r,s=new Jv(o);for(let e=a.curr;e!==null;e=a.next())Zv(s,t(e),0);return Qv(s),R_(o,z_(i)),o.toUint8Array()},cie=e=>sie(e,Yg,q_,Y_),$v=`You must not compute changes after the event-handler fired.`;var ey=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||=lie(this.currentTarget,this.target)}deletes(e){return M_(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw sg($v);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=uh(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=uh(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=uh(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 sg($v);let t=this.target,n=lh(),r=lh(),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 lie=(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},ty=()=>{w_(`Invalid access: Add Yjs type to a document before reading data.`)};let ny=0;var uie=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ny++}};const die=e=>{e.timestamp=ny++},ry=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ny++},fie=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return ry(r,t,n),r}else{let r=new uie(t,n);return e.push(r),r}},iy=(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)=>_h(t-e.index)<_h(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,die(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&&_h(n.index-i)<r.parent.length/80?(ry(n,r,i),n):fie(e._searchMarker,r,i)},ay=(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=yh(t,i.index+n))}},oy=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;sh(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;yv(r._eH,n,t)};var sy=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=gv(),this._dEH=gv(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw cg()}clone(){throw cg()}_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){_v(this._eH,e)}observeDeep(e){_v(this._dEH,e)}unobserve(e){vv(this._eH,e)}unobserveDeep(e){vv(this._dEH,e)}toJSON(){}};const cy=(e,t,n)=>{e.doc??ty(),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},ly=e=>{e.doc??ty();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},pie=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&Ov(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},uy=(e,t)=>{let n=0,r=e._start;for(e.doc??ty();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}},dy=(e,t)=>{let n=[];return uy(e,(r,i)=>{n.push(t(r,i,e))}),n},mie=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}}}},fy=(e,t)=>{e.doc??ty();let n=iy(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}},py=(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 rb(Sv(o,Mv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Xy(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 rb(Sv(o,Mv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Wy(new Uint8Array(n))),i.integrate(e,0);break;case U_:i=new rb(Sv(o,Mv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new qy(n)),i.integrate(e,0);break;default:if(n instanceof sy)i=new rb(Sv(o,Mv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Qy(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},my=()=>sg(`Length exceeded!`),hy=(e,t,n,r)=>{if(n>t._length)throw my();if(n===0)return t._searchMarker&&ay(t._searchMarker,n,r.length),py(e,t,null,r);let i=n,a=iy(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&&Lv(e,Sv(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ay(t._searchMarker,i,r.length),py(e,t,o,r)},hie=(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 py(e,t,r,n)},gy=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=iy(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&&Lv(e,Sv(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Lv(e,Sv(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw my();t._searchMarker&&ay(t._searchMarker,i,-a+r)},_y=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},vy=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new Xy([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new Xy([r]);break;case Uint8Array:s=new Wy(r);break;case U_:s=new qy(r);break;default:if(r instanceof sy)s=new Qy(r);else throw Error(`Unexpected content type`)}new rb(Sv(o,Mv(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},yy=(e,t)=>{e.doc??ty();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},by=e=>{let t={};return e.doc??ty(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},xy=(e,t)=>{e.doc??ty();let n=e._map.get(t);return n!==void 0&&!n.deleted},gie=(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&&Ov(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Sy=e=>(e.doc??ty(),E_(e._map.entries(),e=>!e[1].deleted));var _ie=class extends ey{},Cy=class e extends sy{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 sy?e.clone():e)),t}get length(){return this.doc??ty(),this._length}_callObserver(e,t){super._callObserver(e,t),oy(this,e,new _ie(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Wv(this.doc,n=>{hy(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Wv(this.doc,t=>{hie(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Wv(this.doc,n=>{gy(n,this,e,t)})}get(e){return fy(this,e)}toArray(){return ly(this)}slice(e=0,t=this.length){return cy(this,e,t)}toJSON(){return this.map(e=>e instanceof sy?e.toJSON():e)}map(e){return dy(this,e)}forEach(e){uy(this,e)}[Symbol.iterator](){return mie(this)}_write(e){e.writeTypeRef(Uie)}};const vie=e=>new Cy;var yie=class extends ey{constructor(e,t,n){super(e,t),this.keysChanged=n}},wy=class e extends sy{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 sy?e.clone():e)}),t}_callObserver(e,t){oy(this,e,new yie(this,e,t))}toJSON(){this.doc??ty();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof sy?r.toJSON():r}}),e}get size(){return[...Sy(this)].length}keys(){return D_(Sy(this),e=>e[0])}values(){return D_(Sy(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return D_(Sy(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??ty(),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):Wv(this.doc,t=>{_y(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Wv(this.doc,n=>{vy(n,this,e,t)}),t}get(e){return yy(this,e)}has(e){return xy(this,e)}clear(){this.doc===null?this._prelimContent.clear():Wv(this.doc,e=>{this.forEach(function(t,n,r){_y(e,r,n)})})}_write(e){e.writeTypeRef(Wie)}};const bie=e=>new wy,Ty=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Gg(e,t);var Ey=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&lg(),this.right.content.constructor){case Yy:this.right.deleted||Ay(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 Dy=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case Yy:t.right.deleted||Ay(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Lv(e,Sv(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},Oy=(e,t,n,r)=>{let i=new Map,a=r?iy(t,n):null;return a?Dy(e,new Ey(a.p.left,a.p,a.index,i),n-a.index):Dy(e,new Ey(null,t._start,0,i),n)},ky=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===Yy&&Ty(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 rb(Sv(a,Mv(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new Yy(o,r));l.integrate(e,0),n.right=l,n.forward()})},Ay=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},jy=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===Yy&&Ty(t[e.right.content.key]??null,e.right.content.value));)e.forward()},My=(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(!Ty(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new rb(Sv(a,Mv(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new Yy(s,c)),n.right.integrate(e,0),n.forward()}}return o},Ny=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;jy(n,i);let s=My(e,t,n,i),c=r.constructor===String?new Zy(r):r instanceof sy?new Qy(r):new Jy(r),{left:l,right:u,index:d}=n;t._searchMarker&&ay(t._searchMarker,n.index,c.getLength()),u=new rb(Sv(o,Mv(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(),ky(e,t,n,s)},Py=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;jy(n,i);let s=My(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===Yy));){if(!n.right.deleted)switch(n.right.content.constructor){case Yy:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Ty(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&&Lv(e,Sv(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 rb(Sv(o,Mv(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Zy(i)),n.right.integrate(e,0),n.forward()}ky(e,t,n,s)},Fy=(e,t,n,r,i)=>{let a=t,o=ah();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===Yy){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 Yy:{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&&Ay(i,n);break}}}t=t.right}return s},xie=(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===Yy){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Sie=e=>{let t=0;return Wv(e.doc,n=>{let r=e._start,i=e._start,a=ah(),o=oh(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case Yy:Ay(o,i.content);break;default:t+=Fy(n,r,i,a,o),a=oh(o),r=i;break}i=i.right}}),t},Cie=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&&zv(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===Yy&&e.constructor!==Uy&&t.add(e.parent)})}Wv(n,n=>{A_(e,e.deleteSet,e=>{if(e instanceof Uy||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===Yy?t.add(r):xie(n,e)});for(let e of t)Sie(e)})},Iy=(e,t,n)=>{let r=n,i=oh(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case Qy:case Jy:case Zy:n<t.right.length&&Lv(e,Sv(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&Fy(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&ay(o._searchMarker,t.index,-r+n),t};var wie=class extends ey{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=[];Wv(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},Hg(o)||(e.attributes=Rg({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case Qy:case Jy: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 Zy: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 Yy:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Ty(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Ty(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;Ty(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Ty(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Ay(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}},Ly=class e extends sy{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ty(),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 wie(this,e,t);oy(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ty();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===Zy&&(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)):Wv(this.doc,n=>{let r=new Ey(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)&&Ny(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Iy(n,r,a.delete):Py(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??ty();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(Ov(s,e)||t!==void 0&&Ov(s,t))switch(s.content.constructor){case Zy:{let r=i.get(`ychange`);e!==void 0&&!Ov(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&&!Ov(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 Qy:case Jy:{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 Yy:Ov(s,e)&&(c(),Ay(i,s.content));break}s=s.right}c()};return e||t?Wv(a,n=>{e&&kv(n,e),t&&kv(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)):Wv(r,r=>{let i=Oy(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Ny(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Wv(r,r=>{let i=Oy(r,this,e,!n);Ny(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)):Wv(n,n=>{Iy(n,Oy(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)):Wv(r,r=>{let i=Oy(r,this,e,!1);i.right!==null&&Py(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Wv(this.doc,t=>{_y(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Wv(this.doc,n=>{vy(n,this,e,t)})}getAttribute(e){return yy(this,e)}getAttributes(){return by(this)}_write(e){e.writeTypeRef(Gie)}};const Tie=e=>new Ly;var Ry=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ty()}[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===By||t.constructor===zy)&&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})}},zy=class e extends sy{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 sy?e.clone():e)),t}get length(){return this.doc??ty(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Ry(this,e)}querySelector(e){e=e.toUpperCase();let t=new Ry(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),fh(new Ry(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){oy(this,e,new Oie(this,t,e))}toString(){return dy(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),uy(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Wv(this.doc,n=>{hy(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Wv(this.doc,n=>{let r=e&&e instanceof sy?e._item:e;py(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 sg(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Wv(this.doc,n=>{gy(n,this,e,t)})}toArray(){return ly(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return fy(this,e)}slice(e=0,t=this.length){return cy(this,e,t)}forEach(e){uy(this,e)}_write(e){e.writeTypeRef(qie)}};const Eie=e=>new zy;var By=class e extends zy{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 Bg(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof sy?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):Wv(this.doc,t=>{_y(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Wv(this.doc,n=>{vy(n,this,e,t)})}getAttribute(e){return yy(this,e)}hasAttribute(e){return xy(this,e)}getAttributes(e){return e?gie(this,e):by(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 uy(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Kie),e.writeKey(this.nodeName)}};const Die=e=>new By(e.readKey());var Oie=class extends ey{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)})}},kie=class e extends wy{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(Jie),e.writeKey(this.hookName)}};const Aie=e=>new kie(e.readKey());var Vy=class e extends Ly{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(Yie)}};const jie=e=>new Vy;var Hy=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw cg()}mergeWith(e){return!1}write(e,t,n){throw cg()}integrate(e,t){throw cg()}},Uy=class extends Hy{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),Nv(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},Wy=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 cg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const Mie=e=>new Wy(e.readBuf());var Gy=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){F_(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 Nie=e=>new Gy(e.readLen()),Ky=(e,t)=>new U_({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var qy=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(Ky(this.doc.guid,this.opts))}splice(e){throw cg()}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 Pie=e=>new qy(Ky(e.readString(),e.readAny()));var Jy=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 cg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const Fie=e=>new Jy(e.readJSON());var Yy=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 cg()}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 Iie=e=>new Yy(e.readKey(),e.readJSON());var Lie=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 Rie=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 Lie(n)},zie=r_(`node_env`)===`development`;var Xy=class e{constructor(e){this.arr=e,zie&&qg(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 Bie=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Xy(n)};var Zy=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 Vie=e=>new Zy(e.readString()),Hie=[vie,bie,Tie,Die,Eie,Aie,jie],Uie=0,Wie=1,Gie=2,Kie=3,qie=4,Jie=5,Yie=6;var Qy=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 cg()}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 Xie=e=>new Qy(Hie[e.readTypeRef()](e)),Zie=(e,t)=>{let n=t,r=0,i;do r>0&&(n=Sv(n.client,n.clock+r)),i=Fv(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof rb);return{item:i,diff:r}},$y=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},eb=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new rb(Sv(r,i+n),t,Sv(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=Sv(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},tb=(e,t)=>ph(e,e=>M_(e.deletions,t)),nb=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Lv(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||nb(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Lv(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:Lv(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:Lv(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||M_(r,d.right.id)||tb(a.undoStack,d.right.id)||tb(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Lv(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=Sv(c,Mv(s,c)),h=new rb(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,$y(h,!0),h.integrate(e,0),h};var rb=class e extends Hy{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>=Mv(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Mv(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===bv&&this.id.client!==this.parent.client&&this.parent.clock>=Mv(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Rv(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Lv(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===Uy||this.right&&this.right.constructor===Uy)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===bv){let e=Fv(n,this.parent);e.constructor===Uy?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Rv(e,e.doc.store,Sv(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),xv(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(xv(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Fv(e.doc.store,n.origin)))r.has(Fv(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),Nv(e.doc.store,this),this.content.integrate(e,this),Vv(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Uy(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:Sv(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&xv(e.origin,this.lastId)&&this.right===e&&xv(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(),F_(e.deleteSet,this.id.client,this.id.clock,this.length),Vv(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw lg();this.content.gc(e),t?Zre(e,this,new Uy(this.id,this.length)):this.content=new Gy(this.length)}write(e,t){let n=t>0?Sv(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=Cv(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===bv?(e.writeParentInfo(!1),e.writeLeftID(t)):lg();i!==null&&e.writeString(i)}this.content.write(e,t)}};const ib=(e,t)=>Qie[t&31](e),Qie=[()=>{lg()},Nie,Rie,Mie,Vie,Fie,Iie,Xie,Bie,Pie,()=>{lg()}];var ab=class extends Hy{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){lg()}write(e,t){e.writeInfo(10),Vh(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const ob=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},sb=`__ $YJS$ __`;ob[sb]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),ob[sb]=!0;const $ie=/[\uD800-\uDBFF]/,eae=/[\uDC00-\uDFFF]/,tae=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&$ie.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&&eae.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},nae=e=>{let t=ju(`sha256`);return t.update(e),t.digest()},rae=new Hn(`y-sync`);new Hn(`y-undo`),new Hn(`yjs-cursor`);const iae=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},aae=e=>s_(iae(nae(l_(e)))),oae=()=>({mapping:new Map,isOMark:new Map}),cb=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!M_(t.ds,e.id),sae=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof By)return lb(e,t,n,r,i,a);throw cg()}return o},lb=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof By){let s=sae(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Ly&&!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=cae(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):pie(e,new Tv(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(cb(e._item,r)?cb(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=gb(s),l=xb(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}},cae=(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,xb(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},lae=(e,t)=>{let n=new Vy,r=e.map(e=>({insert:e.text,attributes:Sb(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},uae=(e,t)=>{let n=new By(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=Sb(e.marks||[],t);for(let e in r)n.setAttribute(hb+e,{...r[e]});return n.insert(0,pb(e).map(e=>ub(e,t))),t.mapping.set(n,e),n},ub=(e,t)=>e instanceof Array?lae(e,t):uae(e,t),db=e=>typeof e==`object`&&!!e,fb=(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||db(o)&&db(s)&&fb(o,s)}return r},pb=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},mb=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&zg(e.attributes||{}).length===t[n].marks.length&&Ug(e.attributes,(e,r)=>{let i=bb(r),a=t[n].marks;return a.find(e=>e.type.name===i)?fb(e,a.find(e=>e.type.name===i)?.attrs):!1}))},hb=`ymark:`,gb=e=>{let t={},n={};for(let r in e)r.startsWith(hb)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},dae=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=bb(n),i=t.find(e=>e.type.name===r);return i?fb(e[n],i.attrs):!1}):!1},_b=(e,t)=>{if(e instanceof By&&!(t instanceof Array)&&wb(e,t)){let n=pb(t),r=gb(e.getAttributes());return e._length===n.length&&dae(r.marks,t.marks)&&fb(r.plain,t.attrs)&&e.toArray().every((e,t)=>_b(e,n[t]))}return e instanceof Vy&&t instanceof Array&&mb(e,t)},vb=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),yb=(e,t,n)=>{let r=e.toArray(),i=pb(t),a=i.length,o=r.length,s=vh(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(vb(n.mapping.get(e),t))u=!0;else if(!_b(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(vb(n.mapping.get(e),t))u=!0;else if(!_b(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},fae=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof Zy?t+=n.content.str:n.content instanceof Yy&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},pae=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=fae(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,Sb(e.marks,n))})),{insert:o,remove:s,index:c}=tae(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})))},mae=/(.*)(--[a-zA-Z0-9+/=]{8})$/,bb=e=>mae.exec(e)?.[1]??e,xb=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(bb(r),e[r]));return n},Sb=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=sh(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${aae(e.toJSON())}`:e.type.name]=e.attrs}}),n},Cb=(e,t,n,r)=>{if(t instanceof By&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof By){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(hb)&&t.removeAttribute(n);let a=Sb(n.marks||[],r);for(let n in a){let r=e[hb+n];(r===void 0||!fb(r,a[n]))&&t.setAttribute(hb+n,{...a[n]})}for(let n in e)n.startsWith(hb)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=pb(n),a=i.length,o=t.toArray(),s=o.length,c=vh(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!vb(r.mapping.get(e),t))if(_b(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(!vb(r.mapping.get(e),t))if(_b(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 Vy&&c instanceof Array)mb(n,c)||pae(n,c,r),l+=1;else{let i=n instanceof By&&wb(n,c),a=d instanceof By&&wb(d,f);if(i&&a){let e=yb(n,c,r),t=yb(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Cb(e,n,c,r),l+=1):a?(Cb(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[ub(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Vy?(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(ub(i[t],r));t.insert(l,e)}},rae)},wb=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,hae=(e,t)=>{let n=e.toArray().map(e=>lb(e,t,oae())).filter(e=>e!==null);return et.fromArray(n)},Tb=(e,t)=>t.topNodeType.create(null,hae(e,t));function Eb(e,t,n,r){let{body:i}=Mo(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Qo(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Jo.parseWithFallback(i,Db(n)))}function Db(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Ob(e){return Jo.serialize(Tb(e,qo).toJSON())}function kb(e,t,n,r,i,a){let o=Ob(r),s=Jo.serialize(n),{body:c}=Mo(e.baselineFullMd),l=Jo.serialize(Jo.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:pn(i,t).md})}function Ab(e,t,n,r,i,a){Qo(`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=Eb(e,t,r,i),l=qo.nodeFromJSON(c),u=a?Ob(n):void 0;if(s!==t&&St(o,s,t),Cb(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=Mo(a.baselineFullMd);kb(a,u,c,n,e,Db(r))}})}function jb(e,t,n,r,i){Qo(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=Eb(e,t,n,r),c=qo.nodeFromJSON(s),l=i?Ob(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Cb(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=Mo(i.baselineFullMd);kb(i,l,s,a,e,Db(n))}})}function gae(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=Mo(e.getText(`source`).toString()),o=Db(t),s=Jo.parseWithFallback(a,o),c=qo.nodeFromJSON(s),l=n?Jo.serialize(Tb(r,qo).toJSON()):void 0;if(Cb(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Jo.serialize(Tb(r,qo).toJSON()),t=Jo.serialize(s),{body:a}=Mo(n.baselineFullMd),c=Jo.serialize(Jo.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:pn(i,l).md})}}const _ae=I(`loss-capture`),Mb=`detector-trip`,Nb=`backstop-trip`,Pb=`checkpoint-write`;N({ts:P(),schemaVersion:P(),seq:P(),event:F(),docName:F(),writerId:F().nullable(),site:F().optional(),direction:F().optional(),lostLen:P().optional(),digest:F().optional(),checkpointSha:F().optional()});const Fb=[`.ok`,`local`,`loss-capture`];function vae(e){return R(e,...Fb,`loss-current.jsonl`)}function yae(e){return R(e,...Fb,`loss-prev.jsonl`)}var bae=class{#e;#t;#n=new Map;constructor(e){this.#e=new Is({currentPath:vae(e.projectDir),previousPath:yae(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=>{_ae.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const Ib=I(`checkpoint-chain`);async function Lb(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw Ib.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())}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.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;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
25
25
  `);this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new ZE(`spawn-failed`,`agent process has no stdio`);let s=zre(ute.toWeb(o.stdin),ku.toWeb(o.stdout)),c=Ym({name:`open-knowledge`}).onRequest(bm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(bm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(bm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(bm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(bm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(bm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(bm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(bm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(bm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.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 l;try{l=await c.agent.request(bm.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new ZE(`spawn-failed`,`initialize failed: ${sD(t)}`)}return e.closed?null:(e.lastInit=l,{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){try{return await KT(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof MT)||n.code!==`command-not-found`)throw n;let r=await this.retryWithLoginShellPath(t);if(r!==null)return r;if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=dE(t.kind);if(!bE(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=BT(t,a);return await KT(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(JT(t.env)===JT(e.env))return null;try{await KT(t)}catch(t){if(!(t instanceof MT))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||YT(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:VT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await DE(t,this.opts.log,n);let r=await wE(t,n).catch(()=>null);if(r!==null)return r;let i=(await AE(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new MT(`command-not-found`,aD(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=fE(t).displayName;throw new MT(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=fE(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&&jE(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 OE(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:tT,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Lt,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=Wd[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 MT||t instanceof ZE?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:uD(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)&&(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 openSession(e,t,n,r){let i=await this.buildMcpServers(e,n);try{let n=await t.agent.request(bm.agent.session.new,{cwd:e.cwd,mcpServers:i});e.sessionId=n.sessionId,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){let r=dD(cD(t),uD(e));return oD(t)?this.emitStatus(e,`auth_required`,`sign in required: ${sD(t)}`,{reason:`auth-required`,agentMessage:sD(t),machineDetail:r,authMethods:fD(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${sD(t)}`,{reason:`session-setup`,agentMessage:sD(t),machineDetail:r}),await this.teardownFailedAgent(e)),!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.setPresence(e,`idle`),this.emitStatus(e,`ready`),!0)}async resumeThread(e,t){if(this.destroyed)throw new ZE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new ZE(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new ZE(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new ZE(`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 ZE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new ZE(`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 ZE(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new ZE(`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(bm.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(bm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new ZE(`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(t){throw await this.abortResume(n),t instanceof ZE?t:t instanceof MT?new ZE(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new ZE(`resume-unsupported`,`couldn't resume the previous session: ${sD(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new ZE(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new ZE(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new ZE(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new ZE(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new ZE(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{jT();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new ZE(`spawn-failed`,n)}if(t.closed)throw new ZE(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new ZE(`spawn-failed`,lD(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new ZE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new ZE(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new ZE(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new ZE(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new ZE(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new ZE(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0;try{this.emitStatus(n,`installing`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw $E();let t=e instanceof QE?`the sign-in didn't complete in time — try again`:sD(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:dD(cD(e),uD(n)),authMethods:fD(i.authMethods)}),new ZE(`not-ready`,t)}if(n.closed)throw new ZE(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw $E();if(!await this.openSession(n,r,i,n.launchSettings))throw new ZE(`not-ready`,lD(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new QE),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(bm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}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 aE(t,{graceMs:XE}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(th(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 ZE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new ZE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new ZE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new ZE(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new ZE(`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})}steerPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new ZE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new ZE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new ZE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new ZE(`not-ready`,`thread has no live agent session`);if(!n.turnActive){this.dispatchPrompt(n,t,{echo:!0});return}this.clearSteer(n),n.info.steer={content:t,ts:Date.now()},n.info.lastActivityAt=Date.now(),this.emitInfo(n);let r=setTimeout(()=>this.demoteStalledSteer(n),this.steerStallMs);r.unref?.(),n.steerStallTimer=r,this.cancelTurn(n,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;t===void 0||e.closed||!e.turnActive||(e.info.steer=void 0,e.info.queue=[{id:crypto.randomUUID(),content:t.content,ts:t.ts},...e.info.queue??[]],this.emitInfo(e))}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??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=KE(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 ZE(`not-ready`,`the thread is closing`);let r=GE(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 ZE(`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(bm.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.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,{echo:!0});return}}this.emitStatus(e,`ready`),this.setPresence(e,`idle`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.setPresence(e,`idle`),this.drainIfIdle(e);return}this.emitStatus(e,`error`,`prompt failed: ${sD(t)}`,{reason:`prompt`,agentMessage:sD(t),machineDetail:dD(cD(t),uD(e))}),this.setPresence(e,`idle`)}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(bm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new ZE(`not-ready`,`thread has no live agent session`);n.conn.agent.request(bm.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 ZE(`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(bm.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||!iD(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(bm.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(bm.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`&&iD(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(bm.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.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await aE(r,{graceMs:t?.killGraceMs??YE})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(th(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){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 ZE(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new ZE(`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:XE})))}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:aT(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await Tu(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await Tu(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=Vw(t.dc.document);Bw(t.dc.document,n,`replace`,i,void 0,Rw(t));let a=nt(r,Vw(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(L(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return nD(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new ZE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&uT(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>JE){let t=e.events.length-JE;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,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await aE(t,{graceMs:YE})}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,steer:n,...r}=e.info;return{version:1,info:r,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=oi(e.info.agent.id),a=ei[i]??la(e.agentSessionId);r.setPresence(th(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 nD(e,t,n){let r=await Du(e),i=Xl(Yl(t)?t:B(r,t)),a=i,o=``;for(;;)try{let e=await Du(a),i=o===``?e:R(e,o),s=z(r,i);if(s===``||s.startsWith(`..`)||Yl(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(Ql).join(`/`),t=s.split(Ql).join(`/`);!Kx(e)&&!qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Ql).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=L(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):R(a.slice(t.length+1),o),a=t}}function rD(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function iD(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 aD(e){let t=fE(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 oD(e){return typeof e==`object`&&!!e&&e.code===-32e3}function sD(e){return e instanceof Error?e.message:String(e)}function cD(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function lD(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function uD(e){let t=e.stderrTail.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=Vw(t.dc.document);Bw(t.dc.document,n,`replace`,i,void 0,Rw(t));let a=nt(r,Vw(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-BLumSmkJ.mjs`);await e(L(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return nD(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new ZE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&uT(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>JE){let t=e.events.length-JE;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,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await aE(t,{graceMs:YE})}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,steer:n,...r}=e.info;return{version:1,info:r,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=oi(e.info.agent.id),a=ei[i]??la(e.agentSessionId);r.setPresence(th(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 nD(e,t,n){let r=await Du(e),i=Xl(Yl(t)?t:B(r,t)),a=i,o=``;for(;;)try{let e=await Du(a),i=o===``?e:R(e,o),s=z(r,i);if(s===``||s.startsWith(`..`)||Yl(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(Ql).join(`/`),t=s.split(Ql).join(`/`);!Kx(e)&&!qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Ql).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=L(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):R(a.slice(t.length+1),o),a=t}}function rD(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0}}function iD(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 aD(e){let t=fE(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 oD(e){return typeof e==`object`&&!!e&&e.code===-32e3}function sD(e){return e instanceof Error?e.message:String(e)}function cD(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function lD(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function uD(e){let t=e.stderrTail.join(`
28
28
  `);return t===``?void 0:t}function dD(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
29
29
  `);return t===``?void 0:t}function fD(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}const pD=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`steer`,`queue_edit`,`queue_hold`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`retry`,`authenticate`,`delete`,`list`]);function mD(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`||!pD.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`steer`:return!r(`threadId`)||!r(`reqId`)||!r(`content`)?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)||n.reqId!==void 0&&!r(`reqId`)?null:n;case`queue_hold`:return!r(`threadId`)||!r(`id`)||typeof n.held!=`boolean`?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`retry`:return!r(`threadId`)||!r(`reqId`)?null:n;case`authenticate`:return!r(`threadId`)||!r(`reqId`)||!r(`methodId`)?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function hD(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(gD(e,t,n));e.on(`message`,e=>{let s=mD(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`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});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`steer`:t.steerPrompt(s.threadId,s.content);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);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 ZE?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 ZE)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 gD(e,t,n){return{op:`error`,code:e,message:t,...n}}var _D=class{hocuspocus;log=I(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){nh(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){nh(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(Ti);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),vD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function vD(e){return e?.awareness??null}var yD=class{hocuspocus;log=I(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!nh(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(!nh(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(!nh(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(!nh(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 Roe(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(Ti);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),bD(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function bD(e){return e?.awareness??null}var xD=class extends Error{};const SD=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],CD=1024*1024;async function wD(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 xD(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new xD(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new xD(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new xD(`Website skill fetch exceeded 5 redirects: ${t}`)}function TD(e){let t;try{t=new URL(e)}catch{throw new xD(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new xD(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new xD(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function ED(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function DD(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`||!ED(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&ED(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function OD(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function kD(e,t,n){let r=[];for(let i of SD){let a=new URL(i,e).href;try{let o=await wD(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)>CD){r.push(`${i}: index exceeds ${CD} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=DD(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 xD(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function AD(e,t={}){let{skills:n}=t.index??await jD(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function jD(e,t={}){let n=TD(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new xD(`No fetch implementation available.`);return kD(n,r,t.timeoutMs??15e3)}async function MD(e,t={}){if(!ED(e.skill)||e.skill.includes(`/`))throw new xD(`Invalid website skill name: ${e.skill}`);let n=TD(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new xD(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await kD(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new xD(`Website skill index does not contain ${e.skill}`);let c=su(R(xu(),`ok-skill-site-`)),l=R(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await wD(r,OD(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new xD(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new xD(`Website skill file exceeds ${$t} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new xD(`Website skill file exceeds ${$t} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new xD(`Website skill bundle exceeds ${sn} bytes.`);let d=R(l,...e.split(`/`));ou(L(d),{recursive:!0}),gu(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:()=>fu(c,{recursive:!0,force:!0})}}catch(t){throw fu(c,{recursive:!0,force:!0}),t instanceof xD?t:new xD(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const ND=Ru(Vl),PD=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,FD=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function ID(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 FD.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=PD.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function LD(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 RD(e,t={}){if(e.kind===`well-known`)return MD(e,t);if(e.kind===`local`){let t=B(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!V(t))throw new xD(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!FD.some(t=>t.test(e.url)))throw new xD(`Unsupported git transport: ${e.url}`);let n=su(R(xu(),`ok-skill-import-`));try{await ND(`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){fu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new xD(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Hl(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?B(n,e.subpath):n,a=z(n,i);if(a.startsWith(`..`)||Yl(a))throw fu(n,{recursive:!0,force:!0}),new xD(`subpath escapes the clone: ${e.subpath}`);if(!V(i))throw fu(n,{recursive:!0,force:!0}),new xD(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>fu(n,{recursive:!0,force:!0})}}const zD=[`.ok`,`skills-lock.json`],BD=ce({source:F(),pluginProvider:F().optional(),skill:F().optional(),ref:F().optional(),contentHash:F(),files:M(F()).optional(),localHash:F().optional(),baselineRef:F().optional(),publisher:F().optional(),importedAt:i(),autoUpdate:k().optional()}),VD=ce({schema:j(1),skills:O(F(),BD).default({})});function HD(){return{schema:1,skills:{}}}function UD(e){let t;try{t=JSON.parse(e)}catch{return null}let n=VD.safeParse(t);return n.success?n.data:null}function WD(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const GD=new Set(Object.values(ct));function KD(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?qD(e,t,n):!GD.has(e)||r?.selfIdentifiesAsPack!==!0?null:qD(e,t,n)}function qD(e,t,n){return{source:Jn,skill:e,contentHash:t,importedAt:n}}function JD(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function YD(e,t){let n=t,r=``,{frontmatter:i}=Mo(e);if(i!==``){let{map:e}=Ue(Qr(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 XD=new Set([`.git`,`node_modules`]),ZD=new Set([...XD,`scripts`,`references`]);function QD(e){let t=[],n=r=>{for(let i of lu(r,{withFileTypes:!0})){let a=R(r,i.name);if(i.isDirectory()){XD.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=z(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=H(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 $D(e){let t=R(e,`SKILL.md`);return V(t)?YD(H(t,`utf-8`),Kl(e)):null}function eO(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=V(R(e,`SKILL.md`))?mu(R(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 ${$t}.`;if(n>67108864)return`Skill exceeds ${sn} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=lu(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=R(o,c.name);if(c.isDirectory()){XD.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=z(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=mu(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${$t}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${sn} 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 tO(e){let t=R(e,`SKILL.md`);if(!V(t))return null;let n=H(t,`utf-8`),{name:r,description:i}=YD(n,Kl(e)),a=QD(e),o=ju(`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(`
30
30
  `);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function nO(e){if(V(R(e,`SKILL.md`)))return[{name:Kl(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(V(R(e,`SKILL.md`))){t.push({name:Kl(e),dir:e});return}let a;try{a=lu(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!ZD.has(t.name)&&r(R(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function rO(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:Rn(i),source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:Oo(r)})}return n}const iO={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&#x27;":`'`,"&apos;":`'`};function aO(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>iO[e]??e)}function oO(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=aO(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 sO(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:Rn(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:Oo(r)})}return n}function cO(e){return e.trim().toLowerCase()}function lO(e){return e.split(`/`).filter(Boolean).pop()??e}function uO(e){let t=Xr(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=LD(e);if(!n)return null;let r=Xr(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function dO(e,t,n={}){let r=uO(e);if(r){let e=t??r.skill;if(!e)throw new xD(`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=LD(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new xD(`No fetch implementation available.`);let o=t??i.skill,s=cO(o),c=cO(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 xD(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof xD?e:new xD(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=rO(l).find(e=>{if((e.publisher?cO(e.publisher):``)!==c)return!1;let t=cO(e.name),n=cO(lO(e.id));return t===s||n===s});if(!u)throw new xD(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=Xr(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:ID(u.source);if(!f||f.kind===`local`)throw new xD(`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 fO=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function pO(e){let t=fO.indexOf(e);return t===-1?fO.length:t}function mO(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=pO(e.editor)-pO(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 hO(e){if(!V(e))return[];try{return lu(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>R(e.parentPath,e.name)).sort()}catch{return[]}}function gO(e,t,n,r){let i=R(e,`SKILL.md`);if(!V(i))return null;let a=Kl(e),o=a,s=``;try{({name:o,description:s}=YD(H(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:hO(R(e,`scripts`)),references:hO(R(e,`references`)),provenance:n,inert:r}}function _O(e){if(!V(e))return[];try{return lu(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function vO(e){let t=e=>{try{return mu(e).isDirectory()}catch{return!1}};return{commands:t(R(e,`commands`)),hooks:t(R(e,`hooks`)),mcp:V(R(e,`.mcp.json`))}}const yO={commands:!1,hooks:!1,mcp:!1};function bO(e,t){let n=[];for(let r of _O(e)){let i=gO(R(e,r),t,{},yO);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function xO(e){try{return lu(e).length>0}catch{return!1}}function SO(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=lu(e,{withFileTypes:!0})}catch{return}if(V(R(e,`SKILL.md`))||V(R(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(R(e,t.name),r+1)};return n(R(e,`skills`),0),[...t].sort()}function CO(e){return{commands:xO(R(e,`commands`)),hooks:xO(R(e,`hooks`))||V(R(e,`hooks.json`)),mcp:V(R(e,`.mcp.json`)),agents:xO(R(e,`agents`))}}function wO(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function TO(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!V(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 EO(e){let t=R(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(H(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function DO(e,t){let n=R(e,`installed_plugins.json`);if(!V(n))return[];let r;try{r=JSON.parse(H(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}=wO(e);for(let e of TO(n)){let n=e.installPath,o=vO(n),s=EO(n),c=R(n,`skills`),l=[];for(let n of _O(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=gO(R(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 OO=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,kO=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,AO=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function jO(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function MO(e){let t=kO.exec(jO(e));if(!t)return null;try{let e=H(`${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 NO(e,t){let n=B(e);try{mu(n).isDirectory()||(n=L(n))}catch{return null}let r=B(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(H(R(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=L(n)}return null}function PO(e){let t=jO(e),n=OO.exec(t);if(n){let t=NO(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=AO.exec(t);if(!r)return null;let i=NO(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function FO(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function IO(e){let t=jO(e),n=OO.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=lu(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=FO(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return V(c)?c:e}function LO(e,t){for(let n of t)try{let t=JSON.parse(H(R(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 RO(e){let t=LO(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(H(R(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 zO={id:`claude`,homes:e=>[{harness:`claude`,dir:R(e,`.claude`,`plugins`)}],enumerate:DO,inspectSource:PO,repositoryUrl:MO,resolveUpdateSource:IO,detectDir:RO};function BO(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=LO(e,t);return n?{...n,setupSupported:!1}:null}}}function VO(e,t){try{return JSON.parse(H(R(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const HO=[zO,BO(`codex`,[`.codex-plugin/plugin.json`]),BO(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=LO(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!VO(e,`plugin.json`))return null;let n=LO(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function UO(e){return HO.find(t=>t.id===e)}function WO(e){if(e===void 0)return HO;let t=UO(e);return t?[t]:[]}function GO(e){return HO.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function KO(e,t,n=e){let r=UO(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 qO(e,t){for(let n of WO(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 JO(e){for(let t of HO){let n=t.detectDir(e);if(!n)continue;let r=SO(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:CO(e),setupSupported:n.setupSupported}}return null}function YO(e,t){for(let n of WO(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function XO(e,t){for(let n of WO(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function ZO(e=vu()){let t=dr.flatMap(t=>{let n=Ht[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:R(e,...n.split(`/`))}]});return[...GO(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:R(e,`.agents`,`skills`)}]}function QO(e){return dr.flatMap(t=>{let n=Fa[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:R(e,...n.split(`/`))}]})}function $O(e){return Object.keys(e.provenance).length>0}function ek(e){return e.provenance.plugin!==void 0}function tk(e,t){if(ek(e)!==ek(t))return ek(e)?e:t;if($O(e)!==$O(t))return $O(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function nk(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 rk(e){try{return tO(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function ik(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${rk(n)}`,i=t.get(r);i?(i.winner=tk(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})=>nk(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 ak(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 ok(e={}){let t=[];for(let n of ZO(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...KO(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...bO(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(...sk(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>mo(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:ik(n.flatMap(e=>e.skills)),packs:ak(n)}}function sk(e){let t=uk(B(e,`.ok`,`skills`)),n=[];for(let r of QO(e))try{for(let i of bO(r.dir,r.harness)){let r=i.skills.filter(e=>!lk(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>ck(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 ck(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function lk(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=uk(e.home);return n===t||n.startsWith(t+Ql)}function uk(e){try{return U(e)}catch{return B(e)}}function dk(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 fk=[`skillId`,`source`,`installs`];function pk(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*mk(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(!fk.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 pk(r)}}}}function hk(e){let t=dk(e),n=[];for(let e of mk(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 gk(e){let t=new Map;for(let n of hk(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:Oo(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function _k(e,t){return`${e}/${t}`}function vk(e){if(e.preferredSource===!0)return-1;let t=fO.indexOf(e.editor);return t===-1?fO.length:t}function yk(e){let t=mO(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=_k(e.scope,e.name),o=vk(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 bk=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}})),xk=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})),Sk=n(((t,n)=>{let{Readable:r,Writable:i}=e(`stream`),a=xk(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=bk(),d=Buffer.from(`\r
@@ -1214,7 +1214,7 @@ tags: [lore, history]
1214
1214
  `:``)+t).md;Ab(b.dc.document,i,`agent`,void 0,S),bS(`mcp-write`),ee=!0}T=!0},b.origin)})}finally{O?.touchMode(l,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}K(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(T&&te.length>0){if(_M(c,l,u,d,void 0,Cn({clientName:f,clientVersion:p,label:m}),y),Yb(),Mn(_),ee){let e=await wt(c);if(e?.kind===`failure`){Et(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){Dt(r,`frontmatter-patch`);return}}Ct(c,`frontmatter-patch`)}ne?.setFocus(l,{agentName:u,currentDoc:c,writeKind:`write`,ts:Date.now()}),re?.();let E=yt(c),D=xt();D===0&&kZ().add(1,{"shadow.writer":`agent`,"agent.type":rh(f)});let k=Ot(x);Ht(c,b.dc.document.getText(`source`).toString());let A=await Mt();A.add(c);let ie=GL(b.dc.document.getText(`source`).toString(),c,A,Vt);J(r,200,ree,{timestamp:C,subscriberCount:E,systemSubscriberCount:D,appliedKeys:te,...v?{summary:v}:{},...k?{warning:k,warnings:[k]}:{},brokenLinks:ie},{handler:`frontmatter-patch`})}catch(e){if(e instanceof Xw){K(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e,requestId:rS(n)},`[frontmatter-patch] handler failed`),K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Zn(e){let t=e.getMap(`lifecycle`),n=t.get(`status`);if(typeof n!=`string`||n.length===0)return null;let r=t.get(`reason`);return{status:n,reason:typeof r==`string`?r:``}}let Qn=q(Yn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!gQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let r=vt(n);if(Kx(r)||qx(r)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`document-read`});return}let i=a.documents.get(r);if(i){J(t,200,Qe,{docName:r,content:i.getText(`source`).toString(),lifecycle:Zn(i)},{handler:`document-read`});return}if(!V($Z(s,`file`,r))){K(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${r}.`,{handler:`document-read`});return}let o=await a.openDirectConnection(r);try{let e=o.document;if(!e){K(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}J(t,200,Qe,{docName:r,content:e.getText(`source`).toString(),lifecycle:Zn(e)},{handler:`document-read`})}finally{await o.disconnect()}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),$n=q(Yn,async(e,t)=>{try{ge&&await ge.catch(e=>{X.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=n.searchParams.get(`dir`),i=n.searchParams.get(`showAll`)===`true`,a=n.searchParams.get(`showOk`)===`true`,o=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{HZ(s,r)}catch{K(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&fe&&lpe(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let n=cS(t,`document-list`),i=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=GZ(),n=YZ({contentDir:s,contentFilter:fe,dirFilter:r,maxEntries:t,maxDepth:o,showOk:a,signal:e.signal}),c=0,l=await n.next();for(;!l.done;)await i(`${JSON.stringify(l.value)}\n`),c+=1,l=await n.next();let{truncated:u}=l.value;u&&X.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:u,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):X.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(i&&fe){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=Ie.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=GZ(),{truncated:i}=await upe({contentDir:s,contentFilter:fe,dirFilter:r,documents:e,maxEntries:n,maxDepth:o,showOk:a,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),i&&X.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:i}})();n={promise:i,controller:t,waiters:0};let c=n;Ie.set(e,c),i.finally(()=>{Ie.get(e)===c&&Ie.delete(e)})}let i=n;i.waiters+=1;let c=!1,l=()=>{t.writableEnded||c||(c=!0,--i.waiters,i.waiters<=0&&(i.controller.abort(),Ie.get(e)===i&&Ie.delete(e)))};t.on(`close`,l);try{let{documents:e,truncated:n}=await i.promise;if(c)return;J(t,200,Bn,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,l)}return}let c=l(),u=f(),d=h?.()??new Map,p=[];for(let[e,t]of d)r&&!e.startsWith(`${r}/`)&&e!==r||p.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let m=[];try{let e=Ze(c);ze?.signature!==e&&(ze={signature:e,assets:zse({contentDir:s,fileIndex:c,readMarkdown:e=>{try{return H(e,`utf-8`)}catch{return null}},isExcluded:fe?e=>fe.isPathIgnored(e):void 0})}),m=ze?.assets??[]}catch(e){ze=null,X.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let g=new Set;for(let e of m)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(g.add(e.path),p.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of u){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=Vx(e);p.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(r&&!i.startsWith(`${r}/`)&&i!==r)continue;let a=Vk(z(s,t.canonicalPath));p.push({kind:`document`,docName:i,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}continue}if((!r||e===r||e.startsWith(`${r}/`))&&!g.has(e)){let n=UZ(e);p.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let n of t.aliases){if(!(!r||n===r||n.startsWith(`${r}/`))||g.has(n))continue;let i=Vk(z(s,t.canonicalPath)),a=UZ(n);p.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}}let _=v?.()??new Map;if(_.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of _){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,r]of t){let t=d.get(n),i=t?Vk(z(s,t.canonicalPath)):n;for(let a of r)e(a)&&p.push({kind:`folder`,path:a,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:i})}let n=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of d)n(e,n=>{p.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Vk(z(s,t.canonicalPath))})});for(let[e,t]of u)n(e,n=>{let r=Vk(z(s,t.canonicalPath));if(t.kind===`markdown`)p.push({kind:`document`,docName:n,docExt:Vx(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=UZ(n);p.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}p.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),J(t,200,Bn,{documents:p},{handler:`document-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),er=q(Yn,async(e,t)=>{try{let e=zd(j??s),n=ok({projectDir:e}),r=new Set(XI(s).map(e=>e.name)),i=new Set(ZI(Zo).map(e=>e.name));J(t,200,Le,{...n,skills:n.skills.filter(t=>mo(t.provenance,e)&&!(t.provenance.scope===`project`?r.has(t.name):i.has(t.name))).map(e=>dee(e.provenance,e.home,j??s)?{...e,outsideProject:!0}:e)},{handler:`skills-installed`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),tr=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){K(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let a={};if(r!==null){let e=r.trim();if(e!==``&&!gQ(e)){K(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}a=Object.fromEntries(await at.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&gQ(e));a=Object.fromEntries(await at.countThreads({docNames:e}))}J(t,200,Co,{counts:a},{handler:`comment-counts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),nr=q(Yn,async(e,t)=>{if(!E){K(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!mR(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}J(t,200,Wee,{orphans:(await E.getOrphans([...l().keys()],n)).map(e=>({docName:e,title:ot(e)}))},{handler:`orphans`})}catch(e){zt(t,e,{handler:`orphans`,failureTitle:`Failed to read orphan pages.`})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),ir=q(Yn,async(e,t)=>{if(!E){K(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20,a=await Mt();J(t,200,Oee,{hubs:(await E.getHubs(i)).map(e=>({docName:e.docName,title:dt(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){zt(t,e,{handler:`hubs`,failureTitle:`Failed to read hub pages.`})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),or=q(Ft,async(n,r,i)=>{try{let{find:n,replace:c,offset:l}=i,u=QZ(i.docName,r,`agent-patch`);if(u===null)return;let d=vt(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=xn(i);if(epe(n)){jZ().add(1,{result:`rejected`}),K(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(Kx(d)||qx(d)){K(r,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=Bk(i.summary),y=await o.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),b=MR(t,a,d,s,e.resolveEmbed,oe?.()),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,S;{let{frontmatter:e,body:t}=Mo(y.dc.document.getText(`source`).toString()),r=lo(e,t),i=l==null?r.indexOf(n):r.slice(l,l+n.length)===n?l:-1;if(i!==-1&&i>=e.length){let e=r.slice(0,i)+c+r.slice(i+n.length);S=await Iw(y.dc.document,Mo(e).body,`patch`,x)}}let C=new Date().toISOString(),w=!1,T=!1,ee=!1,te,E;try{let e=oi(h),t=ei[e]??la(m??f);if(O?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),E=Rk(y.dc.document.getText(`source`),f,y.origin,m,h),y.dc.document.transact(()=>{let{frontmatter:e,body:t}=Mo(y.dc.document.getText(`source`).toString()),r=lo(e,t),i=l==null?r.indexOf(n):r.slice(l,l+n.length)===n?l:-1;if(i===-1){l==null?w=!0:T=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:n.length,replaceLength:c.length,hadOffset:l!=null})),Zae();return}if(i<e.length){ee=!0;return}let{body:a}=Mo(r.slice(0,i)+c+r.slice(i+n.length)),o=Vw(y.dc.document);te=Bw(y.dc.document,a,`patch`,x,S,Rw(y));let s=nt(o,Vw(y.dc.document))??void 0;y.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${n.slice(0,50)}`,...s===void 0?{}:{changedBlocks:s}})},y.origin),te!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:te.intendedBytes,actualBytes:te.actualBytes,byteDelta:te.byteDelta,"agent.id":f,"agent.client_name":h})),!w&&!T&&!ee){let{stored:e}=Dn(v);_M(d,f,p,m,void 0,Cn({clientName:h,clientVersion:g,label:_}),e),Yb(),Mn(v),IZ(`agent-patch`,te)}}finally{E?.(),O?.touchMode(f,`idle`)}if(T){K(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(w){K(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ee){jZ().add(1,{result:`rejected`}),K(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let D=await wt(d);if(D?.kind===`failure`){Et(r,D.failure,`agent-patch`);return}if(D?.kind===`divergence`){Dt(r,`agent-patch`);return}Ct(d,`agent-patch`),ne?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),re?.();let k=yt(d),A=xt();A===0&&kZ().add(1,{"shadow.writer":`agent`,"agent.type":rh(h)});let{response:ie}=Dn(v),ae=y.dc.document.getText(`source`).toString();Ht(d,ae);let j=await hF(ae,d),se=await Mt();se.add(d);let ce=GL(ae,d,se,Vt),le=Ot(b),ue=te===void 0?void 0:hS(te),de=[...ue?[ue]:[],...le?[le]:[],...j??[],...await rl(y.dc.document.getText(`source`).toString(),d)];J(r,200,oee,{timestamp:C,subscriberCount:k,systemSubscriberCount:A,...ie?{summary:ie}:{},...ue?{warning:ue}:le?{warning:le}:{},...de.length>0?{warnings:de}:{},brokenLinks:ce},{handler:`agent-patch`})}catch(e){if(e instanceof dS){fS(r,e,`agent-patch`);return}if(e instanceof gS){vS(r,e,`agent-patch`);return}if(e instanceof Xw){K(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e,requestId:rS(n)},`[agent-patch] handler failed`),K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),sr=q(Pn,async(t,n,r)=>{try{let t=QZ(r.docName,n,`agent-undo`);if(t===null)return;let i=vt(t),{agentId:a,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=xn(r);if(Kx(i)||qx(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=r,p,m;if(r.scope===`count`?(p=`count`,m=r.count):p=r.scope===`session`||r.scope===`file`?`session`:`last`,!o.hasSession(i,f)){K(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await o.getSession(i,f),g=!1;try{let t=oi(l),n=ei[t]??la(c??a);O?.setPresence(a,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=Ww(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&_M(i,f,s,c,void 0,Cn({clientName:l,clientVersion:u,label:d}))}finally{O?.touchMode(a,`idle`)}if(g){let e=await wt(i);if(e?.kind===`failure`){Et(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){Dt(n,`agent-undo`);return}St(i,`agent-undo`)}ne?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),J(n,200,Lo,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof dS){fS(n,e,`agent-undo`);return}X.error({err:e,requestId:rS(t)},`[agent-undo] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),ur=q(Yn,async(e,t)=>{try{let n=eh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){K(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}J(t,200,wn,IC(o,n),{handler:`agent-activity`})}catch(n){X.error({err:n,requestId:rS(e)},`[agent-activity] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),dr=q(Yn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=eh(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){K(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){K(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!gQ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=vt(i);if(Kx(s)||qx(s)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!a||Number.isNaN(Number(a))){K(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(a);if(!Number.isInteger(c)||c<0){K(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=o.getLiveSession(s,r);if(!l){K(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){K(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=l.dc.document.getText(`source`),{diff:f,before:p,after:m}=NC(u.undoStack,c,d,s);J(t,200,eee,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){X.error({err:n,requestId:rS(e)},`[agent-burst-diff] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),pr=q(Yn,async(e,t)=>{try{await C?.(),J(t,200,hee,{},{handler:`test-flush-git`})}catch(n){X.error({err:n,requestId:rS(e)},`[test-flush-git] flush failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),hr=q(Yn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=vt(n.searchParams.get(`docName`)??`test-doc`),i;try{i=Uk(r,s)}catch(e){X.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await o.closeAll(r),a.closeConnections(r);let c=`onStoreDocument-${r}`;a.debouncer.isDebounced(c)&&await a.debouncer.executeNow(c);let l=a.documents.get(r);if(l&&await(me??a.unloadDocument.bind(a))(l),gu(i,``,`utf-8`),await E?.testOnly?.resetDocumentForTest(r),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=B(s,`.okignore`),t=a.documents.get(qi);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},IA)}V(e)&&gu(e,``,`utf-8`),fe&&await fe.rebuildIgnorePatterns()}catch(e){X.warn({err:e},`[test-reset] okignore reset partial failure`)}D?.(`files`),J(t,200,aee,{},{handler:`test-reset`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),Sr=q(Yn,async(e,t)=>{try{if(!E?.testOnly){K(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await E.testOnly.rescanBacklinksForTest(),J(t,200,fr,{},{handler:`test-rescan-backlinks`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),wr=q(Yn,async(e,t)=>{try{if(!y){K(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await y(),D?.(`files`),J(t,200,tee,{},{handler:`test-rescan-files`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Er=nZ({getCurrentBranch:T,contentRoot:te}),Dr=eZ(),kr=q(Ii,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=xn(n),o=S?.current;if(!o){K(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let s=/^[a-zA-Z0-9_-]+$/,c=[];if(Array.isArray(n.writers))try{c=n.writers.map(e=>{let t=e.id??`unknown`;if(!s.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){K(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let l=e===void 0?void 0:{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`},u=Bk(typeof n.summary==`string`?n.summary:void 0);J(t,200,ki,{checkpointRef:(await Er.saveCheckpoint(o,{explicitWriters:c,agentWriter:l,summary:u.kind===`value`?u.value:void 0})).checkpointRef},{handler:`save-version`})}catch(n){X.error({err:n,requestId:rS(e)},`[save-version] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),jr=q(Yn,async(e,t)=>{let n=S?.current;if(!n){K(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await C?.();let t=performance.now()-e;t>1e3&&X.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){X.warn({err:e},`[history] pre-read commit flush failed`)}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`folder`),o=r.searchParams.get(`branch`)??T?.()??`main`;if(!i&&a===null){K(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(o.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=Do(a,t,`folder`,`history`);if(!e)return;let i=Number(r.searchParams.get(`limit`)??`50`),s=Math.min(200,Number.isFinite(i)?i:50),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.max(0,Number.isFinite(c)?c:0),u=`folder\0${o}\0${e.folderRel}\0${s}\0${l}`,{promise:d,coalesced:f}=Re.run(u,()=>Qfe(n,e.folderRel,te??`.`,{branch:o,limit:s,offset:l}));f&&_Z(`folder`),J(t,200,xi,{...await d},{handler:`history`});return}let s=te??`.`,c=BZ(i,s);if(`error`in c){K(t,400,`urn:ok:error:invalid-request`,c.error,{handler:`history`});return}let l=Number(r.searchParams.get(`limit`)??`50`),u=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(l)?l:50),f=Number.isFinite(u)?u:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=r.searchParams.get(`includeAutoCheckpoints`)===`true`,_=`doc\0${o}\0${i}\0${d}\0${f}\0${p??``}\0${m??``}\0${h??``}\0${g?`1`:`0`}`,v=Date.now();try{let{promise:e,coalesced:r}=Re.run(_,()=>Zfe(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&_Z(`doc`);let a=await e,c=Date.now()-v;I(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),J(t,200,xi,{...a},{handler:`history`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function Rr(e,t,n){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=S?.current;if(!r){K(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,a=te??`.`,o=BZ(i,a);if(`error`in o){K(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=dx(r),c=T?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await rq(r,i,n,c,PK(r.gitDir),e=>VZ(e,a),RK());if(e===null){K(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let o=await s.raw(`show`,`${n}:${e}`),[l=``,u=``]=(await s.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);J(t,200,Nee,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let Br=q(He,async(t,n,r)=>{let i=sA(r,se);if(i.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=a.documents.get(r.docName);if(o&&lS(o)){fS(n,new dS({file:Ux(r.docName)}),`rollback`);return}let s=S?.current;if(!s){K(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=te??`.`,d=BZ(c,u);if(`error`in d){K(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=dx(s),p=Date.now();try{let t=PK(s.gitDir),r=RK(),o=await rq(s,c,l,T?.()??`main`,t,e=>VZ(e,u),r);if(o===null){K(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${o}`),m=new Date().toISOString();await Ex(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=a.documents.get(c);if(!h){K(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await qS(d,g),v;h.transact(()=>{jb(h,d,g,_),v=mS(h.getText(`source`).toString(),d,`rollback`)},RZ),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":i.kind,...i.kind===`agent`||i.kind===`principal`?{"actor.writer_id":i.writerId}:{}})),IZ(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:Bk(`Restored to ${e}`),r=Dn(n);y=t||!r.response?r.response:kn(r.response),_M(c,i.writerId,i.displayName,i.colorSeed,Ad(c,l),i.actor,r.stored),Yb(),Mn(n,!t);break}case`principal`:{let e=Dn(i.summary);y=e.response,_M(c,i.writerId,i.displayName,i.colorSeed,Ad(c,l),i.actor,e.stored),Mn(i.summary,!1);break}case`anonymous`:X.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(i.kind)}`)}NZ().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await wt(c);if(b?.kind===`failure`){Et(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){Dt(n,`rollback`);return}St(c,`rollback`);let x=Date.now()-p;I(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&ne?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:hS(v);J(n,200,$i,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){K(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Vr=q(Yn,async(e,t)=>{try{J(t,200,Je,ix(),{handler:`metrics-reconciliation`})}catch(n){X.error({err:n,requestId:rS(e)},`[metrics-reconciliation] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:n})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),Hr=q(Yn,async(e,t)=>{try{J(t,200,Bo,Nn(),{handler:`metrics-parse-health`})}catch(n){X.error({err:n,requestId:rS(e)},`[metrics-parse-health] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:n})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Ur=q(Yn,async(e,n)=>{try{ge&&await ge.catch(e=>{X.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=ee?.(),i=rR();J(n,200,cr,{serverInstanceId:c,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),Wr=N({agents:M(N({id:F(),name:F(),version:F(),description:F().optional(),license:F().optional(),iconUrl:F().optional(),website:F().optional(),source:we([`registry`,`custom`]),supported:k(),featured:k(),harness:N({cli:we([`claude`,`codex`,`cursor`,`gemini`,`opencode`,`pi`]),availability:we([`present`,`not-found`,`unknown`])}).optional()})),stale:k(),maxThreads:P()}),Jr=q(Yn,async(e,t)=>{if(le===void 0){K(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=qd(),{agents:n,stale:r}=await le.getCatalog(),i=await ue?.()??[],a=await de();J(t,200,Wr,{agents:[...n.map(t=>{let n=Mk[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:Ud.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))],stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function Yr(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=se?.()??null;if(!n){K(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}J(t,200,kt,n,{handler:`principal`})}async function Xr(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=O?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);J(t,200,Ln,{presence:r},{handler:`metrics-agent-presence`})}catch(n){X.error({err:n,requestId:rS(e)},`[metrics-agent-presence] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:n})}}async function Zr(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-effects`,extraHeaders:{Allow:`GET`}});return}let n;try{let e=[];for(let[t,r]of a.documents){if(Kx(t)||qx(t)||!r.share.has(`agent-effects`))continue;n=t;let i=r.getMap(`agent-effects`);if(i.size===0)continue;let a=[...i.values()].map(e=>{let t=0,n=0;for(let r of e.delta)typeof r.insert==`string`?t+=r.insert.length:r.insert!==void 0&&(t+=1),typeof r.delete==`number`&&(n+=r.delete);return{sessionId:e.sessionId,agentType:e.agent_type,ts:e.timestamp,insertedChars:t,deletedChars:n}}).sort((e,t)=>e.ts-t.ts);e.push({"doc.name":t,entries:a})}e.sort((e,t)=>e[`doc.name`].localeCompare(t[`doc.name`])),J(t,200,cee,{effects:e},{handler:`metrics-agent-effects`})}catch(e){X.error({err:e,"doc.name":n},`[metrics-agent-effects] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function $r(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{J(t,200,ar,{decisions:ZR().map(e=>({ts:e.ts,decision:e.decision,kind:e.kind,"doc.name":e.path,pathRole:e.pathRole}))},{handler:`metrics-watcher-recent`})}catch(n){X.error({err:n,requestId:rS(e)},`[metrics-watcher-recent] handler failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-watcher-recent`,cause:n})}}async function ti(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=SM.read();J(t,200,so,{entries:n,count:n.length,detection:gle(n[0])},{handler:`embed-detect`})}async function ni(e,t){if(!Wz(e.socket.remoteAddress)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=B(s),r=n,a=!0;try{r=U(n)}catch(e){let r=ic(e);if(r===`ENOENT`)X.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{X.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),K(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}J(t,200,Ir,{contentDir:r,pathSeparator:Ql,symlinkResolved:a},{handler:`workspace`})}let ri=vX({contentDir:s,isPathIgnored:e=>fe?.isPathIgnored(e)??!1,getAttachmentFolderPath:d}),ai={"missing-path":[400,`urn:ok:error:invalid-request`,`Missing asset path.`],"unsupported-type":[415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`],"not-found":[404,`urn:ok:error:asset-not-found`,`Asset not found.`],"invalid-path":[400,`urn:ok:error:invalid-request`,`Invalid asset path.`]},si=q(Yn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),r=ri.resolveServableAsset(n);if(!r.ok){let[e,n,i]=ai[r.reason];K(t,e,n,i,{handler:`asset`,...r.cause===void 0?{}:{cause:r.cause}});return}let{asset:i}=r,a={"Content-Type":i.contentType,"Content-Length":String(i.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":i.disposition,"Cache-Control":`no-store`};i.csp!==null&&(a[`Content-Security-Policy`]=i.csp);let o=i.canonicalPath;t.writeHead(200,a);try{await Iu(ru(o),t)}catch(e){X.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:n,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),ui=1048576,di=q(Yn,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),r=ri.resolveTextAsset(n);if(!r.ok){let[e,n,i]=ai[r.reason];K(t,e,n,i,{handler:`asset-text`,...r.cause===void 0?{}:{cause:r.cause}});return}if(r.size>ui){K(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${ui}-byte text-viewer cap.`,{handler:`asset-text`});return}let i=(await Tu(r.canonicalPath)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(i)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),fi=q(Yn,async(e,t)=>{try{if(!S?.current){J(t,200,_a,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=B(S.current.gitDir,`rescue`);if(V(r))try{let t=lu(r).filter(e=>Px(e));for(let i of t){let t=B(r,i),a=mu(t);if(e-a.mtimeMs>864e5){try{hu(t)}catch(e){X.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:Ix(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){X.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=T?.()??`main`,t=await Ox(S.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){X.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}J(t,200,_a,n,{handler:`rescue-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),hi=q(No,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!Px(r)){K(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(r.includes(`..`)||r.startsWith(`/`)||r.includes(`\0`)||r.includes(`\\`)){K(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=B(s),a=B(i,r);if(!Hk(a,i)){K(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=Ix(r);if(Kx(o)||qx(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(iR(r)||xa(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let c=typeof n.template==`string`?n.template.trim():``,l=``,u;if(c.length>0){if(!/^[A-Za-z0-9_-]+$/.test(c)){K(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,a=Dj(i,n),o=a.find(e=>e.name===c);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);K(t,400,`urn:ok:error:invalid-request`,`Template "${c}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let s=B(i,o.path),d;try{d=H(s,`utf-8`)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=Pr(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;l=oM(f,{date:cM(),user:p}),u=o.scope}let d=Ix(r),f=_i.createPage({fullPath:a,docName:d,initialContent:l});if(!f.ok){K(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:f.cause});return}switch(e.kind){case`agent`:case`principal`:_M(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}await Pt(d,l,`create-page`),D?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:c,templateScope:u,docName:d})),J(t,200,bee,{docName:d},{handler:`create-page`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),_i=bX({contentDir:s,resolveContentEntryPath:$Z,docNameForPath:e=>oQ(s,e),docNameToRelativePath:Ux,listManagedDocNamesUnderFolder:e=>mn(e),listAffectedDocNames:(e,t,n)=>dpe(e,t,n),getFileIndex:l,getConflictedFiles:()=>new Set(A?.()?.getConflicts().map(e=>e.file)??[]),isDocNameInLifecycleConflict:e=>{let t=a.documents.get(e);return t!==void 0&&lS(t)},captureAndCloseDocuments:Yt,markRecentlyRemoved:ve?e=>ve.setDeleted(e):void 0,mutateFileIndexDelete:p?({path:e,docName:t})=>p({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:Ye,upsertFolderIndexPathSegments:We,deleteDerivedDocumentsBestEffort:Bt,invalidateReferencedAssetsCache:et,signalFiles:()=>D?.(`files`),nextAvailableDuplicateDocName:e=>gpe(s,e),nextAvailableDuplicateFolderPath:e=>_pe(s,e),resolveDuplicateDocPath:(e,t)=>hpe(s,e,t),collectMarkdownCopies:e=>vpe(s,e),collectFolderPaths:e=>ype(s,e),contentFilter:fe??void 0,unmarkRecentlyRemoved:ve?e=>ve.delete(e):void 0,mutateFileIndexCreate:p?({path:e,docName:t,content:n})=>p({kind:`create`,path:e,docName:t,content:n}):void 0,recordDerivedDocumentBestEffort:Pt,recordDerivedMutationsBestEffort:Nt}),vi=q(zr,async(e,t,n)=>{try{if(sA(n,se).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!XZ(e)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(iR(e)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(fe?.isDirExcluded(e)){K(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!_i.createFolder(e).ok){K(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}J(t,200,uo,{path:e},{handler:`create-folder`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),yi=q(tt,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:r}=n,i=n.path,a=r===`file`?Ix(i):i;if(!XZ(i)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(iR(i)||r===`file`&&(Kx(a)||qx(a))||r===`folder`&&ZZ(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&sQ(s,i);let o=await _i.duplicatePath(r,i,a);if(!o.ok)switch(o.kind){case`not-found`:K(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:K(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return;case`conflict`:fS(t,new dS({file:o.file}),`duplicate-path`);return;case`destination-excluded`:K(t,400,`urn:ok:error:invalid-request`,r===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:K(t,409,`urn:ok:error:doc-already-exists`,`A ${r} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:o.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(o.kind)}`)}let{duplicatedPath:c,duplicatedDocNames:l}=o;switch(e.kind){case`agent`:case`principal`:for(let t of l)_M(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}D?.(`files`),J(t,200,vo,{kind:r,path:c,duplicatedDocNames:l},{handler:`duplicate-path`})}catch(e){if(e instanceof rQ){K(t,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let n=ppe(e);if(n){K(t,n.status,n.type,n.title,{handler:`duplicate-path`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),bi=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){K(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!gQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=it(n);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!V(r)){K(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}J(t,200,ht,{docName:n,headings:hQ(H(r,`utf-8`))},{handler:`page-headings`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),Ci=q(lee,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:r,fromPath:i,toPath:o}=n;if(!XZ(i)||!XZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(Kx(i)||Kx(o)||qx(i)||qx(o))){K(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(iR(i)||iR(o)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===o){J(t,200,oa,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=r===`asset`&&Px(i)&&Px(o)?`file`:r;if(c===`asset`){let n;try{n=Px(i)&&!Px(o)?await vn(i,o):await gn(i,o)}catch(e){if(e instanceof dS){fS(t,e,`rename-path`);return}let{status:n,type:r,error:i}=Jt(e);K(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&et();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${o}`;r=In(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{X.debug({kind:`asset`,fromPath:i,toPath:o,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(NZ().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),w)try{await w()}catch(e){X.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}J(t,200,oa,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&sQ(s,i);let l=c===`file`?[oQ(s,i)]:mn($Z(s,`folder`,i)),u=A?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let n=e,r=a.documents.get(n),i=Ux(n),o=r!==void 0&&lS(r),s=d.has(i);if(o||s){fS(t,new dS({file:i}),`rename-path`);return}}if(fe){let e=Px(i)?Jl(i):Vx(i);if(c===`file`?fe.isExcluded(Px(o)?o:`${o}${e}`):fe.isDirExcluded(o)){K(t,400,`urn:ok:error:invalid-request`,`Destination ${c===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await bn(i,o,c,f?{actor:f}:{})}catch(e){if(e instanceof cN){K(t,409,`urn:ok:error:doc-already-exists`,qt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){J(t,200,oa,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&et();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=In(e,`Renamed ${i} → ${o}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Md(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{X.debug({kind:r,fromPath:i,toPath:o,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),NZ().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),w)try{await w()}catch(e){X.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}J(t,200,oa,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=Jt(e);K(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Ti=q(To,async(e,t,n)=>{try{xn(n);let{kind:e,path:r}=n;if(!XZ(r)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?pn(r):{path:r,ambiguous:!1};if(i.ambiguous){K(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let a=i.path,o=e===`asset`&&Px(a)?`file`:e;if(o===`file`&&sQ(s,a),iR(a)){K(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=await _i.deletePath(o,a);if(!c.ok){c.kind===`not-found`?K(t,404,`urn:ok:error:doc-not-found`,`${o} does not exist.`,{handler:`delete-path`}):c.kind===`type-mismatch`?K(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${o}.`,{handler:`delete-path`}):fS(t,new dS({file:c.file}),`delete-path`);return}J(t,200,Un,{deletedDocNames:c.deletedDocNames},{handler:`delete-path`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ei=q(an,async(e,t,n)=>rs(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":_s(n.path),"ok.cleanup.path.role":Ss(n.path)}},async()=>{try{if(sA(n,se).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!XZ(r)){K(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&Px(r)?`file`:e,a=Ix(r);i===`file`&&sQ(s,r);let o=i===`folder`&&ZZ(r);if(i===`file`&&(Kx(a)||qx(a))||o||iR(r)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:c}=await _i.trashCleanup(i,r,a,`handleTrashCleanup`);J(t,200,fn,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Di=q(Yn,async(e,t)=>{try{let e=l(),n=[];for(let[t,r]of e){let e=Vx(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=H(B(s,`${t}${e}`),`utf-8`);i=xj(n,t),a=Cj(n)}catch(e){X.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:i,docExt:e,size:r.size,modified:r.modified,icon:a})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,lt,{pages:n},{handler:`pages`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0});async function Mi(e,t){if(e.method!==`POST`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await ape(e,j??s)}catch(e){if(e instanceof oL){K(t,sL(e.reason),e.reason,lL(e.reason),{handler:`upload-asset`,cause:e});return}K(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:i,sha:a,byteLength:o,parentDocName:c,placement:l}=n,u=()=>{if(V(i))try{hu(i)}catch{}},d=dA(Lee,{parentDocName:c,placement:l||void 0},t,{handler:`upload-asset`});if(!d.ok){u();return}let{parentDocName:f,placement:p}=d.value,{agentId:m,agentName:h}=xn(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(o===0){u(),K(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(f.includes(`\0`)||f.includes(`..`)||f.startsWith(`/`)){u(),K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let g=await ri.storeUpload({tempPath:i,sha:a,byteLength:o,filename:r,parentDocName:f,placement:p});if(g.ok){X.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:h,dedup:g.deduped,mime:g.mime,size:o,destPath:g.path,httpStatus:200},g.deduped?`[upload] dedup hit`:`[upload] write ok`),J(t,200,Kt,{src:g.src,path:g.path,deduped:g.deduped},{handler:`upload-asset`});return}switch(g.kind){case`config-error`:X.error({err:g.cause},`[upload] project config has invalid content.attachmentFolderPath`),K(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:g.cause});return;case`invalid-attachment-folder`:K(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...g.cause===void 0?{}:{cause:g.cause}});return;case`dest-validation-error`:X.error({err:g.cause,destDir:g.destDir},`[upload] failed to validate destination directory`),K(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:g.cause});return;case`mkdir-failed`:K(t,sL(g.reason),g.reason,lL(g.reason),{handler:`upload-asset`,cause:g.cause,detail:`failed to create attachment directory`});return;case`write-failed`:X.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:rS(e),agentId:m,agentName:h,filename:g.filename,size:o,reason:g.reason,httpStatus:sL(g.reason),err:g.cause},`[upload] write failed`),K(t,sL(g.reason),g.reason,lL(g.reason),{handler:`upload-asset`,cause:g.cause});return}}let Ni=`/api/local-op/clone`,Pi=`/api/local-op/ok-init`,Li=600*1e3,zi={stdio:[`ignore`,`ignore`,`pipe`]},Bi={stdio:[`ignore`,`pipe`,`pipe`]},Vi={stdio:`ignore`},Hi=`local-op-clone`,Ji=q(gee,Yi,{handler:Hi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Hi})});async function Yi(e,t,n){let{url:r,dir:i,branch:a}=n;if(!OW(r)){K(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:Hi,cause:Error(`url=${r}`)});return}if(!MW(i)){K(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:Hi,cause:Error(`dir=${i}`)});return}if(!Pe.tryAcquire(Ni)){K(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:Hi,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let o=cS(t,Hi),s=null,c=bG({cliArgs:ie,url:r,dir:i,branch:a,timeoutMs:Li,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&X.warn({stderr:MF(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=GW(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(MF(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await c.done,s&&!t.writableEnded&&!t.destroyed){let e=await Xi(s);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:s})}\n`):o(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?o(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):X.error({err:e,handler:Hi},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),Pe.release(Ni)}})(),t.on(`close`,()=>{c.cancel()})}async function Xi(e,t){let n=B(kW(e)),r=PA(n),i=iL(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=ie,s=e=>{let n=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...o,e,...n]},c=async e=>{let t=Ul(a,s(e),xN({...zi,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),X.warn({cwd:n,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let o=null,c=null,l=null;t.on(`exit`,(e,t)=>{o=e??-1,c=t??null}),t.on(`error`,t=>{l=t.message,o=-1,X.error({cwd:n,cliCmd:e,err:t},`[local-op/clone] failed to spawn child`)}),t.unref();let u=Date.now()+45e3;for(;Date.now()<u;){await Lu(500);let t=iL(r);if(t&&t.port>0)return{port:t.port};if(o!==null){let t=Buffer.concat(i).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${l?`spawn failed: ${l}`:c?`killed by ${c}`:`code ${o}`})${t?` — ${t}`:``}`,exited:!0}}}let d=Buffer.concat(i).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${d?` — ${d}`:``}`,exited:!1}},l=Qs(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Qs(r);if(e&&e.port>0){let e=await c(`ui`);return`port`in e?e:{error:`${d.error}; connect fallback failed: ${e.error}`}}}return`port`in d?d:{error:d.error}}let Zi=`local-op-ok-init`,ea=q(Vee,async(e,t,n)=>{let{projectPath:r}=n;if(!Yl(r)){K(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:Zi,cause:Error(`projectPath=${r}`)});return}let i;try{i=U(r)}catch(e){J(t,200,Ui,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:Zi});return}if(!MW(i)){K(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:Zi,cause:Error(`projectPath=${r}`)});return}let a=ld(i).kind;if(a!==`directory`&&a!==`linked`){X.warn({project:Kl(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${Kl(i)} result=not-a-git-worktree kind=${a}`),J(t,200,Ui,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:Zi});return}if(Tz(i)){X.warn({project:Kl(i),result:`already-initialized`},`[ok-init] action=init project=${Kl(i)} result=already-initialized`),J(t,200,Ui,{ok:!0,projectPath:i},{handler:Zi});return}if(!Pe.tryAcquire(Pi)){K(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:Zi,extraHeaders:{"Retry-After":`2`}});return}try{await Bs(async()=>{TU(i)}),X.warn({project:Kl(i),result:`success`},`[ok-init] action=init project=${Kl(i)} result=success`),J(t,200,Ui,{ok:!0,projectPath:i},{handler:Zi})}catch(e){let n=e instanceof Error?e.message:String(e);X.warn({project:Kl(i),result:`failed`,reason:n},`[ok-init] action=init project=${Kl(i)} result=failed reason=${n}`),J(t,200,Ui,{ok:!1,reason:`init-failed`,message:n},{handler:Zi})}finally{Pe.release(Pi)}},{handler:Zi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zi})}),ta=`/api/local-op/auth/login`,na=`/api/local-op/auth/status`,ra=`/api/local-op/auth/repos`,sa=`/api/local-op/auth/signout`,ua=`/api/local-op/auth/pat`,da=`/api/local-op/auth/gh-login`,ha=ae??15e3,ya=960*1e3,Sa=()=>SF(j??s),Ca={current:null},wa={current:null};function Ea(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!Pe.tryAcquire(r)){let e=i.current;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-flow-slot-no-controller`,channel:`auth`,transport:`http`,handler:n})),K(t,429,`urn:ok:error:concurrent-operation`,a,{handler:n,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),i.current=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`,handler:n}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let c=cS(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},ha);u.unref();let d=()=>{u!==null&&(clearInterval(u),u=null)},f=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}rpe(e,A),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,Pe.release(r))})}let Da=`local-op-auth-login`,Oa=q(Tr,ka,{handler:Da,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Da})});async function ka(e,t,n){let r=n.host??Sa();Ea({res:t,handler:Da,guardKey:ta,inFlight:Ca,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>zW({cliArgs:ie,host:r,timeoutMs:ya,onEvent:e})})}let Aa=`local-op-auth-gh-login`,ja=q(Tr,async(e,t,n)=>{let r=n.host??Sa(),i=await OG();if(i===null){K(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Aa});return}Ea({res:t,handler:Aa,guardKey:da,inFlight:wa,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>jG({host:r,ghPath:i,timeoutMs:ya,onEvent:e})})},{handler:Aa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Aa})}),Ma=`local-op-auth-cancel`,Na=q(Bee,aB(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:wa,guardKey:da}:{inFlight:Ca,guardKey:ta},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,Pe.release(r.guardKey)),J(t,200,Ut,{},{handler:Ma})},{handler:Ma,title:`Failed to cancel the sign-in.`}),{handler:Ma,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ma})}),Pa=`local-op-auth-status`,Ia=q(Tr,async(e,t,n)=>{let r=n.host??Sa();if(!Pe.tryAcquire(na)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Pa,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ie,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=Ul(e,i,xN({...Bi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,r.kill(`SIGTERM`)},3e4),s=[];r.stdout.on(`data`,e=>s.push(e)),r.on(`close`,()=>{if(clearTimeout(o),a){n(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(s).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
1215
1215
  `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await OG()!==null;o===null?J(t,200,Fe,{authenticated:!1,ghAvailable:s},{handler:Pa}):J(t,200,Fe,{...o,ghAvailable:s},{handler:Pa})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Pa,cause:e})}finally{Pe.release(na)}},{handler:Pa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Pa})}),La=`local-op-auth-pat`,Ba=q(vr,async(e,t,n)=>{let r=n.host??Sa();if(!Pe.tryAcquire(ua)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:La,extraHeaders:{"Retry-After":`5`}});return}try{let e=await BW({cliArgs:ie,host:r,token:n.token});e.ok?(LZ(A),J(t,200,Mr,{host:e.host,login:e.login},{handler:La})):K(t,400,`urn:ok:error:auth-failed`,e.error,{handler:La})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:La,cause:e})}finally{Pe.release(ua)}},{handler:La,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:La})}),Va=`local-op-auth-repos`,Ha=q(Tr,Ua,{handler:Va,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Va})});async function Ua(e,t,n){let r=n.host??Sa();if(!Pe.tryAcquire(ra)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Va,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=cS(t,Va),[a,...o]=ie,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=Ul(a,s,xN({...Bi,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},Li);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1216
1216
  `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{X.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Pe.release(ra))}),u.on(`error`,e=>{clearTimeout(d),c||(c=!0,t.writableEnded||(i(500,`urn:ok:error:auth-failed`,`Failed to spawn the auth repos subprocess.`,{cause:e}),t.end()),Pe.release(ra))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Pe.release(ra))})}let Wa=`local-op-auth-signout`,Ga=q(Tr,async(e,t,n)=>{let r=n.host??Sa();if(!Pe.tryAcquire(sa)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Wa,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ie,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Ul(e,i,xN({...Vi,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,Ut,{},{handler:Wa})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Wa,cause:e})}finally{Pe.release(sa)}},{handler:Wa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Wa})}),Ka=`/api/local-op/auth/set-identity`,qa=`local-op-auth-set-identity`,Ja=q(An,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!j){K(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:qa});return}if(!Pe.tryAcquire(Ka)){K(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:qa,extraHeaders:{"Retry-After":`5`}});return}try{Uz(j,r,i),A?.()?.refreshIdentity().catch(()=>{}),J(t,200,Ut,{},{handler:qa})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:qa,cause:e})}finally{Pe.release(Ka)}},{handler:qa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:qa})});async function Xa(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=A?.();if(!e){J(t,200,ba,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),J(t,200,ba,e.getStatus(),{handler:`sync-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Za=q(Ri,async(e,t,n)=>{let r=A?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;J(t,202,ji,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?A?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function io(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=A?.();J(t,200,Tee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let fo=q(wi,async(e,t,n)=>{let r=A?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),J(t,200,Fee,{},{handler:`sync-resolve-conflict`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?A?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function po(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!j){K(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=Ix(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=A?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){K(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=zs({baseDir:j,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),o=Ix(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=ye?ye(o):null;t!==null&&(c=t,l=!0)}else{eL(R(j,i),j);try{c=H(R(j,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;J(t,200,no,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=Ix(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=ye?ye(e):null;t!==null&&!ipe(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else X.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}J(t,200,no,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function go(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=jq(a);if(a!==null&&a!==``&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,pa,{plan:await qq({projectDir:s,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof yq){K(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof bq){K(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let yo=q(jee,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){K(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=jq(a);if(typeof a==`string`&&a.length>0&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,Kee,{result:await Hq(i,{projectDir:s,packId:o})},{handler:`seed-apply`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function bo(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}J(t,200,Cee,{packs:Nq()},{handler:`seed-packs`})}}let xo=q(Ki,async(e,t,n)=>{if(n.out!==void 0&&!MW(n.out)){K(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{J(t,200,qr,await pI({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Eo(e,t){if(r(e,t,{handler:`installed-agents`}))try{await _ue(e,t,rt.probeAll)}catch(n){t.headersSent||(X.error({err:n,requestId:rS(e)},`[installed-agents] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Do(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return K(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=B(s),o=i===``?a:B(a,i);return o!==a&&!o.startsWith(`${a}${Ql}`)?(K(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let Oo=/^[A-Za-z0-9_-]+$/;function Ao(e,t,n=`template`){return!e||!Oo.test(e)?(K(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Po(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:B(e,i);if(a!==e&&!a.startsWith(`${e}${Ql}`))continue;let o=B(a,`.ok`,`templates`,`${n}.md`);if(V(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Fo(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}let Io=mU({GET:q(Yn,async(e,t)=>{try{let n=Do(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await Bj(n.folderRel,{projectDir:n.resolvedContentDir}),i=B(B(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(V(i))try{let e=(0,kk.parse)(await Tu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);X.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}J(t,200,yr,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Nr,async(e,t,n)=>{try{if(Oe){K(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Do(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=Gce({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(Vn(e,Rn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Hn(`folder-config-put`))}J(t,200,jn,{applied:i},{handler:`folder-config-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function zo(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&lS(o)?(fS(r,new dS({file:`${i}.md`}),n),!0):!1}function Vo(e,t,n){let r=a.documents.get(e);return r&&lS(r)?(fS(n,new dS({file:`${e}.md`}),t),!0):!1}let Ho=q(Yn,aB(async(e,t)=>{let n=await Oj(B(s));J(t,200,Xee,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),Uo=e=>{let{body:t}=Mo(e);return{frontmatter:br(e)??{},body:t}},Wo=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ao(r,t,`template-get`))return;let i=Do(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Po(o,a,r);if(!s){K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=ao(await Tu(c,`utf-8`)),f=d.identity,p=d.starterContent;J(t,200,iee,{template:{name:r,folder:l,scope:u,path:z(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Go=q(Ne,async(e,t,n)=>{try{if(Oe){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Ao(r,t,`template-put`))return;let i=Do(n.folder,t,`folder`,`template-put`);if(!i||zo(i.folderRel,r,`template-put`,t))return;let a=uM({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Fo(n.frontmatter)});if(!a.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let s=B(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!V(s),l=z(i.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=Ts(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=xn(n),h=await o.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Ab(h.dc.document,a.content,`agent`)},h.origin);let g=await wt(u);if(g?.kind===`failure`){Et(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Dt(t,`template-put`);return}Vn(e,Rn(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await Hn(`template-put`),J(t,200,gi,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ko=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ao(r,t,`template-delete`))return;let i=Do(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=ns(n,se);if(a.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(zo(i.folderRel,r,`template-delete`,t))return;await Yt([Ts(i.folderRel,r)],`deleted-upstream`);let o=nle({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(Vn(a,Rn(`template`,i.folderRel,r),`template-delete: ${o.path}`),await Hn(`template-delete`)),J(t,200,zee,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),qo=mU({GET:Wo,PUT:Go,POST:q(Ar,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ao(n.fromName,t,`template-move`)||!Ao(n.toName,t,`template-move`))return;let r=Do(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Do(n.toFolder,t,`folder`,`template-move`);if(!i||zo(r.folderRel,n.fromName,`template-move`,t))return;await Yt([Ts(r.folderRel,n.fromName)],`renamed`);let a=await rle({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await mQ(j,e,t);return n||pQ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Po(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){K(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}let o=null;if(n.body!==void 0||n.frontmatter!==void 0){let e;if(typeof n.body==`string`)e=n.body;else try{e=Pr(H(B(i.resolvedContentDir,a.toPath),`utf-8`))}catch{e=null}if(e===null)o={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=tle({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Fo(n.frontmatter)});t.ok||(o=t.error)}}if(Vn(e,Rn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Hn(`template-move`),D?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}J(t,200,On,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ko},{handler:`template`}),Jo=q(Cr,async(e,t,n)=>{try{if(Oe){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!gQ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=vt(r);if(Kx(i)||qx(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let c=$Z(s,`file`,i);if(!V(c)){K(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let l=a.documents.get(i);if(n.deleteSource){let e=A?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=l!==void 0&&lS(l),a=n.has(r);if(i||a){fS(t,new dS({file:r}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){K(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=eQ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Ao(d,t,`template-import`))return;let f=Do(n.targetFolder,t,`folder`,`template-import`);if(!f||zo(f.folderRel,d,`template-import`,t))return;let{frontmatter:m,body:h}=Mo(u),g=Qr(m),_={};try{g.trim()&&(_=(0,kk.parse)(g))}catch{}let v=n.title||_?.title||xj(u,d),y=_?.description||``,b=Array.isArray(_?.tags)?_.tags:[],x={..._};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,kk.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${h}`:h;let C=uM({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=B(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!V(w),ee=z(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),te=Ts(f.folderRel,d),{agentId:E,agentName:ne,colorSeed:O,clientName:k}=xn(n),re=await o.getSession(te,E,{displayName:ne,colorSeed:O,clientName:k});re.dc.document.transact(()=>{Ab(re.dc.document,C.content,`agent`)},re.origin);let ie=await wt(te);if(ie?.kind===`failure`){Et(t,ie.failure,`template-import`);return}if(ie?.kind===`divergence`){Dt(t,`template-import`);return}Vn(e,Rn(`template`,f.folderRel,d),`template-import: ${ee}`),n.deleteSource&&(await Yt([i],`deleted-upstream`),ve&&ve.setDeleted(i),us(c),p?.({kind:`delete`,path:c,docName:i})),await Hn(`template-import`),D?.(`files`),J(t,200,gr,{path:ee,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Yo(e,t,n){return!e||e.length>64||!mi.test(e)?(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Xo(e,t,n){let r=bt.safeParse(e??`project`);return r.success?r.data:(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Zo=ce??vu(),$o=$X({contentDir:s,skillsHome:Zo});function es(e){return B(e===`global`?Zo:s,`.ok`,`skills`)}function ts(e,t,n){let r=B(es(e),t);if(e===`global`){if(n!==void 0){let e=ZI(Zo).find(e=>e.name===t&&e.hosts.includes(n));return e?B(Zo,e.dir):null}let e=QI(Zo,t);return e===null?V(R(r,`SKILL.md`))?r:null:e}let i=XI(s).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?B(s,i.dir):n===void 0&&V(R(r,`SKILL.md`))?r:null}function ns(e,t){let n=e.searchParams;return sA({agentId:n.get(`agentId`)??void 0,agentName:n.get(`agentName`)??void 0,colorSeed:n.get(`colorSeed`)??void 0,clientName:n.get(`clientName`)??void 0,clientVersion:n.get(`clientVersion`)??void 0,label:n.get(`label`)??void 0,summary:n.get(`summary`)??void 0},t)}function is(e,t){let n=e===`project`?j:Zo;if(!n)return`symlink`;try{return tc(R(n,...zD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function as(e){let t=e===`project`?j:Zo;return t?R(t,...zD):null}function os(e,t,n,r={}){let i=as(e);return i?uq(i,e=>{let i=e.skills[t];if(!i)return e;let a={...e.skills};return delete a[t],a[n]={...i,...r},{...e,skills:a}}):Promise.resolve()}async function ss(e,t,n){let r=as(e),i=as(t);if(!r||!i)return!1;let a=cq(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await uq(i,e=>({...e,skills:{...e.skills,[n]:o}})),await uq(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function cs(e,t,n){let r=as(e);return r?uq(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function ls(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];K(e,r,i,t.error,{handler:n,detail:t.code})}function ds(e,t,n){let r=e===`project`?j:Zo;return(r?qX(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function fs(e){let t=ts(`project`,e);return t?z(s,t).split(Ql).join(`/`):`${ii}/${e}`}let ps=PF.project;function ms(e,t,n){let r=[],i=null,a=[..._r.map(e=>({id:e,root:Fa[e]??``})),{id:`agents`,root:`.agents/skills`}];for(let{id:o,root:s}of a){if(!s)continue;let a=B(e,...s.split(`/`),t);V(B(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=B(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:z(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function gs(e){let t=YO(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function bs(e,t){if(!IF(t))return null;let n=ms(e,t);if(!n)return null;let r=tO(n.dir)?.contentHash??``,i;try{i=mu(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:Jn,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function xs(e,t,n){let r=ms(e,t);if(!r)return null;let i;try{let{frontmatter:e}=Uo(H(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=bs(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:gs(a)}:{}}}function Cs(e,t,n){return IF(e)?(K(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function Ts(e,t){return`${ro}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Es(e){return e===`navigation`||e===`relevance`?e:void 0}function Ds(e,t){return z(t===`global`?Zo:s,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Os(e){return e===`global`?Zo:j}async function ks(e,t,n){let r=await XN(e,t);if(!V(B(es(n),t,`SKILL.md`))){let i=(n===`project`?XI(s):ZI(Zo)).find(e=>e.name===t);if(i){let a=n===`project`?s:Zo,o=B(a,i.dir),c=B(a,`.agents`,`skills`),l=R(c,t);if(V(c)&&!V(R(l,`SKILL.md`))){let e=!1;try{e=U(o)===U(l)}catch{e=!1}e||vs(o,l,{recursive:!0,dereference:!0})}return AI({canonicalAbs:V(R(l,`SKILL.md`))?l:o,canonicalHash:i.contentHash,name:t,cwd:e,targets:[..._r],roots:yI(n)}),r!==null}}return jI(t,e,_r,yI(n)),r!==null}function As(e,t){let n=[];if(!V(e))return{skills:n,truncated:!1};let r;try{r=lu(e,{withFileTypes:!0})}catch(r){return I(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!mi.test(a.name))continue;if(n.length>=500){i=!0;break}let r=B(e,a.name,`SKILL.md`);if(!V(r))continue;let o;try{let{frontmatter:e}=Uo(H(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Ds(r,t),absolutePath:r})}return{skills:n,truncated:i}}let js=q(Yn,aB(async(e,t)=>{let n=es(`project`),r=As(n,`project`),i=As(es(`global`),`global`),a=[..._r],o=fI(Zo).map(e=>e.editorId),c=j?qN(j).skills:{},l=qN(Zo).skills,u=j?UD(V(R(j,...zD))?H(R(j,...zD),`utf-8`):``)??null:null,d=gs,f=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?u?.skills[e.name]:void 0,o=a?d(a):void 0,s=a?.localHash!==void 0&&nc(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=j?JX(j):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=B(e,i.path);if(n!==void 0&&t===B(n))continue;let a=!1;try{a=au(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(U(t)===U(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=j?HI(s,`project`):{},g=KI(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=GI(`project`),y=GI(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=j?XI(s).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??bs(s,e.name):void 0,r=n?d(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:B(s,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(j,b(t?p[e.name]:void 0,g),B(s,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...ds(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...IF(e.name)?{managed:!0}:{}}}):[],C=JX(Zo),w=tc(R(Zo,...zD)),T=HI(Zo,`global`),ee=KI(T,`global`),te=new Set(ZI(Zo).map(e=>e.name));i.skills=i.skills.filter(e=>!te.has(e.name));let E=new Set,D=ZI(Zo).map(e=>{let t=!E.has(e.name);E.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:B(Zo,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(Zo,b(n,ee),B(Zo,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,ee).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...ds(`global`,e.name,e)===`link`?{linkMode:!0}:{},...IF(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??bs(Zo,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),ne=new Set(S.map(e=>e.name)),O=j&&!r.skills.some(e=>e.name===ps)&&!ne.has(ps)?xs(j,ps,`project`):null,k=new Set(D.map(e=>e.name)),re=zF.map(e=>PF[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!k.has(e)).map(e=>xs(Zo,e,`global`)).filter(e=>e!==null),A=new Set(S.map(e=>e.name));J(t,200,mee,{skills:[...f(r,c,!0).filter(e=>!A.has(e.name)),...S,...f(i,l,!1),...D,...O?[O]:[],...re],truncated:r.truncated||i.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Ms=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Yo(r,t,`skill-get`))return;let i=Xo(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(IF(r)){let e=i===`global`?Zo:j,a=e?ms(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=Uo(await Tu(a.skillMd,`utf-8`));J(t,200,Ai,{skill:{name:r,scope:i,path:a.relPath,frontmatter:{name:typeof e.name==`string`?e.name:r,description:typeof e.description==`string`?e.description:``},body:n,files:NI(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=ts(i,r,a);if(o===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=B(o,`SKILL.md`),{frontmatter:c,body:l}=Uo(await Tu(s,`utf-8`));J(t,200,Ai,{skill:{name:r,scope:i,path:Ds(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:NI(o)}},{handler:`skill-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function Ns(e,t){if(!(!E||Qx(e))){if(fe)try{await fe.rebuildIgnorePatterns()}catch{}await Pt(e,t,`skill-put`)}}let Ps=q(st,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Yo(n.name,t,`skill-put`)||Cs(n.name,t,`skill-put`))return;let r=qj({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?s:Zo,a=ts(n.scope,n.name);if(a===null){let a=qI(i,n.scope),o=Jj({skillsRoot:B(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(Vn(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await Hn(`skill-put`)),await Ns(n.scope===`project`?`${a}/${n.name}/SKILL`:Wn(`global`,n.name),r.content),D?.(`files`),J(t,200,_n,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let c=z(i,a).split(Ql).join(`/`),l=`${c}/SKILL.md`,u=n.scope===`project`?`${c}/SKILL`:Wn(n.scope,n.name);if(Vo(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=xn(n),h=await o.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Ab(h.dc.document,r.content,`agent`)},h.origin);let g=await wt(u);if(g?.kind===`failure`){Et(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Dt(t,`skill-put`);return}n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.name),`skill-edit: ${l}`),await Hn(`skill-put`)),await Ns(u,r.content),D?.(`files`),J(t,200,_n,{path:l,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function Fs(e,t){let n=e===`project`?s:Zo,r=ts(e,t);return{root:r===null?es(e):L(r),dirRel:r===null?`.ok/skills/${t}`:z(n,r).split(Ql).join(`/`),realDir:r}}function Is(e,t){let n=e===`project`?s:Zo,r=(e===`project`?XI(s):ZI(Zo)).find(e=>e.name===t);r&&AI({canonicalAbs:B(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>za(e)),roots:yI(e)})}let Ls=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Yo(r,t,`skill-delete`))return;let i=Xo(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=Fs(i,r),s=ns(n,se);if(s.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Yt(i===`project`?[...new Set([`${o}/SKILL`,Wn(i,r)])]:[Wn(i,r)],`deleted-upstream`),Is(i,r);let c=$j({skillsRoot:a,name:r}),l=es(i);if(c.ok&&l!==a&&V(B(l,r,`SKILL.md`))){let e=$j({skillsRoot:l,name:r});e.ok||X.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(Vn(s,o,`skill-delete: ${o}`),await Hn(`skill-delete`)),D?.(`files`));let u=Os(i);u&&await ks(u,r,i),J(t,200,Wi,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Rs=q($e,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Yo(n.fromName,t,`skill-move`)||!Yo(n.toName,t,`skill-move`)||Cs(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=Fs(n.scope,n.fromName);if(ts(n.scope,n.toName)!==null){K(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=Os(n.scope),o=a?qN(a).skills[n.fromName]:void 0,c=n.scope===`project`?s:Zo,l=(n.scope===`project`?XI(s):ZI(Zo)).find(e=>e.name===n.fromName),u=l?L(l.dir):null,d=u===null?[]:Object.entries(HI(c,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?hI(o.hosts):[],...l?hI(l.hosts):[],...hI(d)])];await Yt(n.scope===`project`?[...new Set([`${i}/SKILL`,Wn(n.scope,n.fromName)])]:[Wn(n.scope,n.fromName)],`renamed`),Is(n.scope,n.fromName);let p=await Yce({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await mQ(j,e,t);return n||pQ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,p.error.message,{handler:`skill-move`,detail:p.error.code});return}let e=p.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:p.error.code,cause:Error(p.error.message)});return}let m=null,h=B(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=Uo(H(h,`utf-8`));g=e.body,typeof e.frontmatter.description==`string`&&(_=e.frontmatter.description)}catch{}let v=typeof n.body==`string`?n.body:g,y=n.frontmatter===void 0?_:n.frontmatter.description,b=Jj({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=zfe({base:n.scope===`project`?s:Zo,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){I(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await fe?.rebuildIgnorePatterns(),await Ys(r,n.fromName,n.toName),await Xs(x,n.toName)}catch(e){I(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=Ds(B(r,n.fromName),n.scope),C=Ds(B(r,n.toName),n.scope);n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await Hn(`skill-move`));let w=nc(r,n.toName),T=n.scope===`project`?await rc(ac(e),C):void 0;if(await os(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await XN(a,n.fromName),jI(n.fromName,a,f,yI(n.scope));let e=B(r,n.toName);if(f.length>0){let t=wI(e,n.toName,a,f,is(n.scope,n.toName),yI(n.scope));await YN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??_I(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(D?.(`files`),m){let e=m.code===`WRITE_ERROR`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:m.code,cause:Error(m.message)});return}J(t,200,mt,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),Vs=q(Gee,async(e,t,n)=>{let{name:r,home:i}=n;if(!Yo(r,t,`skill-edit-external`))return;let a;try{a=U(i)}catch{K(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!mu(a).isDirectory()||!V(B(a,`SKILL.md`))){K(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}PR(r,a),J(t,200,See,{docName:Iee(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),Hs=q(_o,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!Yo(r,t,`skill-move-scope`))return;if(i===a){K(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:c,realDir:l}=Fs(i,r),u=B(o,r),d=(()=>{try{return U(u)}catch{return u}})(),f=a===`project`?s:Zo,p=B(f,qI(f,a)),m=B(p,r);if(l===null||!V(u)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(B(l)===B(m)||V(m)&&U(l)===U(m)){K(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(ts(a,r)!==null||V(m)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let h=Os(i),g=Os(a),_=h?qN(h).skills[r]:void 0,v=i===`project`?s:Zo,y=(i===`project`?XI(s):ZI(Zo)).find(e=>e.name===r),b=y?L(y.dir):null,x=b===null?[]:Object.entries(HI(v,i)).filter(([,e])=>e===b).map(([e])=>e),S=[...new Set([..._?hI(_.hosts):[],...y?hI(y.hosts):[],...hI(x)])];await Yt([...new Set([...i===`project`?[`${c}/SKILL`]:[],Wn(i,r),Wn(a,r)])],`renamed`),hs(p,{recursive:!0}),vs(d,m,{recursive:!0,dereference:!0}),Is(i,r);let C=$j({skillsRoot:o,name:r});if(C.ok&&d!==u){let e=z((()=>{try{return U(v)}catch{return v}})(),d);e!==``&&!e.startsWith(`..`)&&!Yl(e)&&ys(d,{recursive:!0,force:!0})}if(!C.ok){$j({skillsRoot:p,name:r}),K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:C.error.code,cause:Error(C.error.message)});return}let w=await ss(i,a,r);if(h&&await ks(h,r,i),g&&S.length>0){let e=wI(m,r,g,S,is(a,n.name),yI(a));await YN(g,r,{..._,scope:a,hosts:e,scripts:_?.scripts??_I(m,r).hasScripts,installedAt:_?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(Vn(e,i===`project`?c:z(s,m).split(Ql).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await Hn(`skill-move-scope`)),w){let t=nc(p,r),n=a===`project`?await rc(ac(e),z(s,m).split(Ql).join(`/`)):void 0;await cs(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!V(R(m,`SKILL.md`))){K(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:z(f,m).split(Ql).join(`/`)});return}D?.(`files`),J(t,200,fee,{scope:a,path:z(f,m).split(Ql).join(`/`)},{handler:`skill-move-scope`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),Us=q(Gr,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!Yo(n.name,t,`skill-duplicate`)||!Yo(n.toName,t,`skill-duplicate`)||Cs(n.toName,t,`skill-duplicate`))return;let r=ts(n.scope,n.name);if(r===null||!V(R(r,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?s:Zo,a=B(i,qI(i,n.scope)),o=B(a,n.toName);if(ts(n.scope,n.toName)!==null||V(o)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let c=tO(r);if(!c){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}hs(a,{recursive:!0}),vs(r,o,{recursive:!0,dereference:!0});let{fenced:l,body:u}=yn(c.skillMd),d=ut(l,{name:n.toName});if(!d.ok){$j({skillsRoot:a,name:n.toName}),K(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:d.error.kind});return}try{ws(R(o,`SKILL.md`),`${d.nextFenced}${u}`)}catch(e){throw $j({skillsRoot:a,name:n.toName}),e}if(n.scope===`project`){let t=z(s,o).split(Ql).join(`/`);Vn(e,Rn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await Hn(`skill-duplicate`)}D?.(`files`),J(t,200,kee,{name:n.toName},{handler:`skill-duplicate`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),Ws=mU({GET:Ms,PUT:Ps,POST:Rs,DELETE:Ls},{handler:`skill`});function Gs(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<1||t.some(e=>e===`..`)||t.length===1&&t[0].toLowerCase()===`skill.md`?null:t[0]===`references`&&t.length>=2?`reference`:t[0]===`scripts`&&t.length>=2?`script`:`file`}function Ks(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function qs(e,t){let n=t.replace(/\.md$/i,``);return`${xee(e).replace(/\/SKILL$/,``)}/${n}`}function Js(e,t){let n=B(e,t,`references`);if(!V(n))return[];let r=[],i=(e,t)=>{for(let n of lu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(B(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Ys(e,t,n){if(!E){I(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=H(n,`utf-8`)}catch(i){I(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=z(s,e).split(Ql).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),B(e,n,`SKILL.md`));for(let r of Js(e,n))i(o(t,r),o(n,r),B(e,n,r));await E.recordDirectMutations(r)}async function Xs(e,t){if(!E||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await E.recordDirectMutations(n)}let Zs=mU({GET:q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Yo(r,t,`skill-file-get`))return;let i=Xo(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=IF(r)?i===`global`?Zo:j:void 0,s=n.searchParams.get(`host`)??void 0,c=o?ms(o,r,s):null;if(a===``||a.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:Gs(a))??`reference`,u=s,d=o?c?.dir??null:ts(i,r,u);if(d===null&&u!==void 0){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??B(es(i),r),p=B(f,a);if(p!==f&&!p.startsWith(`${f}${Ql}`)){K(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!V(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Ya.map(t=>`${e[1]}${t}`).find(e=>e!==a&&V(B(f,e))):void 0;if(n===void 0){K(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=B(f,n)}let g=await Tu(m);if(g.includes(0)){K(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}J(t,200,eo,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(wee,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Yo(n.name,t,`skill-file-put`)||Cs(n.name,t,`skill-file-put`))return;let r=Gs(n.path);if(r===null){K(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){K(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=ts(n.scope,n.name);if(i===null||!V(R(i,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=z(n.scope===`project`?s:Zo,i).split(Ql).join(`/`),c=n.path.replace(/\\/g,`/`),l=Ks(n.scope,r,c),u;if(l){let e=`${a}/${c.replace(/\.mdx?$/i,``)}`;if(Vo(e,`skill-file-put`,t))return;if(u=!V(B(i,c)),u&&Xj(i)>=50){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:s,colorSeed:l,clientName:d}=xn(n),f=await o.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Ab(f.dc.document,n.content,`agent`)},f.origin);let p=await wt(e);if(p?.kind===`failure`){Et(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Dt(t,`skill-file-put`);return}}else{let e=Zj({skillsRoot:L(i),name:n.name,relPath:c,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;K(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}u=e.created}n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${c}`),await Hn(`skill-file-put`)),D?.(`files`),J(t,200,Si,{path:c,created:u,kind:r,content:l},{handler:`skill-file-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!Yo(i,t,`skill-file-delete`)||Cs(i,t,`skill-file-delete`))return;let a=Xo(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),c=Gs(o);if(c===null){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let l=ns(n,se);if(l.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=ts(a,i),d=u===null?es(a):L(u);if(V(B(u??R(d,i),o))&&Ks(a,c,o)){let e=o.replace(/\.md$/i,``);await Yt([u===null?qs(i,o):`${z(s,u).split(Ql).join(`/`)}/${e}`],`deleted-upstream`)}let f=Qj({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(Vn(l,Rn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${z(s,u).split(Ql).join(`/`)}/${o}`}`),await Hn(`skill-file-delete`)),f.existed&&D?.(`files`),J(t,200,fa,{path:o,existed:f.existed,kind:c},{handler:`skill-file-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),$s=q(Pee,async(e,t,n)=>{try{if(!Yo(n.name,t,`skill-file-rename`)||Cs(n.name,t,`skill-file-rename`))return;let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=Gs(r),o=Gs(i);if(a===null||o===null){K(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let c=ts(n.scope,n.name);if(c===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let l=L(c),u=Ks(n.scope,a,r),d=Ks(n.scope,o,i),f=z(s,c).split(Ql).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Vo(p,`skill-file-rename`,t))return;p!==null&&await Yt([p],`deleted-upstream`);let h=Jce({skillsRoot:l,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,h.error.message,{handler:`skill-file-rename`,detail:h.error.code});return}if(E){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:H(B(l,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:p})}else if(p!==null)e.push({kind:`delete`,documentName:p});else if(m!==null)try{e.push({kind:`upsert`,documentName:m,markdown:H(B(l,n.name,i),`utf-8`)})}catch{}await Nt(e,`skill-file-rename`)}n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await Hn(`skill-file-rename`)),D?.(`files`),J(t,200,va,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){X.error({err:e},`[skill-file-rename] failed`),t.headersSent||K(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function ec(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let tc=cq;function nc(e,t){return tO(B(e,t))?.contentHash}async function rc(e,t){let n=S?.current;if(!(!n||!e))try{let r=dx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1217
- `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Hn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let ac=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function oc(e){try{let t=Os(e.scope);if(!t)return;let n=vI(t);if(n.length===0)return;let r=wI(B(e.skillsRoot,e.name),e.name,t,n,`copy`,yI(e.scope));if(r.length===0)return;await YN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function sc(e,t){if(t.ok){J(e,200,co,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let cc=FX({contentDir:s,skillsHome:Zo,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:ts,parseFrontmatterDoc:Uo,attributeOkArtifactWrite:Vn,commitOkArtifactWrite:Hn,shadowHeadSha:rc,artifactWriterId:ac,effectiveInstallMode:ds,signalFiles:()=>D?.(`files`)}),lc=q(Lr,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await dO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??ID(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(iZ(t,p,`skill-import`))return;let m=await RD(p);r=m.cleanup,s=m.ref;let h=nO(m.dir);if(h.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>$D(e.dir)?.name===f)??h.find(e=>e.name===ct[f]);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??ec(d)}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await cc.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||aa(u))&&lI({source:u,skills:[d.body.name]},JF()),sc(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),uc=q(rr,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await dO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??ID(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(iZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??ec(d),f.kind===`well-known`)a=f,o=await jD(f.origin);else{let e=await RD(f);r=e.cleanup,c=e.ref,s=nO(e.dir)}}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await RD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof xD?`not-found`:`failed`,warnings:[],...e instanceof xD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>tO(e.dir)?.name===t)??s.find(e=>e.name===ct[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await cc.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){I(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){I(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||aa(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&lI({source:u,skills:e},JF())}J(t,200,nee,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),dc=8*1024*1024,fc=32*1024*1024;function pc(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=B(e,n);return r!==e&&!r.startsWith(e+Ql)?null:r}function mc(e){return new Promise((t,n)=>{let r;try{r=(0,Ak.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:dc}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>fc){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function hc(e,t){return new Promise((n,r)=>{(0,jk.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=pc(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){hs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>dc){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>fc){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{hs(L(n),{recursive:!0}),ws(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function gc(e,t){let n=su(R(xu(),`ok-skill-upload-`)),r=()=>{try{ys(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=Xo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=sA({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},se);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await mc(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await hc(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=pc(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}hs(L(r),{recursive:!0}),ws(r,e.data)}let u=nO(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];sc(t,await cc.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let _c=q(jo,async(e,t,n)=>{try{let e=es(n.scope);if(!Yo(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Os(n.scope),i=B(e,n.name),a=n.scope===`project`?s:Zo,o=(n.scope===`project`?XI(s):ZI(Zo)).find(e=>e.name===n.name),c=o?B(a,o.dir):i;if(!V(c)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await wt(n.scope===`project`?`${z(a,c).split(Ql).join(`/`)}/SKILL`:Wn(n.scope,n.name));let l=_I(c,n.name);if(!l.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=$o.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:o.hosts.filter(za),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await $o.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(za),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await $o.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}D?.(`files`),J(t,200,wo,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:Zo;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Dr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||D?.(`files`),J(t,200,wo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:Zo;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Dr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:Zo,s=await Dr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:c,canonicalHash:o.contentHash});if(!s.ok)switch(s.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(s.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?_r.filter(e=>f?.some(t=>t===e)):[..._r]:f===void 0?vI(r):_r.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?j:Zo,s=d===void 0?ds(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await $o.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}D?.(`files`),J(t,200,wo,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await $o.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:s,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),D?.(`files`),J(t,200,wo,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=hI(qN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&jI(n.name,r,v,yI(n.scope));let y=R(r,...zD),b=V(y)?H(y,`utf-8`):null,x=b===null?null:UD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=wI(c,n.name,r,h,C,yI(n.scope));w.length===0?await XN(r,n.name):await YN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),D?.(`files`),J(t,200,wo,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),vc=q(Ro,async(e,t,n)=>{try{if(!Yo(n.name,t,`skill-uninstall`))return;let e=Os(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await ks(e,n.name,n.scope);D?.(`files`),J(t,200,qe,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),yc=mU({GET:q(Yn,async(e,t)=>{try{let e=vI(j??``),n=(e,t)=>{let n=GX(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,It,{targets:e,configured:!1,folders:[...j?IX(s,WI(s,`project`)).map(e=>({...e,scope:`project`,...n(s,e)})):[],...IX(Zo,WI(Zo,`global`)).map(e=>({...e,scope:`global`,...n(Zo,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(see,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?s:Zo;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await KX(r,i.join(`/`)),D?.(`files`),J(t,200,Fn,{targets:vI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(WI(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?BX({base:r,folderRel:e.root,targetRootRel:a}):VX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await WX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),D?.(`files`),J(t,200,Fn,{targets:vI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),bc=q(Qi,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Yo(n.name,t,`skill-restore`)||Cs(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=S?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await sZ({shadow:r,contentDir:s,contentRoot:te??`.`,name:n.name,version:n.version,skillDirRel:fs(n.name)});if(!i.ok){ls(t,i,`skill-restore`);return}let a=[],o=_I(B(s,fs(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),Vn(e,Rn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Hn(`skill-restore`),D?.(`files`),J(t,200,nn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),xc=q(ia,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Yo(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Zo:s,{root:a,dirRel:o,realDir:c}=Fs(n.scope,n.name),l=!o.startsWith(`${ii}/`);if(c===null||!V(B(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=R(n.scope===`global`?Zo:j,...zD),d=tc(u).skills[n.name];if(!d){let e=KD(n.name,tO(B(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:$fe(B(a,n.name))})??bs(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await uq(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),J(t,200,Be,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=ct[e],a=await dO(d.source,e).catch(async e=>{if(i===void 0)throw e;return dO(d.source,i)}),o=a?.source??XO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??ID(o);if(!c){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(iZ(t,c,`skill-reimport`))return;let l=await RD(c);r=l.cleanup,f=l.ref;let u=nO(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>tO(e.dir)?.name===n.name)??u.find(e=>e.name===ct[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=eO(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=tO(m.dir)}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=PX(p);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=tO(B(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){J(t,200,Be,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Uo(p.skillMd).body;if(n.dryRun){let e=tO(B(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=zs({baseDir:j,timeout:{block:15e3}}),t=z(j,B(a,n.name)).split(Ql).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}J(t,200,Be,{name:n.name,updated:!0,source:d.source,localBody:Uo(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await Yt(e,`deleted-upstream`)}let x=Jj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=Zj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:NX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Qj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await Hn(`skill-reimport`));let C=nc(a,n.name),w=n.scope===`project`?await rc(ac(e),o):void 0;await uq(u,e=>WD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await oc({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),D?.(`files`),J(t,200,Be,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Sc=q(un,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Yo(n.name,t,`skill-revert`)||Cs(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=R(j,...zD),i=tc(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=S?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await sZ({shadow:a,contentDir:s,contentRoot:te??`.`,name:n.name,version:i.baselineRef,skillDirRel:fs(n.name)});if(!o.ok){ls(t,o,`skill-revert`);return}Vn(e,Rn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Hn(`skill-revert`);let c=B(s,fs(n.name),`..`),l=nc(c,n.name);await uq(r,e=>WD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),c===es(`project`)&&await oc({skillsRoot:c,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),D?.(`files`),J(t,200,Sn,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Cc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function wc(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Tc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ec(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Dc=jX({contentDir:s,projectDir:j,getAllFilesIndex:f,getFileIndexGeneration:m,getSearchMaxEntries:ope,semanticSearch:xe,getSemanticSimilarityFloor:Se,ready:ge,getProjectSkillsRoot:()=>es(`project`),parseFrontmatterDoc:Uo});Dc.prewarm();let Oc=mU({GET:q(Yn,aB(async(e,t)=>{let n=Zee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Cc(n.get(`intent`)),o=Es(n.get(`ranking`)),s=wc(n.get(`scope`)??n.get(`scopes`)),c=Tc(n.get(`semantic`)),l=Ec(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Ta,await Dc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Jee,aB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Cc(n.intent),a=Es(n.ranking),o=wc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Tc(n.semantic),l=Ec(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Ta,await Dc.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),kc=q(Yn,aB(async(e,t)=>{J(t,200,yee,{...await oI(vu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Ac(e,t){if(r(e,t,{handler:`handoff`}))try{await wue(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:rt.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:rS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function jc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await kN(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:rS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Mc=q(En,async(e,t,n)=>{try{if(!j){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Nde(e,n.kind)){_F(`invalid-path`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`invalid-path`},{handler:gF});return}let r=Rde(j);if(r===null){if(xF(j).kind===`no-remote`){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}_F(`detached-head`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`detached-head`},{handler:gF});return}let i=xF(j);if(i.kind===`no-remote`){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}if(i.kind===`non-github`){_F(`non-github-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`non-github-remote`},{handler:gF});return}if(!Ude(j,r)){_F(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,je,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:gF});return}let a=cQ(j,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&I(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=Pde(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=Fde(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Ju(c)}`,u=await Ide(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);_F(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,je,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:gF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:gF,cause:e})}},{handler:gF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:gF})}),Nc=q(Yn,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Az});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!to(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Az});return}if(!Oz(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Az});return}J(t,200,xr,await kz(j,r,i,a),{handler:Az})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Az,cause:e})}},{handler:Az,method:`GET`,skipBodyParse:!0}),Pc=q(Kr,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:NF});return}if(!Oz(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:NF});return}let e=cQ(j,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,Aee,await Zde(j,n.branch,r,n.kind),{handler:NF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NF,cause:e})}},{handler:NF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:NF})}),Fc=q(mr,async(e,t,n)=>{if(sA(n,se).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:Fz});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Fz});return}try{J(t,200,Or,await Bs(()=>Lz(j,n.branch,{fastForward:n.fastForward===!0})),{handler:Fz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Fz,cause:e})}},{handler:Fz,method:`POST`});async function Ic(e){let[t,...n]=ie,r=[...n,...e];return await new Promise((e,n)=>{let i=Ul(t,r,xN({...Bi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},EF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${EF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=MF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Lc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:CF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ic([`share`,`owners`,`--json`]),n=Wde(kF(e));jF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Dee,n,{handler:CF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CF,cause:e})}finally{Pe.release(`/api/share/publish/owners`)}},{handler:CF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:CF})}),Rc=q(Yn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!OF(r)||!DF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:wF});return}if(!Pe.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:wF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ic([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Gde(kF(e));jF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Yee,n,{handler:wF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:wF,cause:e})}finally{Pe.release(`/api/share/publish/name-check`)}},{handler:wF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:wF})}),zc=q(Uee,async(e,t,n)=>{if(!j){jF(`publish-create`,`no-project`),J(t,200,Gi,{ok:!1,error:`no-project`},{handler:TF});return}if(!OF(n.owner)||!DF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:TF});return}if(!Pe.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:TF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ic(e),i=Jde(kF(r));jF(`publish-create`,i.ok?`ok`:i.error),i.ok&&A?.()?.refreshRemote().catch(()=>{}),J(t,200,Gi,i,{handler:TF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:TF,cause:e})}finally{Pe.release(`/api/share/publish`)}},{handler:TF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:TF})}),Bc=q(ln,async(e,t,n)=>{try{let e=I(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,uee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Vc=j?PA(j):null;async function Hc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Bse(e.headers),previewUrl:null,port:Vc?Qs(Vc)?.port??0:0,singleFile:Oe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,Ge,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function Uc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Me?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,he,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Wc=`local-op-embeddings-set-key`,Gc=`local-op-embeddings-clear-key`,Kc=`/api/local-op/embeddings`;function qc(){let e=Te?.();return{projectDir:j??s,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Jc=q(qee,async(e,t,n)=>{if(!Pe.tryAcquire(Kc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=qc();await new UM(Ce).setForProject(e,r,n.key),xe?.reloadCredential(),J(t,200,pi,{keyPresent:!0},{handler:Wc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Wc,cause:e})}finally{Pe.release(Kc)}},{handler:Wc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Wc})}),Yc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(Kc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=qc();await new UM(Ce).clearForProject(e,n),xe?.reloadCredential(),J(t,200,pi,{keyPresent:!1},{handler:Gc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Gc,cause:e})}finally{Pe.release(Kc)}},{handler:Gc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Gc})}),Xc=`local-op-embeddings-test`,Zc=`/api/local-op/embeddings/test`,Qc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(Zc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Xc,extraHeaders:{"Retry-After":`5`}});return}try{let e=Te?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await IM(new UM(Ce),j??s,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Fle({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,Eee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Xc,cause:e})}finally{Pe.release(Zc)}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Xc})}),$c=q(Yn,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(xe){let t=xe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Te?.()?.baseUrl??`https://api.openai.com/v1`,o=await IM(new UM(Ce),j??s,a),c=o.apiKey!==null,u=!c&&o.keyless,d=c?o.source:null,f=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of l())!Kx(e)&&!qx(e)&&!li(e)&&(p+=1);J(t,200,Hee,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),el=0;function tl(){el+=1,D?.(`lint-config`)}let nl=()=>`${el} ${t.getActiveBranch()}`;async function rl(e,t){let n=Ee?.()??ho;try{let r=await Ra(e,$P(s,n,{docName:t,projectDir:j??s,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=De?.()??`warning`;if(E&&a!==`off`&&!Qx(t)){await Lt(t,e,`lint-validation`);let r=fF({projectDir:j??s,contentDir:s,baseConfig:n,derivedDocumentIndex:E,linksValidation:a,admittedDocNames:Mt,docFilePathFor:e=>aQ(s,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:aQ(s,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function il(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=nF({projectDir:j??s,contentDir:s});return TP(t.schemas,n)}let al=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!gQ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Ee?.()??ho,i=[],a=XP(s,n??void 0,e=>i.push(e)),o=QP(j??s,ZP(r,a),e=>i.push(e));n===null&&i.push(...il(o)),J(t,200,Oi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),ol=q(vee,async(e,t,n)=>{let r;try{r=dF(B(s),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}tl();try{let e=Ee?.()??ho,n=[],r=XP(s,void 0,e=>n.push(e)),i=QP(j??s,ZP(e,r),e=>n.push(e));n.push(...il(i)),J(t,200,Oi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),sl=q(Mee,async(e,t,n)=>{let r;try{let e=B(j??s),t=n.parentPath??[];r=n.delete?bde(e,n.file):n.field!==void 0&&n.removeField?vde(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?yde(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?gde(e,n.file,n.field,n.constraint,t):_de(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&D?.(`files`),tl();try{let e=Ee?.()??ho,n=[],r=XP(s,void 0,e=>n.push(e)),i=QP(j??s,ZP(e,r),e=>n.push(e));n.push(...il(i)),J(t,200,Oi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),cl=q(Yn,async(e,t)=>{try{let e=B(j??s),{schemas:n,truncated:r}=Gue(e),i=new Set(n),a=!1;if(fe!==void 0){let t=YZ({contentDir:s,contentFilter:fe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Qa(a)){let t=z(e,B(s,a));!t.startsWith(`..`)&&!Yl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,ga,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),ll=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},ul=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!gQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=aQ(s,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Ee?.()??ho,a=[],o=await tF({projectDir:j??s,contentDir:s,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:ll});J(t,200,Fr,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof mN){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),dl=new xP,fl=rZ();function pl(e,t,n){let r=`${n} ${nl()} ${t??``}`;return fl.run(r,()=>wde(e,{targetPath:t})).promise}function ml(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let hl=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!XZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Ee?.()??ho;J(t,200,Fi,await rF({projectDir:j??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:ll,cache:dl,auditGeneration:nl}),{handler:`lint-audit`})}catch(e){if(e instanceof eF){ml(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),gl=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!XZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!XZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=aQ(s,o)??`${o}.md`}let c=Ee?.()??ho,l=await pl(fF({projectDir:j??s,contentDir:s,baseConfig:c,liveSourceFor:ll,derivedDocumentIndex:E??null,linksValidation:De?.(),admittedDocNames:Mt,docFilePathFor:e=>aQ(s,e),cache:dl,auditGeneration:nl}),i,xP.fingerprintConfig(c));if(n.searchParams.get(`counts`)===`1`){J(t,200,So,Cde(l),{handler:`audit`});return}J(t,200,zn,l,{handler:`audit`})}catch(e){if(e instanceof eF){ml(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),_l=q(oo,async(t,n,r)=>{try{let t=QZ(r.docName,n,`lint-fix`);if(t===null)return;let i=vt(t),a=sA(r,se);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?c:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Kx(i)||qx(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=aQ(s,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}yN(B(s,f),s);let p=Ee?.()??ho,{stored:m}=Dn(a.summary),h=await o.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await fde({projectDir:j??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=oi(d),n=ei[t]??la(u??c);O?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{Bw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,Rw(h))},h.origin),a.kind!==`anonymous`&&_M(i,c,l,u,void 0,a.kind===`agent`?Cn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{O?.touchMode(c,`idle`)}let t=await wt(i);if(t?.kind===`failure`){Et(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Dt(n,`lint-fix`);return}Ct(i,`lint-fix`);try{b=await Ra(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,ko,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof mN){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof dS){fS(n,e,`lint-fix`);return}if(e instanceof gS){vS(n,e,`lint-fix`);return}if(e instanceof Xw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),vl=`link-preview`,yl=new xW({cacheDir:Oe?null:B(j??s,`.ok`,`local`,`link-previews`)}),bl=null,xl=()=>(bl??=yl.init(),bl),Sl=ke??fW;async function Cl(e){let t=await Sl(e);return t.ok?{ok:!0,metadata:await _W({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Sl})}:{ok:!1,reason:t.reason}}let wl=()=>{try{return Ae?.()===!0}catch{return!1}},Tl=q($a,async(e,t,n)=>{try{if(!wl()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,ci,{ok:!1,reason:`disabled`},{handler:vl});return}await xl();let e=!1,r=await yl.load(n.url,()=>(e=!0,Cl(n.url)));yl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,ci,i,{handler:vl})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vl,cause:e})}},{handler:vl,method:`POST`,preBodyGate:(e,t)=>{let n=wW({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:vl}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:vl}),!1)}}),El=Zse({service:at,getPrincipal:se,onChanged:()=>D?.(`comments`)}),Dl=mU({GET:El.list,POST:El.create},{handler:`comments`}),Ol=mU({GET:El.read,POST:El.mutate,DELETE:El.remove},{handler:`comment`}),{handleSkillsSearch:kl,handleSkillsPopular:Al,handleSkillsDetail:jl,handleSkillsPreview:Ml,handleSkillsDiscover:Nl,handleSkillsResolveRef:Pl}=dZ({log:X,skillsHome:Zo,projectDir:j,contentDir:s,resolveSkillDirForRead:ts}),Fl={"/api/config":Hc,"/api/config/diagnostics":Uc,"/api/comments":Dl,"/api/comment":Ol,"/api/asset":si,"/api/asset-text":di,"/api/document":Qn,"/api/documents":$n,"/api/comment-counts":tr,"/api/link-preview":Tl,"/api/orphans":nr,"/api/hubs":ir,"/api/pages":Di,"/api/folder-config":Io,"/api/template":qo,"/api/template/import":Jo,"/api/templates":Ho,"/api/skill":Ws,"/api/skill-file":Zs,"/api/skill-file/rename":$s,"/api/skills":js,"/api/skills/installed":er,"/api/skills/search":kl,"/api/skills/popular":Al,"/api/skills/detail":jl,"/api/skills/preview":Ml,"/api/skills/discover":Nl,"/api/skills/resolve-ref":Pl,"/api/skill/import":lc,"/api/skills/import-bulk":uc,"/api/skill/edit-external":Vs,"/api/skill/duplicate":Us,"/api/skill/move-scope":Hs,"/api/skill-upload":gc,"/api/skill/install":_c,"/api/skill/uninstall":vc,"/api/skill/restore":bc,"/api/skill/reimport":xc,"/api/skill/revert":Sc,"/api/skill-targets":yc,"/api/search":Oc,"/api/semantic-status":$c,"/api/lint/config":al,"/api/lint/markdownlint-config":ol,"/api/lint/frontmatter-schema":sl,"/api/lint/frontmatter-schemas":cl,"/api/lint":ul,"/api/lint/audit":hl,"/api/lint/fix":_l,"/api/audit":gl,"/api/page-headings":bi,"/api/create-page":hi,"/api/create-folder":vi,"/api/duplicate-path":yi,"/api/rename-path":Ci,"/api/delete-path":Ti,"/api/trash/cleanup":Ei,"/api/upload":Mi,"/api/agent-write":Gn,"/api/agent-write-md":Kn,"/api/agent-write-batch":qn,"/api/frontmatter-patch":Xn,"/api/agent-patch":or,"/api/agent-undo":sr,"/api/agent-activity":ur,"/api/agent-burst-diff":dr,"/api/save-version":kr,"/api/history":jr,"/api/rollback":Br,"/api/metrics/reconciliation":Vr,"/api/metrics/parse-health":Hr,"/api/metrics/agent-presence":Xr,"/api/metrics/agent-effects":Zr,"/api/metrics/watcher-recent":$r,"/api/__embed-detect":ti,"/api/server-info":Ur,"/api/acp/catalog":Jr,"/api/share/construct-url":Mc,"/api/share/target-status":Pc,"/api/git/branch-info":Nc,"/api/git/checkout":Fc,"/api/share/publish/owners":Lc,"/api/share/publish/name-check":Rc,"/api/share/publish":zc,"/api/principal":Yr,"/api/rescue":fi,"/api/workspace":ni,"/api/sync/status":Xa,"/api/sync/trigger":Za,"/api/sync/conflicts":io,"/api/sync/conflict-content":po,"/api/sync/resolve-conflict":fo,"/api/local-op/clone":Ji,"/api/local-op/ok-init":ea,"/api/local-op/auth/login":Oa,"/api/local-op/auth/status":Ia,"/api/local-op/auth/pat":Ba,"/api/local-op/auth/gh-login":ja,"/api/local-op/auth/cancel":Na,"/api/local-op/auth/repos":Ha,"/api/local-op/auth/signout":Ga,"/api/local-op/auth/set-identity":Ja,"/api/local-op/embeddings/set-key":Jc,"/api/local-op/embeddings/clear-key":Yc,"/api/local-op/embeddings/test":Qc,"/api/installed-agents":Eo,"/api/spawn-cursor":jc,"/api/handoff":Ac,"/api/install-skill":xo,"/api/skill/install-state":kc,"/api/seed/plan":go,"/api/seed/apply":yo,"/api/seed/packs":bo,"/api/client-logs":Bc};x&&(Fl[`/api/test-reset`]=hr,Fl[`/api/test-flush-git`]=pr,Fl[`/api/test-rescan-backlinks`]=Sr,Fl[`/api/test-rescan-files`]=wr);let Il=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Ll=[`/api/local-op/`],Rl=iB({log:X,remotePublicHost:n,ephemeral:Oe,table:{resolve(e){let t=Fl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Rr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>Il.has(e)||Ll.some(t=>e.startsWith(t))}}),zl=pU({hocuspocus:a,derivedDocumentIndex:E,getFileIndex:l,isSafeDocName:gQ,readPageTitleForDocName:ot,readPageTitleForLinkedDocName:dt,readFrontmatterMetadataForLinkedDocName:gt,collectAdmittedDocNames:Mt,resolveAlias:vt,respondToDerivedIndexQueryFailure:zt});return BH(zl.paths,Fl),{priority:100,async onRequest({request:e,response:t}){await Rl(e,t)},nativeApi:{paths:zl.paths,dispatch:iB({log:X,remotePublicHost:n,ephemeral:Oe,table:zl.table})}}}function vQ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a}=e;return(e,o,s)=>{let c;try{c=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return s()}let l=Jl(c).slice(1).toLowerCase(),u=l===`md`||l===`mdx`;if(!c||t.isPathIgnored(c)||!u&&!i.has(l))return s();o.setHeader(`X-Content-Type-Options`,`nosniff`);let d=uX(l,r);u||o.setHeader(`Content-Disposition`,d.disposition),d.csp!==null&&o.setHeader(`Content-Security-Policy`,d.csp),d.sandboxedHtml&&o.setHeader(`Cache-Control`,`no-store`),n(e,o,()=>{if(o.headersSent)return;let e=te.has(l);if(!e&&(i.has(l)||a.has(l))){o.statusCode=404,o.end();return}e&&(o.removeHeader(`Content-Security-Policy`),o.removeHeader(`Content-Disposition`),o.removeHeader(`X-Content-Type-Options`),o.removeHeader(`Cache-Control`)),s()})}}function yQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Spe(e){let t;try{t=lu(e.contentDir,{withFileTypes:!0})}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Fx(n.name,c)&&e.basenameIndex.add(n.name)}async function bQ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Eu(i,{withFileTypes:!0})}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=R(i,o.name),s=Vk(z(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await wu(a)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Du(a)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Hk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Ou(i)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Fx(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Fx(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const xQ=N({principalId:F().optional(),tabSessionId:F().optional(),expectedServerInstanceId:F().optional(),expectedBranch:F().optional(),expectedDocLineageEpoch:F().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:F().optional(),clientKind:F().optional()}).loose(),SQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function CQ(e){return SQ.includes(e)}function wQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Cpe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!CQ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var TQ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=wQ(e,this.payload)}};function EQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=xQ.safeParse(t);return n.success?n.data:void 0}var DQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const OQ=I(`conflict-storage`);var kQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=R(PA(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!V(this.storePath)){this.conflicts=[];return}try{let e=H(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){OQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){OQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=L(this.storePath);V(e)||ou(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return gu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return OQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-Ca0yLTy3.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=B(this.projectDir),r=B(t,e);if(!Hk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);eL(r,t),ws(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),OQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await zb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){OQ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),OQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=B(this.projectDir),a=B(i,e.file);if(!Hk(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(eL(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-Ca0yLTy3.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);eL(a,i),ws(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);ws(a,n,`utf-8`);break;case`delete`:V(a)&&us(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function wpe(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Tpe(e,t){let n=PA(e);try{ou(n,{recursive:!0}),gu(R(n,Dr),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Ps(e);ou(L(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};gu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const AQ=new Map;let jQ=!1;function Epe(e,t){try{let n=wpe(e,t);for(let e of AQ.keys())Tpe(e,n)}catch{}}function Dpe(e){AQ.set(e,(AQ.get(e)??0)+1),jQ||(jQ=!0,process.on(`uncaughtExceptionMonitor`,Epe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=AQ.get(e)??0;n<=1?AQ.delete(e):AQ.set(e,n-1)}}}function MQ(e){let t=e.scheduler??ai,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function NQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function PQ(e){if(!V(e))return{};let t;try{t=(0,kk.parse)(H(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!NQ(t))return{};let n=t.telemetry;if(!NQ(n))return{};let r=n.localSink;return NQ(r)?r:{}}function FQ(e){return typeof e==`boolean`?e:void 0}function Ope(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function IQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function LQ(e){if(NQ(e))return Ope(e.maxBytes)}function kpe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=PQ(ts(`project`,e.projectDir)),n=PQ(ts(`project-local`,e.projectDir));if((FQ(n.enabled)??FQ(t.enabled)??!0)===!1)return null;let r=LQ(n.spans)??LQ(t.spans)??52428800,i=LQ(n.logs)??LQ(t.logs)??26214400,a=IQ(n.attributeDenylist)??IQ(t.attributeDenylist)??Ee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var RQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(RQ||={});var Ape;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Ape||={});const zQ=RQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),BQ=e=>{switch(typeof e){case`undefined`:return zQ.undefined;case`string`:return zQ.string;case`number`:return Number.isNaN(e)?zQ.nan:zQ.number;case`boolean`:return zQ.boolean;case`function`:return zQ.function;case`bigint`:return zQ.bigint;case`symbol`:return zQ.symbol;case`object`:return Array.isArray(e)?zQ.array:e===null?zQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?zQ.promise:typeof Map<`u`&&e instanceof Map?zQ.map:typeof Set<`u`&&e instanceof Set?zQ.set:typeof Date<`u`&&e instanceof Date?zQ.date:zQ.object;default:return zQ.unknown}},Z=RQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var VQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,RQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};VQ.create=e=>new VQ(e);const HQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===zQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,RQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${RQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${RQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${RQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:RQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,RQ.assertNever(e)}return{message:n}};let jpe=HQ;function UQ(){return jpe}const WQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function GQ(e,t){let n=UQ(),r=WQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===HQ?void 0:HQ].filter(e=>!!e)});e.common.issues.push(r)}var KQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return qQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return qQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const qQ=Object.freeze({status:`aborted`}),JQ=e=>({status:`dirty`,value:e}),YQ=e=>({status:`valid`,value:e}),XQ=e=>e.status===`aborted`,ZQ=e=>e.status===`dirty`,QQ=e=>e.status===`valid`,$Q=e=>typeof Promise<`u`&&e instanceof Promise;var e$;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(e$||={});var t$=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const n$=(e,t)=>{if(QQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new VQ(e.common.issues);return this._error=t,this._error}}};function r$(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var i$=class{get description(){return this._def.description}_getType(e){return BQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:BQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new KQ,ctx:{common:e.parent.common,data:e.data,parsedType:BQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if($Q(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)};return n$(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return QQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>QQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)},r=this._parse({data:e,path:n.path,parent:n});return n$(n,await($Q(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new I$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return L$.create(this,this._def)}nullable(){return R$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return b$.create(this)}promise(){return F$.create(this,this._def)}or(e){return C$.create([this,e],this._def)}and(e){return E$.create(this,e,this._def)}transform(e){return new I$({...r$(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new z$({...r$(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new H$({typeName:Q.ZodBranded,type:this,...r$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new B$({...r$(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return U$.create(this,e)}readonly(){return W$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Mpe=/^c[^\s-]{8,}$/i,Npe=/^[0-9a-z]+$/,Ppe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fpe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ipe=/^[a-z0-9_-]{21}$/i,Lpe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rpe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zpe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let a$;const Bpe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Vpe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Hpe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Upe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wpe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gpe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,o$=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Kpe=RegExp(`^${o$}$`);function s$(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function qpe(e){return RegExp(`^${s$(e)}$`)}function Jpe(e){let t=`${o$}T${s$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Ype(e,t){return!!((t===`v4`||!t)&&Bpe.test(e)||(t===`v6`||!t)&&Hpe.test(e))}function Xpe(e,t){if(!Lpe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Zpe(e,t){return!!((t===`v4`||!t)&&Vpe.test(e)||(t===`v6`||!t)&&Upe.test(e))}var c$=class e extends i${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==zQ.string){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.string,received:t.parsedType}),qQ}let t=new KQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?GQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&GQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)zpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)a$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),a$.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Fpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ipe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Mpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Npe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ppe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),GQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Jpe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Kpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?qpe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Rpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Ype(e.data,r.version)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Xpe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Zpe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):RQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...e$.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...e$.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...e$.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...e$.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...e$.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...e$.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...e$.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...e$.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...e$.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...e$.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...e$.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...e$.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...e$.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...e$.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...e$.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...e$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...e$.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...e$.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...e$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...e$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...e$.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...e$.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...e$.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...e$.errToObj(t)})}nonempty(e){return this.min(1,e$.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};c$.create=e=>new c$({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...r$(e)});function Qpe(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var l$=class e extends i${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==zQ.number){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.number,received:t.parsedType}),qQ}let t,n=new KQ;for(let r of this._def.checks)r.kind===`int`?RQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Qpe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):RQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,e$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,e$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,e$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,e$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:e$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:e$.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:e$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:e$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:e$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:e$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:e$.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:e$.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:e$.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:e$.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&RQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};l$.create=e=>new l$({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...r$(e)});var u$=class e extends i${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==zQ.bigint)return this._getInvalidInput(e);let t,n=new KQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):RQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.bigint,received:t.parsedType}),qQ}gte(e,t){return this.setLimit(`min`,e,!0,e$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,e$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,e$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,e$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:e$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:e$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:e$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:e$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:e$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:e$.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};u$.create=e=>new u$({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...r$(e)});var d$=class extends i${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==zQ.boolean){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.boolean,received:t.parsedType}),qQ}return YQ(e.data)}};d$.create=e=>new d$({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...r$(e)});var f$=class e extends i${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==zQ.date){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.date,received:t.parsedType}),qQ}if(Number.isNaN(e.data.getTime()))return GQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),qQ;let t=new KQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):RQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:e$.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:e$.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};f$.create=e=>new f$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...r$(e)});var p$=class extends i${_parse(e){if(this._getType(e)!==zQ.symbol){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.symbol,received:t.parsedType}),qQ}return YQ(e.data)}};p$.create=e=>new p$({typeName:Q.ZodSymbol,...r$(e)});var m$=class extends i${_parse(e){if(this._getType(e)!==zQ.undefined){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.undefined,received:t.parsedType}),qQ}return YQ(e.data)}};m$.create=e=>new m$({typeName:Q.ZodUndefined,...r$(e)});var h$=class extends i${_parse(e){if(this._getType(e)!==zQ.null){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.null,received:t.parsedType}),qQ}return YQ(e.data)}};h$.create=e=>new h$({typeName:Q.ZodNull,...r$(e)});var g$=class extends i${constructor(){super(...arguments),this._any=!0}_parse(e){return YQ(e.data)}};g$.create=e=>new g$({typeName:Q.ZodAny,...r$(e)});var _$=class extends i${constructor(){super(...arguments),this._unknown=!0}_parse(e){return YQ(e.data)}};_$.create=e=>new _$({typeName:Q.ZodUnknown,...r$(e)});var v$=class extends i${_parse(e){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.never,received:t.parsedType}),qQ}};v$.create=e=>new v$({typeName:Q.ZodNever,...r$(e)});var y$=class extends i${_parse(e){if(this._getType(e)!==zQ.undefined){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.void,received:t.parsedType}),qQ}return YQ(e.data)}};y$.create=e=>new y$({typeName:Q.ZodVoid,...r$(e)});var b$=class e extends i${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==zQ.array)return GQ(t,{code:Z.invalid_type,expected:zQ.array,received:t.parsedType}),qQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(GQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(GQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(GQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new t$(t,e,t.path,n)))).then(e=>KQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new t$(t,e,t.path,n)));return KQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:e$.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:e$.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:e$.toString(n)}})}nonempty(e){return this.min(1,e)}};b$.create=(e,t)=>new b$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...r$(t)});function x$(e){if(e instanceof S$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=L$.create(x$(r))}return new S$({...e._def,shape:()=>t})}else if(e instanceof b$)return new b$({...e._def,type:x$(e.element)});else if(e instanceof L$)return L$.create(x$(e.unwrap()));else if(e instanceof R$)return R$.create(x$(e.unwrap()));else if(e instanceof D$)return D$.create(e.items.map(e=>x$(e)));else return e}var S$=class e extends i${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=RQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==zQ.object){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.object,received:t.parsedType}),qQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof v$&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new t$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof v$){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(GQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new t$(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>KQ.mergeObjectSync(t,e)):KQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return e$.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:e$.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of RQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of RQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return x$(this)}partial(t){let n={};for(let e of RQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of RQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof L$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return M$(RQ.objectKeys(this.shape))}};S$.create=(e,t)=>new S$({shape:()=>e,unknownKeys:`strip`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)}),S$.strictCreate=(e,t)=>new S$({shape:()=>e,unknownKeys:`strict`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)}),S$.lazycreate=(e,t)=>new S$({shape:e,unknownKeys:`strip`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)});var C$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new VQ(e.ctx.common.issues));return GQ(t,{code:Z.invalid_union,unionErrors:n}),qQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new VQ(e));return GQ(t,{code:Z.invalid_union,unionErrors:i}),qQ}}get options(){return this._def.options}};C$.create=(e,t)=>new C$({options:e,typeName:Q.ZodUnion,...r$(t)});const w$=e=>e instanceof A$?w$(e.schema):e instanceof I$?w$(e.innerType()):e instanceof j$?[e.value]:e instanceof N$?e.options:e instanceof P$?RQ.objectValues(e.enum):e instanceof z$?w$(e._def.innerType):e instanceof m$?[void 0]:e instanceof h$?[null]:e instanceof L$?[void 0,...w$(e.unwrap())]:e instanceof R$?[null,...w$(e.unwrap())]:e instanceof H$||e instanceof W$?w$(e.unwrap()):e instanceof B$?w$(e._def.innerType):[];var $pe=class e extends i${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==zQ.object)return GQ(t,{code:Z.invalid_type,expected:zQ.object,received:t.parsedType}),qQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(GQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),qQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=w$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...r$(r)})}};function T$(e,t){let n=BQ(e),r=BQ(t);if(e===t)return{valid:!0,data:e};if(n===zQ.object&&r===zQ.object){let n=RQ.objectKeys(t),r=RQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=T$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===zQ.array&&r===zQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=T$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===zQ.date&&r===zQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var E$=class extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(XQ(e)||XQ(r))return qQ;let i=T$(e.value,r.value);return i.valid?((ZQ(e)||ZQ(r))&&t.dirty(),{status:t.value,value:i.data}):(GQ(n,{code:Z.invalid_intersection_types}),qQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};E$.create=(e,t,n)=>new E$({left:e,right:t,typeName:Q.ZodIntersection,...r$(n)});var D$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.array)return GQ(n,{code:Z.invalid_type,expected:zQ.array,received:n.parsedType}),qQ;if(n.data.length<this._def.items.length)return GQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),qQ;!this._def.rest&&n.data.length>this._def.items.length&&(GQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new t$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>KQ.mergeArray(t,e)):KQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};D$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new D$({items:e,typeName:Q.ZodTuple,rest:null,...r$(t)})};var eme=class e extends i${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.object)return GQ(n,{code:Z.invalid_type,expected:zQ.object,received:n.parsedType}),qQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new t$(n,e,n.path,e)),value:a._parse(new t$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?KQ.mergeObjectAsync(t,r):KQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof i$?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...r$(r)}):new e({keyType:c$.create(),valueType:t,typeName:Q.ZodRecord,...r$(n)})}},O$=class extends i${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.map)return GQ(n,{code:Z.invalid_type,expected:zQ.map,received:n.parsedType}),qQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new t$(n,e,n.path,[a,`key`])),value:i._parse(new t$(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return qQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return qQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};O$.create=(e,t,n)=>new O$({valueType:t,keyType:e,typeName:Q.ZodMap,...r$(n)});var k$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.set)return GQ(n,{code:Z.invalid_type,expected:zQ.set,received:n.parsedType}),qQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(GQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(GQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return qQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new t$(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:e$.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:e$.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};k$.create=(e,t)=>new k$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...r$(t)});var tme=class e extends i${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==zQ.function)return GQ(t,{code:Z.invalid_type,expected:zQ.function,received:t.parsedType}),qQ;function n(e,n){return WQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,UQ(),HQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return WQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,UQ(),HQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof F$){let e=this;return YQ(async function(...t){let o=new VQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return YQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new VQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new VQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:D$.create(t).rest(_$.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||D$.create([]).rest(_$.create()),returns:n||_$.create(),typeName:Q.ZodFunction,...r$(r)})}},A$=class extends i${get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};A$.create=(e,t)=>new A$({getter:e,typeName:Q.ZodLazy,...r$(t)});var j$=class extends i${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return GQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),qQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};j$.create=(e,t)=>new j$({value:e,typeName:Q.ZodLiteral,...r$(t)});function M$(e,t){return new N$({values:e,typeName:Q.ZodEnum,...r$(t)})}var N$=class e extends i${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return GQ(t,{expected:RQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),qQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return GQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),qQ}return YQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};N$.create=M$;var P$=class extends i${_parse(e){let t=RQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==zQ.string&&n.parsedType!==zQ.number){let e=RQ.objectValues(t);return GQ(n,{expected:RQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),qQ}if(this._cache||=new Set(RQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=RQ.objectValues(t);return GQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),qQ}return YQ(e.data)}get enum(){return this._def.values}};P$.create=(e,t)=>new P$({values:e,typeName:Q.ZodNativeEnum,...r$(t)});var F$=class extends i${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==zQ.promise&&t.common.async===!1?(GQ(t,{code:Z.invalid_type,expected:zQ.promise,received:t.parsedType}),qQ):YQ((t.parsedType===zQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};F$.create=(e,t)=>new F$({type:e,typeName:Q.ZodPromise,...r$(t)});var I$=class extends i${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{GQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return qQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?qQ:r.status===`dirty`||t.value===`dirty`?JQ(r.value):r});{if(t.value===`aborted`)return qQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?qQ:r.status===`dirty`||t.value===`dirty`?JQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?qQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?qQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!QQ(e))return qQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>QQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):qQ);RQ.assertNever(r)}};I$.create=(e,t,n)=>new I$({schema:e,typeName:Q.ZodEffects,effect:t,...r$(n)}),I$.createWithPreprocess=(e,t,n)=>new I$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...r$(n)});var L$=class extends i${_parse(e){return this._getType(e)===zQ.undefined?YQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:Q.ZodOptional,...r$(t)});var R$=class extends i${_parse(e){return this._getType(e)===zQ.null?YQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:Q.ZodNullable,...r$(t)});var z$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===zQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...r$(t)});var B$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return $Q(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new VQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new VQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};B$.create=(e,t)=>new B$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...r$(t)});var V$=class extends i${_parse(e){if(this._getType(e)!==zQ.nan){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.nan,received:t.parsedType}),qQ}return{status:`valid`,value:e.data}}};V$.create=e=>new V$({typeName:Q.ZodNaN,...r$(e)});var H$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},U$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qQ:e.status===`dirty`?(t.dirty(),JQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},W$=class extends i${_parse(e){let t=this._def.innerType._parse(e),n=e=>(QQ(e)&&(e.value=Object.freeze(e.value)),e);return $Q(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};W$.create=(e,t)=>new W$({innerType:e,typeName:Q.ZodReadonly,...r$(t)}),S$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),c$.create,l$.create,V$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create,b$.create;const nme=S$.create;S$.strictCreate,C$.create,$pe.create,E$.create,D$.create,eme.create,O$.create,k$.create,tme.create,A$.create,j$.create,N$.create,P$.create,F$.create,I$.create,L$.create,R$.create,I$.createWithPreprocess,U$.create;const rme=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>me(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>pe(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ime=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),rme.init(e,t),l(e,`shape`,()=>t.shape)});function G$(e,t){return new ime({type:`object`,shape:e??{},...d(t)})}function K$(e){return!!e._zod}function q$(e){let t=Object.values(e);if(t.length===0)return G$({});let n=t.every(K$),r=t.every(e=>!K$(e));if(n)return G$(e);if(r)return nme(e);throw Error(`Mixed Zod versions detected in object shape.`)}function J$(e,t){return K$(e)?pe(e,t):e.safeParse(t)}async function Y$(e,t){return K$(e)?await h(e,t):await e.safeParseAsync(t)}function X$(e){if(!e)return;let t;if(t=K$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Z$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return q$(e)}}if(K$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Q$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function ame(e){return e.description}function ome(e){if(K$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function $$(e){if(K$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const e1=`2025-11-25`,t1=[e1,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],n1=`io.modelcontextprotocol/related-task`,r1=ye(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),i1=Ae([F(),P().int()]),a1=F();ce({ttl:P().optional(),pollInterval:P().optional()});const sme=N({ttl:P().optional()}),cme=N({taskId:F()}),o1=ce({progressToken:i1.optional(),[n1]:cme.optional()}),s1=N({_meta:o1.optional()}),c1=s1.extend({task:sme.optional()}),lme=e=>c1.safeParse(e).success,l1=N({method:F(),params:s1.loose().optional()}),u1=N({_meta:o1.optional()}),d1=N({method:F(),params:u1.loose().optional()}),f1=ce({_meta:o1.optional()}),p1=Ae([F(),P().int()]),m1=N({jsonrpc:j(`2.0`),id:p1,...l1.shape}).strict(),h1=e=>m1.safeParse(e).success,g1=N({jsonrpc:j(`2.0`),...d1.shape}).strict(),ume=e=>g1.safeParse(e).success,_1=N({jsonrpc:j(`2.0`),id:p1,result:f1}).strict(),v1=e=>_1.safeParse(e).success;var y1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(y1||={});const b1=N({jsonrpc:j(`2.0`),id:p1.optional(),error:N({code:P().int(),message:F(),data:A().optional()})}).strict(),x1=e=>b1.safeParse(e).success,S1=Ae([m1,g1,_1,b1]);Ae([_1,b1]);const C1=f1.strict(),dme=u1.extend({requestId:p1.optional(),reason:F().optional()}),w1=d1.extend({method:j(`notifications/cancelled`),params:dme}),T1=N({icons:M(N({src:F(),mimeType:F().optional(),sizes:M(F()).optional(),theme:we([`light`,`dark`]).optional()})).optional()}),E1=N({name:F(),title:F().optional()}),D1=E1.extend({...E1.shape,...T1.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),fme=ue(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ge(N({form:ge(N({applyDefaults:k().optional()}),O(F(),A())).optional(),url:r1.optional()}),O(F(),A()).optional())),pme=ce({list:r1.optional(),cancel:r1.optional(),requests:ce({sampling:ce({createMessage:r1.optional()}).optional(),elicitation:ce({create:r1.optional()}).optional()}).optional()}),mme=ce({list:r1.optional(),cancel:r1.optional(),requests:ce({tools:ce({call:r1.optional()}).optional()}).optional()}),hme=N({experimental:O(F(),r1).optional(),sampling:N({context:r1.optional(),tools:r1.optional()}).optional(),elicitation:fme.optional(),roots:N({listChanged:k().optional()}).optional(),tasks:pme.optional(),extensions:O(F(),r1).optional()}),gme=s1.extend({protocolVersion:F(),capabilities:hme,clientInfo:D1}),O1=l1.extend({method:j(`initialize`),params:gme}),k1=e=>O1.safeParse(e).success,_me=N({experimental:O(F(),r1).optional(),logging:r1.optional(),completions:r1.optional(),prompts:N({listChanged:k().optional()}).optional(),resources:N({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:N({listChanged:k().optional()}).optional(),tasks:mme.optional(),extensions:O(F(),r1).optional()}),vme=f1.extend({protocolVersion:F(),capabilities:_me,serverInfo:D1,instructions:F().optional()}),A1=d1.extend({method:j(`notifications/initialized`),params:u1.optional()}),yme=e=>A1.safeParse(e).success,j1=l1.extend({method:j(`ping`),params:s1.optional()}),bme=N({progress:P(),total:de(P()),message:de(F())}),xme=N({...u1.shape,...bme.shape,progressToken:i1}),M1=d1.extend({method:j(`notifications/progress`),params:xme}),Sme=s1.extend({cursor:a1.optional()}),N1=l1.extend({params:Sme.optional()}),P1=f1.extend({nextCursor:a1.optional()}),Cme=we([`working`,`input_required`,`completed`,`failed`,`cancelled`]),F1=N({taskId:F(),status:Cme,ttl:Ae([P(),ve()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:de(P()),statusMessage:de(F())}),I1=f1.extend({task:F1}),wme=u1.merge(F1),L1=d1.extend({method:j(`notifications/tasks/status`),params:wme}),R1=l1.extend({method:j(`tasks/get`),params:s1.extend({taskId:F()})}),z1=f1.merge(F1),B1=l1.extend({method:j(`tasks/result`),params:s1.extend({taskId:F()})});f1.loose();const V1=N1.extend({method:j(`tasks/list`)}),H1=P1.extend({tasks:M(F1)}),U1=l1.extend({method:j(`tasks/cancel`),params:s1.extend({taskId:F()})}),Tme=f1.merge(F1),W1=N({uri:F(),mimeType:de(F()),_meta:O(F(),A()).optional()}),G1=W1.extend({text:F()}),K1=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),q1=W1.extend({blob:K1}),J1=we([`user`,`assistant`]),Y1=N({audience:M(J1).optional(),priority:P().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),X1=N({...E1.shape,...T1.shape,uri:F(),description:de(F()),mimeType:de(F()),size:de(P()),annotations:Y1.optional(),_meta:de(ce({}))}),Eme=N({...E1.shape,...T1.shape,uriTemplate:F(),description:de(F()),mimeType:de(F()),annotations:Y1.optional(),_meta:de(ce({}))}),Z1=N1.extend({method:j(`resources/list`)}),Dme=P1.extend({resources:M(X1)}),Q1=N1.extend({method:j(`resources/templates/list`)}),Ome=P1.extend({resourceTemplates:M(Eme)}),$1=s1.extend({uri:F()}),kme=$1,e0=l1.extend({method:j(`resources/read`),params:kme}),Ame=f1.extend({contents:M(Ae([G1,q1]))}),jme=d1.extend({method:j(`notifications/resources/list_changed`),params:u1.optional()}),Mme=$1,Nme=l1.extend({method:j(`resources/subscribe`),params:Mme}),Pme=$1,Fme=l1.extend({method:j(`resources/unsubscribe`),params:Pme}),Ime=u1.extend({uri:F()}),Lme=d1.extend({method:j(`notifications/resources/updated`),params:Ime}),Rme=N({name:F(),description:de(F()),required:de(k())}),zme=N({...E1.shape,...T1.shape,description:de(F()),arguments:de(M(Rme)),_meta:de(ce({}))}),t0=N1.extend({method:j(`prompts/list`)}),Bme=P1.extend({prompts:M(zme)}),Vme=s1.extend({name:F(),arguments:O(F(),F()).optional()}),n0=l1.extend({method:j(`prompts/get`),params:Vme}),r0=N({type:j(`text`),text:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),i0=N({type:j(`image`),data:K1,mimeType:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),a0=N({type:j(`audio`),data:K1,mimeType:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),Hme=N({type:j(`tool_use`),name:F(),id:F(),input:O(F(),A()),_meta:O(F(),A()).optional()}),Ume=N({type:j(`resource`),resource:Ae([G1,q1]),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),o0=Ae([r0,i0,a0,X1.extend({type:j(`resource_link`)}),Ume]),Wme=N({role:J1,content:o0}),Gme=f1.extend({description:F().optional(),messages:M(Wme)}),Kme=d1.extend({method:j(`notifications/prompts/list_changed`),params:u1.optional()}),qme=N({title:F().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),Jme=N({taskSupport:we([`required`,`optional`,`forbidden`]).optional()}),s0=N({...E1.shape,...T1.shape,description:F().optional(),inputSchema:N({type:j(`object`),properties:O(F(),r1).optional(),required:M(F()).optional()}).catchall(A()),outputSchema:N({type:j(`object`),properties:O(F(),r1).optional(),required:M(F()).optional()}).catchall(A()).optional(),annotations:qme.optional(),execution:Jme.optional(),_meta:O(F(),A()).optional()}),c0=N1.extend({method:j(`tools/list`)}),Yme=P1.extend({tools:M(s0)}),l0=f1.extend({content:M(o0).default([]),structuredContent:O(F(),A()).optional(),isError:k().optional()});l0.or(f1.extend({toolResult:A()}));const Xme=c1.extend({name:F(),arguments:O(F(),A()).optional()}),u0=l1.extend({method:j(`tools/call`),params:Xme}),Zme=d1.extend({method:j(`notifications/tools/list_changed`),params:u1.optional()});N({autoRefresh:k().default(!0),debounceMs:P().int().nonnegative().default(300)});const d0=we([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Qme=s1.extend({level:d0}),f0=l1.extend({method:j(`logging/setLevel`),params:Qme}),$me=u1.extend({level:d0,logger:F().optional(),data:A()}),ehe=d1.extend({method:j(`notifications/message`),params:$me}),the=N({hints:M(N({name:F().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),nhe=N({mode:we([`auto`,`required`,`none`]).optional()}),rhe=N({type:j(`tool_result`),toolUseId:F().describe(`The unique identifier for the corresponding tool call.`),content:M(o0).default([]),structuredContent:N({}).loose().optional(),isError:k().optional(),_meta:O(F(),A()).optional()}),ihe=Se(`type`,[r0,i0,a0]),p0=Se(`type`,[r0,i0,a0,Hme,rhe]),ahe=N({role:J1,content:Ae([p0,M(p0)]),_meta:O(F(),A()).optional()}),ohe=c1.extend({messages:M(ahe),modelPreferences:the.optional(),systemPrompt:F().optional(),includeContext:we([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:M(F()).optional(),metadata:r1.optional(),tools:M(s0).optional(),toolChoice:nhe.optional()}),she=l1.extend({method:j(`sampling/createMessage`),params:ohe}),m0=f1.extend({model:F(),stopReason:de(we([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:J1,content:ihe}),h0=f1.extend({model:F(),stopReason:de(we([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(F())),role:J1,content:Ae([p0,M(p0)])}),che=N({type:j(`boolean`),title:F().optional(),description:F().optional(),default:k().optional()}),lhe=N({type:j(`string`),title:F().optional(),description:F().optional(),minLength:P().optional(),maxLength:P().optional(),format:we([`email`,`uri`,`date`,`date-time`]).optional(),default:F().optional()}),uhe=N({type:we([`number`,`integer`]),title:F().optional(),description:F().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),dhe=N({type:j(`string`),title:F().optional(),description:F().optional(),enum:M(F()),default:F().optional()}),fhe=N({type:j(`string`),title:F().optional(),description:F().optional(),oneOf:M(N({const:F(),title:F()})),default:F().optional()}),phe=Ae([Ae([N({type:j(`string`),title:F().optional(),description:F().optional(),enum:M(F()),enumNames:M(F()).optional(),default:F().optional()}),Ae([dhe,fhe]),Ae([N({type:j(`array`),title:F().optional(),description:F().optional(),minItems:P().optional(),maxItems:P().optional(),items:N({type:j(`string`),enum:M(F())}),default:M(F()).optional()}),N({type:j(`array`),title:F().optional(),description:F().optional(),minItems:P().optional(),maxItems:P().optional(),items:N({anyOf:M(N({const:F(),title:F()}))}),default:M(F()).optional()})])]),che,lhe,uhe]),mhe=Ae([c1.extend({mode:j(`form`).optional(),message:F(),requestedSchema:N({type:j(`object`),properties:O(F(),phe),required:M(F()).optional()})}),c1.extend({mode:j(`url`),message:F(),elicitationId:F(),url:F().url()})]),hhe=l1.extend({method:j(`elicitation/create`),params:mhe}),ghe=u1.extend({elicitationId:F()}),_he=d1.extend({method:j(`notifications/elicitation/complete`),params:ghe}),g0=f1.extend({action:we([`accept`,`decline`,`cancel`]),content:ue(e=>e===null?void 0:e,O(F(),Ae([F(),P(),k(),M(F())])).optional())}),vhe=N({type:j(`ref/resource`),uri:F()}),yhe=N({type:j(`ref/prompt`),name:F()}),bhe=s1.extend({ref:Ae([yhe,vhe]),argument:N({name:F(),value:F()}),context:N({arguments:O(F(),F()).optional()}).optional()}),_0=l1.extend({method:j(`completion/complete`),params:bhe});function xhe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function She(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Che=f1.extend({completion:ce({values:M(F()).max(100),total:de(P().int()),hasMore:de(k())})}),whe=N({uri:F().startsWith(`file://`),name:F().optional(),_meta:O(F(),A()).optional()}),The=l1.extend({method:j(`roots/list`),params:s1.optional()}),v0=f1.extend({roots:M(whe)}),Ehe=d1.extend({method:j(`notifications/roots/list_changed`),params:u1.optional()});Ae([j1,O1,_0,f0,n0,t0,Z1,Q1,e0,Nme,Fme,u0,c0,R1,B1,V1,U1]),Ae([w1,M1,A1,Ehe,L1]),Ae([C1,m0,h0,g0,v0,z1,H1,I1]),Ae([j1,she,hhe,The,R1,B1,V1,U1]),Ae([w1,M1,ehe,Lme,jme,Zme,Kme,L1,_he]),Ae([C1,vme,Che,Gme,Bme,Dme,Ome,Ame,l0,Yme,z1,H1,I1]);var y0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===y1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Dhe(e.elicitations,n)}return new e(t,n,r)}},Dhe=class extends y0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(y1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function b0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Ohe=Symbol(`Let zodToJsonSchema decide on which parser to use`),x0={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},khe=e=>typeof e==`string`?{...x0,name:e}:{...x0,...e},Ahe=e=>{let t=khe(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function S0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function C0(e,t,n,r,i){e[t]=n,S0(e,t,r,i)}const w0=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function T0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?w0(t,e.currentPath):t.join(`/`)}}function jhe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=R0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&C0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&C0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(C0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),C0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Mhe(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function Nhe(){return{type:`boolean`}}function E0(e,t){return R0(e.type._def,t)}const Phe=(e,t)=>R0(e.innerType._def,t);function D0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>D0(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Fhe(e,t)}}const Fhe=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minimum`,r.value,r.message,t);break;case`max`:C0(n,`maximum`,r.value,r.message,t);break}return n};function Ihe(e,t){return{...R0(e.innerType._def,t),default:e.defaultValue()}}function Lhe(e,t){return t.effectStrategy===`input`?R0(e.schema._def,t):T0(t)}function Rhe(e){return{type:`string`,enum:Array.from(e.values)}}const zhe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Bhe(e,t){let n=[R0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),R0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(zhe(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Vhe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let O0;const k0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(O0===void 0&&(O0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),O0),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function A0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:M0(n,`email`,r.message,t);break;case`format:idn-email`:M0(n,`idn-email`,r.message,t);break;case`pattern:zod`:N0(n,k0.email,r.message,t);break}break;case`url`:M0(n,`uri`,r.message,t);break;case`uuid`:M0(n,`uuid`,r.message,t);break;case`regex`:N0(n,r.regex,r.message,t);break;case`cuid`:N0(n,k0.cuid,r.message,t);break;case`cuid2`:N0(n,k0.cuid2,r.message,t);break;case`startsWith`:N0(n,RegExp(`^${j0(r.value,t)}`),r.message,t);break;case`endsWith`:N0(n,RegExp(`${j0(r.value,t)}$`),r.message,t);break;case`datetime`:M0(n,`date-time`,r.message,t);break;case`date`:M0(n,`date`,r.message,t);break;case`time`:M0(n,`time`,r.message,t);break;case`duration`:M0(n,`duration`,r.message,t);break;case`length`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:N0(n,RegExp(j0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&M0(n,`ipv4`,r.message,t),r.version!==`v4`&&M0(n,`ipv6`,r.message,t);break;case`base64url`:N0(n,k0.base64url,r.message,t);break;case`jwt`:N0(n,k0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&N0(n,k0.ipv4Cidr,r.message,t),r.version!==`v4`&&N0(n,k0.ipv6Cidr,r.message,t);break;case`emoji`:N0(n,k0.emoji(),r.message,t);break;case`ulid`:N0(n,k0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:M0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:C0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:N0(n,k0.base64,r.message,t);break}break;case`nanoid`:N0(n,k0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function j0(e,t){return t.patternStrategy===`escape`?Uhe(e):e}const Hhe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Uhe(e){let t=``;for(let n=0;n<e.length;n++)Hhe.has(e[n])||(t+=`\\`),t+=e[n];return t}function M0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):C0(e,`format`,t,n,r)}function N0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:P0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):C0(e,`pattern`,P0(t,r),n,r)}function P0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1217
+ `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await Hn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let ac=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function oc(e){try{let t=Os(e.scope);if(!t)return;let n=vI(t);if(n.length===0)return;let r=wI(B(e.skillsRoot,e.name),e.name,t,n,`copy`,yI(e.scope));if(r.length===0)return;await YN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function sc(e,t){if(t.ok){J(e,200,co,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let cc=FX({contentDir:s,skillsHome:Zo,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:ts,parseFrontmatterDoc:Uo,attributeOkArtifactWrite:Vn,commitOkArtifactWrite:Hn,shadowHeadSha:rc,artifactWriterId:ac,effectiveInstallMode:ds,signalFiles:()=>D?.(`files`)}),lc=q(Lr,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await dO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??ID(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(iZ(t,p,`skill-import`))return;let m=await RD(p);r=m.cleanup,s=m.ref;let h=nO(m.dir);if(h.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>$D(e.dir)?.name===f)??h.find(e=>e.name===ct[f]);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??ec(d)}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await cc.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||aa(u))&&lI({source:u,skills:[d.body.name]},JF()),sc(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),uc=q(rr,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await dO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??ID(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(iZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??ec(d),f.kind===`well-known`)a=f,o=await jD(f.origin);else{let e=await RD(f);r=e.cleanup,c=e.ref,s=nO(e.dir)}}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await RD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof xD?`not-found`:`failed`,warnings:[],...e instanceof xD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>tO(e.dir)?.name===t)??s.find(e=>e.name===ct[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await cc.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){I(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){I(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||aa(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&lI({source:u,skills:e},JF())}J(t,200,nee,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),dc=8*1024*1024,fc=32*1024*1024;function pc(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=B(e,n);return r!==e&&!r.startsWith(e+Ql)?null:r}function mc(e){return new Promise((t,n)=>{let r;try{r=(0,Ak.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:dc}})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>fc){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function hc(e,t){return new Promise((n,r)=>{(0,jk.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=pc(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){hs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>dc){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>fc){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{hs(L(n),{recursive:!0}),ws(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function gc(e,t){let n=su(R(xu(),`ok-skill-upload-`)),r=()=>{try{ys(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=Xo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=sA({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},se);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await mc(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await hc(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=pc(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}hs(L(r),{recursive:!0}),ws(r,e.data)}let u=nO(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];sc(t,await cc.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let _c=q(jo,async(e,t,n)=>{try{let e=es(n.scope);if(!Yo(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Os(n.scope),i=B(e,n.name),a=n.scope===`project`?s:Zo,o=(n.scope===`project`?XI(s):ZI(Zo)).find(e=>e.name===n.name),c=o?B(a,o.dir):i;if(!V(c)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await wt(n.scope===`project`?`${z(a,c).split(Ql).join(`/`)}/SKILL`:Wn(n.scope,n.name));let l=_I(c,n.name);if(!l.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=$o.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:o.hosts.filter(za),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await $o.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(za),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await $o.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}D?.(`files`),J(t,200,wo,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:Zo;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Dr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||D?.(`files`),J(t,200,wo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:Zo;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await Dr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:Zo,s=await Dr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:c,canonicalHash:o.contentHash});if(!s.ok)switch(s.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(s.kind)}`)}D?.(`files`),J(t,200,wo,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?_r.filter(e=>f?.some(t=>t===e)):[..._r]:f===void 0?vI(r):_r.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?j:Zo,s=d===void 0?ds(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await $o.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}D?.(`files`),J(t,200,wo,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await $o.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:s,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),D?.(`files`),J(t,200,wo,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=hI(qN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&jI(n.name,r,v,yI(n.scope));let y=R(r,...zD),b=V(y)?H(y,`utf-8`):null,x=b===null?null:UD(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=wI(c,n.name,r,h,C,yI(n.scope));w.length===0?await XN(r,n.name):await YN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),D?.(`files`),J(t,200,wo,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),vc=q(Ro,async(e,t,n)=>{try{if(!Yo(n.name,t,`skill-uninstall`))return;let e=Os(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await ks(e,n.name,n.scope);D?.(`files`),J(t,200,qe,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),yc=mU({GET:q(Yn,async(e,t)=>{try{let e=vI(j??``),n=(e,t)=>{let n=GX(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,It,{targets:e,configured:!1,folders:[...j?IX(s,WI(s,`project`)).map(e=>({...e,scope:`project`,...n(s,e)})):[],...IX(Zo,WI(Zo,`global`)).map(e=>({...e,scope:`global`,...n(Zo,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(see,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?s:Zo;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await KX(r,i.join(`/`)),D?.(`files`),J(t,200,Fn,{targets:vI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(WI(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?BX({base:r,folderRel:e.root,targetRootRel:a}):VX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await WX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),D?.(`files`),J(t,200,Fn,{targets:vI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),bc=q(Qi,async(e,t,n)=>{try{let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Yo(n.name,t,`skill-restore`)||Cs(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=S?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await sZ({shadow:r,contentDir:s,contentRoot:te??`.`,name:n.name,version:n.version,skillDirRel:fs(n.name)});if(!i.ok){ls(t,i,`skill-restore`);return}let a=[],o=_I(B(s,fs(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),Vn(e,Rn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Hn(`skill-restore`),D?.(`files`),J(t,200,nn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),xc=q(ia,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Yo(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Zo:s,{root:a,dirRel:o,realDir:c}=Fs(n.scope,n.name),l=!o.startsWith(`${ii}/`);if(c===null||!V(B(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=R(n.scope===`global`?Zo:j,...zD),d=tc(u).skills[n.name];if(!d){let e=KD(n.name,tO(B(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:$fe(B(a,n.name))})??bs(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await uq(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),J(t,200,Be,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=ct[e],a=await dO(d.source,e).catch(async e=>{if(i===void 0)throw e;return dO(d.source,i)}),o=a?.source??XO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??ID(o);if(!c){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(iZ(t,c,`skill-reimport`))return;let l=await RD(c);r=l.cleanup,f=l.ref;let u=nO(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>tO(e.dir)?.name===n.name)??u.find(e=>e.name===ct[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=eO(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=tO(m.dir)}catch(e){if(e instanceof xD){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=PX(p);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=tO(B(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){J(t,200,Be,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Uo(p.skillMd).body;if(n.dryRun){let e=tO(B(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=zs({baseDir:j,timeout:{block:15e3}}),t=z(j,B(a,n.name)).split(Ql).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}J(t,200,Be,{name:n.name,updated:!0,source:d.source,localBody:Uo(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await Yt(e,`deleted-upstream`)}let x=Jj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=Zj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:NX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Qj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(Vn(e,Rn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await Hn(`skill-reimport`));let C=nc(a,n.name),w=n.scope===`project`?await rc(ac(e),o):void 0;await uq(u,e=>WD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await oc({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),D?.(`files`),J(t,200,Be,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Sc=q(un,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=sA(n,se);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Yo(n.name,t,`skill-revert`)||Cs(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=R(j,...zD),i=tc(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=S?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await sZ({shadow:a,contentDir:s,contentRoot:te??`.`,name:n.name,version:i.baselineRef,skillDirRel:fs(n.name)});if(!o.ok){ls(t,o,`skill-revert`);return}Vn(e,Rn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Hn(`skill-revert`);let c=B(s,fs(n.name),`..`),l=nc(c,n.name);await uq(r,e=>WD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),c===es(`project`)&&await oc({skillsRoot:c,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),D?.(`files`),J(t,200,Sn,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Cc(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function wc(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Tc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Ec(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Dc=jX({contentDir:s,projectDir:j,getAllFilesIndex:f,getFileIndexGeneration:m,getSearchMaxEntries:ope,semanticSearch:xe,getSemanticSimilarityFloor:Se,ready:ge,getProjectSkillsRoot:()=>es(`project`),parseFrontmatterDoc:Uo});Dc.prewarm();let Oc=mU({GET:q(Yn,aB(async(e,t)=>{let n=Zee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Cc(n.get(`intent`)),o=Es(n.get(`ranking`)),s=wc(n.get(`scope`)??n.get(`scopes`)),c=Tc(n.get(`semantic`)),l=Ec(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,Ta,await Dc.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(Jee,aB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Cc(n.intent),a=Es(n.ranking),o=wc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Tc(n.semantic),l=Ec(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,Ta,await Dc.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),kc=q(Yn,aB(async(e,t)=>{J(t,200,yee,{...await oI(vu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Ac(e,t){if(r(e,t,{handler:`handoff`}))try{await wue(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:rt.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:rS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function jc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await kN(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:rS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Mc=q(En,async(e,t,n)=>{try{if(!j){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Nde(e,n.kind)){_F(`invalid-path`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`invalid-path`},{handler:gF});return}let r=Rde(j);if(r===null){if(xF(j).kind===`no-remote`){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}_F(`detached-head`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`detached-head`},{handler:gF});return}let i=xF(j);if(i.kind===`no-remote`){_F(`no-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`no-remote`},{handler:gF});return}if(i.kind===`non-github`){_F(`non-github-remote`,{kind:n.kind}),J(t,200,je,{ok:!1,error:`non-github-remote`},{handler:gF});return}if(!Ude(j,r)){_F(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,je,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:gF});return}let a=cQ(j,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&I(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=Pde(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=Fde(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Ju(c)}`,u=await Ide(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);_F(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,je,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:gF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:gF,cause:e})}},{handler:gF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:gF})}),Nc=q(Yn,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Az});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!to(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Az});return}if(!Oz(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Az});return}J(t,200,xr,await kz(j,r,i,a),{handler:Az})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Az,cause:e})}},{handler:Az,method:`GET`,skipBodyParse:!0}),Pc=q(Kr,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:NF});return}if(!Oz(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:NF});return}let e=cQ(j,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,Aee,await Zde(j,n.branch,r,n.kind),{handler:NF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NF,cause:e})}},{handler:NF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:NF})}),Fc=q(mr,async(e,t,n)=>{if(sA(n,se).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:Fz});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Fz});return}try{J(t,200,Or,await Bs(()=>Lz(j,n.branch,{fastForward:n.fastForward===!0})),{handler:Fz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Fz,cause:e})}},{handler:Fz,method:`POST`});async function Ic(e){let[t,...n]=ie,r=[...n,...e];return await new Promise((e,n)=>{let i=Ul(t,r,xN({...Bi,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},EF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${EF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=MF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Lc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:CF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ic([`share`,`owners`,`--json`]),n=Wde(kF(e));jF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,Dee,n,{handler:CF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CF,cause:e})}finally{Pe.release(`/api/share/publish/owners`)}},{handler:CF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:CF})}),Rc=q(Yn,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!OF(r)||!DF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:wF});return}if(!Pe.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:wF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Ic([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Gde(kF(e));jF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Yee,n,{handler:wF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:wF,cause:e})}finally{Pe.release(`/api/share/publish/name-check`)}},{handler:wF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:wF})}),zc=q(Uee,async(e,t,n)=>{if(!j){jF(`publish-create`,`no-project`),J(t,200,Gi,{ok:!1,error:`no-project`},{handler:TF});return}if(!OF(n.owner)||!DF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:TF});return}if(!Pe.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:TF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Ic(e),i=Jde(kF(r));jF(`publish-create`,i.ok?`ok`:i.error),i.ok&&A?.()?.refreshRemote().catch(()=>{}),J(t,200,Gi,i,{handler:TF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:TF,cause:e})}finally{Pe.release(`/api/share/publish`)}},{handler:TF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:TF})}),Bc=q(ln,async(e,t,n)=>{try{let e=I(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,uee,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Vc=j?PA(j):null;async function Hc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Bse(e.headers),previewUrl:null,port:Vc?Qs(Vc)?.port??0:0,singleFile:Oe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,Ge,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function Uc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Me?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,he,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let Wc=`local-op-embeddings-set-key`,Gc=`local-op-embeddings-clear-key`,Kc=`/api/local-op/embeddings`;function qc(){let e=Te?.();return{projectDir:j??s,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let Jc=q(qee,async(e,t,n)=>{if(!Pe.tryAcquire(Kc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Wc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=qc();await new UM(Ce).setForProject(e,r,n.key),xe?.reloadCredential(),J(t,200,pi,{keyPresent:!0},{handler:Wc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Wc,cause:e})}finally{Pe.release(Kc)}},{handler:Wc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Wc})}),Yc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(Kc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Gc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=qc();await new UM(Ce).clearForProject(e,n),xe?.reloadCredential(),J(t,200,pi,{keyPresent:!1},{handler:Gc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Gc,cause:e})}finally{Pe.release(Kc)}},{handler:Gc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Gc})}),Xc=`local-op-embeddings-test`,Zc=`/api/local-op/embeddings/test`,Qc=q(Yn,async(e,t)=>{if(!Pe.tryAcquire(Zc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Xc,extraHeaders:{"Retry-After":`5`}});return}try{let e=Te?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await IM(new UM(Ce),j??s,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Fle({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,Eee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Xc,cause:e})}finally{Pe.release(Zc)}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Xc})}),$c=q(Yn,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(xe){let t=xe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Te?.()?.baseUrl??`https://api.openai.com/v1`,o=await IM(new UM(Ce),j??s,a),c=o.apiKey!==null,u=!c&&o.keyless,d=c?o.source:null,f=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of l())!Kx(e)&&!qx(e)&&!li(e)&&(p+=1);J(t,200,Hee,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),el=0;function tl(){el+=1,D?.(`lint-config`)}let nl=()=>`${el} ${t.getActiveBranch()}`;async function rl(e,t){let n=Ee?.()??ho;try{let r=await Ra(e,$P(s,n,{docName:t,projectDir:j??s,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=De?.()??`warning`;if(E&&a!==`off`&&!Qx(t)){await Lt(t,e,`lint-validation`);let r=fF({projectDir:j??s,contentDir:s,baseConfig:n,derivedDocumentIndex:E,linksValidation:a,admittedDocNames:Mt,docFilePathFor:e=>aQ(s,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:aQ(s,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function il(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=nF({projectDir:j??s,contentDir:s});return TP(t.schemas,n)}let al=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!gQ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Ee?.()??ho,i=[],a=XP(s,n??void 0,e=>i.push(e)),o=QP(j??s,ZP(r,a),e=>i.push(e));n===null&&i.push(...il(o)),J(t,200,Oi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),ol=q(vee,async(e,t,n)=>{let r;try{r=dF(B(s),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}tl();try{let e=Ee?.()??ho,n=[],r=XP(s,void 0,e=>n.push(e)),i=QP(j??s,ZP(e,r),e=>n.push(e));n.push(...il(i)),J(t,200,Oi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),sl=q(Mee,async(e,t,n)=>{let r;try{let e=B(j??s),t=n.parentPath??[];r=n.delete?bde(e,n.file):n.field!==void 0&&n.removeField?vde(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?yde(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?gde(e,n.file,n.field,n.constraint,t):_de(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&D?.(`files`),tl();try{let e=Ee?.()??ho,n=[],r=XP(s,void 0,e=>n.push(e)),i=QP(j??s,ZP(e,r),e=>n.push(e));n.push(...il(i)),J(t,200,Oi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),cl=q(Yn,async(e,t)=>{try{let e=B(j??s),{schemas:n,truncated:r}=Gue(e),i=new Set(n),a=!1;if(fe!==void 0){let t=YZ({contentDir:s,contentFilter:fe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Qa(a)){let t=z(e,B(s,a));!t.startsWith(`..`)&&!Yl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,ga,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),ll=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},ul=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!gQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=aQ(s,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Ee?.()??ho,a=[],o=await tF({projectDir:j??s,contentDir:s,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:ll});J(t,200,Fr,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof mN){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),dl=new xP,fl=rZ();function pl(e,t,n){let r=`${n} ${nl()} ${t??``}`;return fl.run(r,()=>wde(e,{targetPath:t})).promise}function ml(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let hl=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!XZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Ee?.()??ho;J(t,200,Fi,await rF({projectDir:j??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:ll,cache:dl,auditGeneration:nl}),{handler:`lint-audit`})}catch(e){if(e instanceof eF){ml(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),gl=q(Yn,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!XZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!XZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=aQ(s,o)??`${o}.md`}let c=Ee?.()??ho,l=await pl(fF({projectDir:j??s,contentDir:s,baseConfig:c,liveSourceFor:ll,derivedDocumentIndex:E??null,linksValidation:De?.(),admittedDocNames:Mt,docFilePathFor:e=>aQ(s,e),cache:dl,auditGeneration:nl}),i,xP.fingerprintConfig(c));if(n.searchParams.get(`counts`)===`1`){J(t,200,So,Cde(l),{handler:`audit`});return}J(t,200,zn,l,{handler:`audit`})}catch(e){if(e instanceof eF){ml(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),_l=q(oo,async(t,n,r)=>{try{let t=QZ(r.docName,n,`lint-fix`);if(t===null)return;let i=vt(t),a=sA(r,se);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?c:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Kx(i)||qx(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=aQ(s,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}yN(B(s,f),s);let p=Ee?.()??ho,{stored:m}=Dn(a.summary),h=await o.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await fde({projectDir:j??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=oi(d),n=ei[t]??la(u??c);O?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{Bw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,Rw(h))},h.origin),a.kind!==`anonymous`&&_M(i,c,l,u,void 0,a.kind===`agent`?Cn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{O?.touchMode(c,`idle`)}let t=await wt(i);if(t?.kind===`failure`){Et(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Dt(n,`lint-fix`);return}Ct(i,`lint-fix`);try{b=await Ra(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,ko,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof mN){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof dS){fS(n,e,`lint-fix`);return}if(e instanceof gS){vS(n,e,`lint-fix`);return}if(e instanceof Xw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),vl=`link-preview`,yl=new xW({cacheDir:Oe?null:B(j??s,`.ok`,`local`,`link-previews`)}),bl=null,xl=()=>(bl??=yl.init(),bl),Sl=ke??fW;async function Cl(e){let t=await Sl(e);return t.ok?{ok:!0,metadata:await _W({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Sl})}:{ok:!1,reason:t.reason}}let wl=()=>{try{return Ae?.()===!0}catch{return!1}},Tl=q($a,async(e,t,n)=>{try{if(!wl()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,ci,{ok:!1,reason:`disabled`},{handler:vl});return}await xl();let e=!1,r=await yl.load(n.url,()=>(e=!0,Cl(n.url)));yl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,ci,i,{handler:vl})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vl,cause:e})}},{handler:vl,method:`POST`,preBodyGate:(e,t)=>{let n=wW({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:vl}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:vl}),!1)}}),El=Zse({service:at,getPrincipal:se,onChanged:()=>D?.(`comments`)}),Dl=mU({GET:El.list,POST:El.create},{handler:`comments`}),Ol=mU({GET:El.read,POST:El.mutate,DELETE:El.remove},{handler:`comment`}),{handleSkillsSearch:kl,handleSkillsPopular:Al,handleSkillsDetail:jl,handleSkillsPreview:Ml,handleSkillsDiscover:Nl,handleSkillsResolveRef:Pl}=dZ({log:X,skillsHome:Zo,projectDir:j,contentDir:s,resolveSkillDirForRead:ts}),Fl={"/api/config":Hc,"/api/config/diagnostics":Uc,"/api/comments":Dl,"/api/comment":Ol,"/api/asset":si,"/api/asset-text":di,"/api/document":Qn,"/api/documents":$n,"/api/comment-counts":tr,"/api/link-preview":Tl,"/api/orphans":nr,"/api/hubs":ir,"/api/pages":Di,"/api/folder-config":Io,"/api/template":qo,"/api/template/import":Jo,"/api/templates":Ho,"/api/skill":Ws,"/api/skill-file":Zs,"/api/skill-file/rename":$s,"/api/skills":js,"/api/skills/installed":er,"/api/skills/search":kl,"/api/skills/popular":Al,"/api/skills/detail":jl,"/api/skills/preview":Ml,"/api/skills/discover":Nl,"/api/skills/resolve-ref":Pl,"/api/skill/import":lc,"/api/skills/import-bulk":uc,"/api/skill/edit-external":Vs,"/api/skill/duplicate":Us,"/api/skill/move-scope":Hs,"/api/skill-upload":gc,"/api/skill/install":_c,"/api/skill/uninstall":vc,"/api/skill/restore":bc,"/api/skill/reimport":xc,"/api/skill/revert":Sc,"/api/skill-targets":yc,"/api/search":Oc,"/api/semantic-status":$c,"/api/lint/config":al,"/api/lint/markdownlint-config":ol,"/api/lint/frontmatter-schema":sl,"/api/lint/frontmatter-schemas":cl,"/api/lint":ul,"/api/lint/audit":hl,"/api/lint/fix":_l,"/api/audit":gl,"/api/page-headings":bi,"/api/create-page":hi,"/api/create-folder":vi,"/api/duplicate-path":yi,"/api/rename-path":Ci,"/api/delete-path":Ti,"/api/trash/cleanup":Ei,"/api/upload":Mi,"/api/agent-write":Gn,"/api/agent-write-md":Kn,"/api/agent-write-batch":qn,"/api/frontmatter-patch":Xn,"/api/agent-patch":or,"/api/agent-undo":sr,"/api/agent-activity":ur,"/api/agent-burst-diff":dr,"/api/save-version":kr,"/api/history":jr,"/api/rollback":Br,"/api/metrics/reconciliation":Vr,"/api/metrics/parse-health":Hr,"/api/metrics/agent-presence":Xr,"/api/metrics/agent-effects":Zr,"/api/metrics/watcher-recent":$r,"/api/__embed-detect":ti,"/api/server-info":Ur,"/api/acp/catalog":Jr,"/api/share/construct-url":Mc,"/api/share/target-status":Pc,"/api/git/branch-info":Nc,"/api/git/checkout":Fc,"/api/share/publish/owners":Lc,"/api/share/publish/name-check":Rc,"/api/share/publish":zc,"/api/principal":Yr,"/api/rescue":fi,"/api/workspace":ni,"/api/sync/status":Xa,"/api/sync/trigger":Za,"/api/sync/conflicts":io,"/api/sync/conflict-content":po,"/api/sync/resolve-conflict":fo,"/api/local-op/clone":Ji,"/api/local-op/ok-init":ea,"/api/local-op/auth/login":Oa,"/api/local-op/auth/status":Ia,"/api/local-op/auth/pat":Ba,"/api/local-op/auth/gh-login":ja,"/api/local-op/auth/cancel":Na,"/api/local-op/auth/repos":Ha,"/api/local-op/auth/signout":Ga,"/api/local-op/auth/set-identity":Ja,"/api/local-op/embeddings/set-key":Jc,"/api/local-op/embeddings/clear-key":Yc,"/api/local-op/embeddings/test":Qc,"/api/installed-agents":Eo,"/api/spawn-cursor":jc,"/api/handoff":Ac,"/api/install-skill":xo,"/api/skill/install-state":kc,"/api/seed/plan":go,"/api/seed/apply":yo,"/api/seed/packs":bo,"/api/client-logs":Bc};x&&(Fl[`/api/test-reset`]=hr,Fl[`/api/test-flush-git`]=pr,Fl[`/api/test-rescan-backlinks`]=Sr,Fl[`/api/test-rescan-files`]=wr);let Il=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Ll=[`/api/local-op/`],Rl=iB({log:X,remotePublicHost:n,ephemeral:Oe,table:{resolve(e){let t=Fl[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await Rr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>Il.has(e)||Ll.some(t=>e.startsWith(t))}}),zl=pU({hocuspocus:a,derivedDocumentIndex:E,getFileIndex:l,isSafeDocName:gQ,readPageTitleForDocName:ot,readPageTitleForLinkedDocName:dt,readFrontmatterMetadataForLinkedDocName:gt,collectAdmittedDocNames:Mt,resolveAlias:vt,respondToDerivedIndexQueryFailure:zt});return BH(zl.paths,Fl),{priority:100,async onRequest({request:e,response:t}){await Rl(e,t)},nativeApi:{paths:zl.paths,dispatch:iB({log:X,remotePublicHost:n,ephemeral:Oe,table:zl.table})}}}function vQ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a}=e;return(e,o,s)=>{let c;try{c=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return s()}let l=Jl(c).slice(1).toLowerCase(),u=l===`md`||l===`mdx`;if(!c||t.isPathIgnored(c)||!u&&!i.has(l))return s();o.setHeader(`X-Content-Type-Options`,`nosniff`);let d=uX(l,r);u||o.setHeader(`Content-Disposition`,d.disposition),d.csp!==null&&o.setHeader(`Content-Security-Policy`,d.csp),d.sandboxedHtml&&o.setHeader(`Cache-Control`,`no-store`),n(e,o,()=>{if(o.headersSent)return;let e=te.has(l);if(!e&&(i.has(l)||a.has(l))){o.statusCode=404,o.end();return}e&&(o.removeHeader(`Content-Security-Policy`),o.removeHeader(`Content-Disposition`),o.removeHeader(`X-Content-Type-Options`),o.removeHeader(`Cache-Control`)),s()})}}function yQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Spe(e){let t;try{t=lu(e.contentDir,{withFileTypes:!0})}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Fx(n.name,c)&&e.basenameIndex.add(n.name)}async function bQ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Eu(i,{withFileTypes:!0})}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=R(i,o.name),s=Vk(z(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await wu(a)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Du(a)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Hk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Ou(i)}catch(t){let n=yQ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Fx(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Fx(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const xQ=N({principalId:F().optional(),tabSessionId:F().optional(),expectedServerInstanceId:F().optional(),expectedBranch:F().optional(),expectedDocLineageEpoch:F().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:F().optional(),clientKind:F().optional()}).loose(),SQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function CQ(e){return SQ.includes(e)}function wQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Cpe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!CQ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var TQ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=wQ(e,this.payload)}};function EQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=xQ.safeParse(t);return n.success?n.data:void 0}var DQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const OQ=I(`conflict-storage`);var kQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=R(PA(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!V(this.storePath)){this.conflicts=[];return}try{let e=H(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){OQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){OQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=L(this.storePath);V(e)||ou(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return gu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return OQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-o1JfXOwU.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=B(this.projectDir),r=B(t,e);if(!Hk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);eL(r,t),ws(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),OQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await zb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){OQ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),OQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=B(this.projectDir),a=B(i,e.file);if(!Hk(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(eL(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-o1JfXOwU.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);eL(a,i),ws(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);ws(a,n,`utf-8`);break;case`delete`:V(a)&&us(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function wpe(e,t){let n=e instanceof Error?{name:e.name,message:e.message,stack:e.stack??null}:{name:`NonError`,message:String(e),stack:null};return{timestamp:new Date().toISOString(),origin:t,error:n,pid:process.pid,uptimeSec:Math.round(process.uptime()*1e3)/1e3}}function Tpe(e,t){let n=PA(e);try{ou(n,{recursive:!0}),gu(R(n,Dr),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Ps(e);ou(L(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};gu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const AQ=new Map;let jQ=!1;function Epe(e,t){try{let n=wpe(e,t);for(let e of AQ.keys())Tpe(e,n)}catch{}}function Dpe(e){AQ.set(e,(AQ.get(e)??0)+1),jQ||(jQ=!0,process.on(`uncaughtExceptionMonitor`,Epe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=AQ.get(e)??0;n<=1?AQ.delete(e):AQ.set(e,n-1)}}}function MQ(e){let t=e.scheduler??ai,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function NQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function PQ(e){if(!V(e))return{};let t;try{t=(0,kk.parse)(H(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!NQ(t))return{};let n=t.telemetry;if(!NQ(n))return{};let r=n.localSink;return NQ(r)?r:{}}function FQ(e){return typeof e==`boolean`?e:void 0}function Ope(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function IQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function LQ(e){if(NQ(e))return Ope(e.maxBytes)}function kpe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=PQ(ts(`project`,e.projectDir)),n=PQ(ts(`project-local`,e.projectDir));if((FQ(n.enabled)??FQ(t.enabled)??!0)===!1)return null;let r=LQ(n.spans)??LQ(t.spans)??52428800,i=LQ(n.logs)??LQ(t.logs)??26214400,a=IQ(n.attributeDenylist)??IQ(t.attributeDenylist)??Ee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var RQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(RQ||={});var Ape;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Ape||={});const zQ=RQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),BQ=e=>{switch(typeof e){case`undefined`:return zQ.undefined;case`string`:return zQ.string;case`number`:return Number.isNaN(e)?zQ.nan:zQ.number;case`boolean`:return zQ.boolean;case`function`:return zQ.function;case`bigint`:return zQ.bigint;case`symbol`:return zQ.symbol;case`object`:return Array.isArray(e)?zQ.array:e===null?zQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?zQ.promise:typeof Map<`u`&&e instanceof Map?zQ.map:typeof Set<`u`&&e instanceof Set?zQ.set:typeof Date<`u`&&e instanceof Date?zQ.date:zQ.object;default:return zQ.unknown}},Z=RQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var VQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,RQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};VQ.create=e=>new VQ(e);const HQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===zQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,RQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${RQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${RQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${RQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:RQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,RQ.assertNever(e)}return{message:n}};let jpe=HQ;function UQ(){return jpe}const WQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function GQ(e,t){let n=UQ(),r=WQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===HQ?void 0:HQ].filter(e=>!!e)});e.common.issues.push(r)}var KQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return qQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return qQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const qQ=Object.freeze({status:`aborted`}),JQ=e=>({status:`dirty`,value:e}),YQ=e=>({status:`valid`,value:e}),XQ=e=>e.status===`aborted`,ZQ=e=>e.status===`dirty`,QQ=e=>e.status===`valid`,$Q=e=>typeof Promise<`u`&&e instanceof Promise;var e$;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(e$||={});var t$=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const n$=(e,t)=>{if(QQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new VQ(e.common.issues);return this._error=t,this._error}}};function r$(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var i$=class{get description(){return this._def.description}_getType(e){return BQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:BQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new KQ,ctx:{common:e.parent.common,data:e.data,parsedType:BQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if($Q(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)};return n$(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return QQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>QQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:BQ(e)},r=this._parse({data:e,path:n.path,parent:n});return n$(n,await($Q(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new I$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return L$.create(this,this._def)}nullable(){return R$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return b$.create(this)}promise(){return F$.create(this,this._def)}or(e){return C$.create([this,e],this._def)}and(e){return E$.create(this,e,this._def)}transform(e){return new I$({...r$(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new z$({...r$(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new H$({typeName:Q.ZodBranded,type:this,...r$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new B$({...r$(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return U$.create(this,e)}readonly(){return W$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Mpe=/^c[^\s-]{8,}$/i,Npe=/^[0-9a-z]+$/,Ppe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fpe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ipe=/^[a-z0-9_-]{21}$/i,Lpe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rpe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zpe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let a$;const Bpe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Vpe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Hpe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Upe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Wpe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gpe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,o$=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Kpe=RegExp(`^${o$}$`);function s$(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function qpe(e){return RegExp(`^${s$(e)}$`)}function Jpe(e){let t=`${o$}T${s$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Ype(e,t){return!!((t===`v4`||!t)&&Bpe.test(e)||(t===`v6`||!t)&&Hpe.test(e))}function Xpe(e,t){if(!Lpe.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function Zpe(e,t){return!!((t===`v4`||!t)&&Vpe.test(e)||(t===`v6`||!t)&&Upe.test(e))}var c$=class e extends i${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==zQ.string){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.string,received:t.parsedType}),qQ}let t=new KQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?GQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&GQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)zpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)a$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),a$.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Fpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Ipe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Mpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Npe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Ppe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),GQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Jpe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Kpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?qpe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Rpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Ype(e.data,r.version)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Xpe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Zpe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gpe.test(e.data)||(n=this._getOrReturnCtx(e,n),GQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):RQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...e$.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...e$.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...e$.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...e$.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...e$.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...e$.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...e$.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...e$.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...e$.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...e$.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...e$.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...e$.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...e$.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...e$.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...e$.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...e$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...e$.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...e$.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...e$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...e$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...e$.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...e$.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...e$.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...e$.errToObj(t)})}nonempty(e){return this.min(1,e$.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};c$.create=e=>new c$({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...r$(e)});function Qpe(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var l$=class e extends i${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==zQ.number){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.number,received:t.parsedType}),qQ}let t,n=new KQ;for(let r of this._def.checks)r.kind===`int`?RQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Qpe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):RQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,e$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,e$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,e$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,e$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:e$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:e$.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:e$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:e$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:e$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:e$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:e$.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:e$.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:e$.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:e$.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&RQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};l$.create=e=>new l$({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...r$(e)});var u$=class e extends i${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==zQ.bigint)return this._getInvalidInput(e);let t,n=new KQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),GQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):RQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.bigint,received:t.parsedType}),qQ}gte(e,t){return this.setLimit(`min`,e,!0,e$.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,e$.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,e$.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,e$.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:e$.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:e$.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:e$.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:e$.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:e$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:e$.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};u$.create=e=>new u$({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...r$(e)});var d$=class extends i${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==zQ.boolean){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.boolean,received:t.parsedType}),qQ}return YQ(e.data)}};d$.create=e=>new d$({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...r$(e)});var f$=class e extends i${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==zQ.date){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.date,received:t.parsedType}),qQ}if(Number.isNaN(e.data.getTime()))return GQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),qQ;let t=new KQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),GQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):RQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:e$.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:e$.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};f$.create=e=>new f$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...r$(e)});var p$=class extends i${_parse(e){if(this._getType(e)!==zQ.symbol){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.symbol,received:t.parsedType}),qQ}return YQ(e.data)}};p$.create=e=>new p$({typeName:Q.ZodSymbol,...r$(e)});var m$=class extends i${_parse(e){if(this._getType(e)!==zQ.undefined){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.undefined,received:t.parsedType}),qQ}return YQ(e.data)}};m$.create=e=>new m$({typeName:Q.ZodUndefined,...r$(e)});var h$=class extends i${_parse(e){if(this._getType(e)!==zQ.null){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.null,received:t.parsedType}),qQ}return YQ(e.data)}};h$.create=e=>new h$({typeName:Q.ZodNull,...r$(e)});var g$=class extends i${constructor(){super(...arguments),this._any=!0}_parse(e){return YQ(e.data)}};g$.create=e=>new g$({typeName:Q.ZodAny,...r$(e)});var _$=class extends i${constructor(){super(...arguments),this._unknown=!0}_parse(e){return YQ(e.data)}};_$.create=e=>new _$({typeName:Q.ZodUnknown,...r$(e)});var v$=class extends i${_parse(e){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.never,received:t.parsedType}),qQ}};v$.create=e=>new v$({typeName:Q.ZodNever,...r$(e)});var y$=class extends i${_parse(e){if(this._getType(e)!==zQ.undefined){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.void,received:t.parsedType}),qQ}return YQ(e.data)}};y$.create=e=>new y$({typeName:Q.ZodVoid,...r$(e)});var b$=class e extends i${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==zQ.array)return GQ(t,{code:Z.invalid_type,expected:zQ.array,received:t.parsedType}),qQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(GQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(GQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(GQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new t$(t,e,t.path,n)))).then(e=>KQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new t$(t,e,t.path,n)));return KQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:e$.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:e$.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:e$.toString(n)}})}nonempty(e){return this.min(1,e)}};b$.create=(e,t)=>new b$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...r$(t)});function x$(e){if(e instanceof S$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=L$.create(x$(r))}return new S$({...e._def,shape:()=>t})}else if(e instanceof b$)return new b$({...e._def,type:x$(e.element)});else if(e instanceof L$)return L$.create(x$(e.unwrap()));else if(e instanceof R$)return R$.create(x$(e.unwrap()));else if(e instanceof D$)return D$.create(e.items.map(e=>x$(e)));else return e}var S$=class e extends i${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=RQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==zQ.object){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.object,received:t.parsedType}),qQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof v$&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new t$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof v$){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(GQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new t$(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>KQ.mergeObjectSync(t,e)):KQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return e$.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:e$.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of RQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of RQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return x$(this)}partial(t){let n={};for(let e of RQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of RQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof L$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return M$(RQ.objectKeys(this.shape))}};S$.create=(e,t)=>new S$({shape:()=>e,unknownKeys:`strip`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)}),S$.strictCreate=(e,t)=>new S$({shape:()=>e,unknownKeys:`strict`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)}),S$.lazycreate=(e,t)=>new S$({shape:e,unknownKeys:`strip`,catchall:v$.create(),typeName:Q.ZodObject,...r$(t)});var C$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new VQ(e.ctx.common.issues));return GQ(t,{code:Z.invalid_union,unionErrors:n}),qQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new VQ(e));return GQ(t,{code:Z.invalid_union,unionErrors:i}),qQ}}get options(){return this._def.options}};C$.create=(e,t)=>new C$({options:e,typeName:Q.ZodUnion,...r$(t)});const w$=e=>e instanceof A$?w$(e.schema):e instanceof I$?w$(e.innerType()):e instanceof j$?[e.value]:e instanceof N$?e.options:e instanceof P$?RQ.objectValues(e.enum):e instanceof z$?w$(e._def.innerType):e instanceof m$?[void 0]:e instanceof h$?[null]:e instanceof L$?[void 0,...w$(e.unwrap())]:e instanceof R$?[null,...w$(e.unwrap())]:e instanceof H$||e instanceof W$?w$(e.unwrap()):e instanceof B$?w$(e._def.innerType):[];var $pe=class e extends i${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==zQ.object)return GQ(t,{code:Z.invalid_type,expected:zQ.object,received:t.parsedType}),qQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(GQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),qQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=w$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...r$(r)})}};function T$(e,t){let n=BQ(e),r=BQ(t);if(e===t)return{valid:!0,data:e};if(n===zQ.object&&r===zQ.object){let n=RQ.objectKeys(t),r=RQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=T$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===zQ.array&&r===zQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=T$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===zQ.date&&r===zQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var E$=class extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(XQ(e)||XQ(r))return qQ;let i=T$(e.value,r.value);return i.valid?((ZQ(e)||ZQ(r))&&t.dirty(),{status:t.value,value:i.data}):(GQ(n,{code:Z.invalid_intersection_types}),qQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};E$.create=(e,t,n)=>new E$({left:e,right:t,typeName:Q.ZodIntersection,...r$(n)});var D$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.array)return GQ(n,{code:Z.invalid_type,expected:zQ.array,received:n.parsedType}),qQ;if(n.data.length<this._def.items.length)return GQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),qQ;!this._def.rest&&n.data.length>this._def.items.length&&(GQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new t$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>KQ.mergeArray(t,e)):KQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};D$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new D$({items:e,typeName:Q.ZodTuple,rest:null,...r$(t)})};var eme=class e extends i${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.object)return GQ(n,{code:Z.invalid_type,expected:zQ.object,received:n.parsedType}),qQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new t$(n,e,n.path,e)),value:a._parse(new t$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?KQ.mergeObjectAsync(t,r):KQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof i$?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...r$(r)}):new e({keyType:c$.create(),valueType:t,typeName:Q.ZodRecord,...r$(n)})}},O$=class extends i${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.map)return GQ(n,{code:Z.invalid_type,expected:zQ.map,received:n.parsedType}),qQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new t$(n,e,n.path,[a,`key`])),value:i._parse(new t$(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return qQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return qQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};O$.create=(e,t,n)=>new O$({valueType:t,keyType:e,typeName:Q.ZodMap,...r$(n)});var k$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==zQ.set)return GQ(n,{code:Z.invalid_type,expected:zQ.set,received:n.parsedType}),qQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(GQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(GQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return qQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new t$(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:e$.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:e$.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};k$.create=(e,t)=>new k$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...r$(t)});var tme=class e extends i${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==zQ.function)return GQ(t,{code:Z.invalid_type,expected:zQ.function,received:t.parsedType}),qQ;function n(e,n){return WQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,UQ(),HQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return WQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,UQ(),HQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof F$){let e=this;return YQ(async function(...t){let o=new VQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return YQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new VQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new VQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:D$.create(t).rest(_$.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||D$.create([]).rest(_$.create()),returns:n||_$.create(),typeName:Q.ZodFunction,...r$(r)})}},A$=class extends i${get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};A$.create=(e,t)=>new A$({getter:e,typeName:Q.ZodLazy,...r$(t)});var j$=class extends i${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return GQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),qQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};j$.create=(e,t)=>new j$({value:e,typeName:Q.ZodLiteral,...r$(t)});function M$(e,t){return new N$({values:e,typeName:Q.ZodEnum,...r$(t)})}var N$=class e extends i${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return GQ(t,{expected:RQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),qQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return GQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),qQ}return YQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};N$.create=M$;var P$=class extends i${_parse(e){let t=RQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==zQ.string&&n.parsedType!==zQ.number){let e=RQ.objectValues(t);return GQ(n,{expected:RQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),qQ}if(this._cache||=new Set(RQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=RQ.objectValues(t);return GQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),qQ}return YQ(e.data)}get enum(){return this._def.values}};P$.create=(e,t)=>new P$({values:e,typeName:Q.ZodNativeEnum,...r$(t)});var F$=class extends i${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==zQ.promise&&t.common.async===!1?(GQ(t,{code:Z.invalid_type,expected:zQ.promise,received:t.parsedType}),qQ):YQ((t.parsedType===zQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};F$.create=(e,t)=>new F$({type:e,typeName:Q.ZodPromise,...r$(t)});var I$=class extends i${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{GQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return qQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?qQ:r.status===`dirty`||t.value===`dirty`?JQ(r.value):r});{if(t.value===`aborted`)return qQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?qQ:r.status===`dirty`||t.value===`dirty`?JQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?qQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?qQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!QQ(e))return qQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>QQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):qQ);RQ.assertNever(r)}};I$.create=(e,t,n)=>new I$({schema:e,typeName:Q.ZodEffects,effect:t,...r$(n)}),I$.createWithPreprocess=(e,t,n)=>new I$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...r$(n)});var L$=class extends i${_parse(e){return this._getType(e)===zQ.undefined?YQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:Q.ZodOptional,...r$(t)});var R$=class extends i${_parse(e){return this._getType(e)===zQ.null?YQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:Q.ZodNullable,...r$(t)});var z$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===zQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...r$(t)});var B$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return $Q(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new VQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new VQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};B$.create=(e,t)=>new B$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...r$(t)});var V$=class extends i${_parse(e){if(this._getType(e)!==zQ.nan){let t=this._getOrReturnCtx(e);return GQ(t,{code:Z.invalid_type,expected:zQ.nan,received:t.parsedType}),qQ}return{status:`valid`,value:e.data}}};V$.create=e=>new V$({typeName:Q.ZodNaN,...r$(e)});var H$=class extends i${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},U$=class e extends i${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qQ:e.status===`dirty`?(t.dirty(),JQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?qQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},W$=class extends i${_parse(e){let t=this._def.innerType._parse(e),n=e=>(QQ(e)&&(e.value=Object.freeze(e.value)),e);return $Q(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};W$.create=(e,t)=>new W$({innerType:e,typeName:Q.ZodReadonly,...r$(t)}),S$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),c$.create,l$.create,V$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create,b$.create;const nme=S$.create;S$.strictCreate,C$.create,$pe.create,E$.create,D$.create,eme.create,O$.create,k$.create,tme.create,A$.create,j$.create,N$.create,P$.create,F$.create,I$.create,L$.create,R$.create,I$.createWithPreprocess,U$.create;const rme=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>me(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>pe(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ime=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),rme.init(e,t),l(e,`shape`,()=>t.shape)});function G$(e,t){return new ime({type:`object`,shape:e??{},...d(t)})}function K$(e){return!!e._zod}function q$(e){let t=Object.values(e);if(t.length===0)return G$({});let n=t.every(K$),r=t.every(e=>!K$(e));if(n)return G$(e);if(r)return nme(e);throw Error(`Mixed Zod versions detected in object shape.`)}function J$(e,t){return K$(e)?pe(e,t):e.safeParse(t)}async function Y$(e,t){return K$(e)?await h(e,t):await e.safeParseAsync(t)}function X$(e){if(!e)return;let t;if(t=K$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Z$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return q$(e)}}if(K$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Q$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function ame(e){return e.description}function ome(e){if(K$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function $$(e){if(K$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const e1=`2025-11-25`,t1=[e1,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],n1=`io.modelcontextprotocol/related-task`,r1=ye(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),i1=Ae([F(),P().int()]),a1=F();ce({ttl:P().optional(),pollInterval:P().optional()});const sme=N({ttl:P().optional()}),cme=N({taskId:F()}),o1=ce({progressToken:i1.optional(),[n1]:cme.optional()}),s1=N({_meta:o1.optional()}),c1=s1.extend({task:sme.optional()}),lme=e=>c1.safeParse(e).success,l1=N({method:F(),params:s1.loose().optional()}),u1=N({_meta:o1.optional()}),d1=N({method:F(),params:u1.loose().optional()}),f1=ce({_meta:o1.optional()}),p1=Ae([F(),P().int()]),m1=N({jsonrpc:j(`2.0`),id:p1,...l1.shape}).strict(),h1=e=>m1.safeParse(e).success,g1=N({jsonrpc:j(`2.0`),...d1.shape}).strict(),ume=e=>g1.safeParse(e).success,_1=N({jsonrpc:j(`2.0`),id:p1,result:f1}).strict(),v1=e=>_1.safeParse(e).success;var y1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(y1||={});const b1=N({jsonrpc:j(`2.0`),id:p1.optional(),error:N({code:P().int(),message:F(),data:A().optional()})}).strict(),x1=e=>b1.safeParse(e).success,S1=Ae([m1,g1,_1,b1]);Ae([_1,b1]);const C1=f1.strict(),dme=u1.extend({requestId:p1.optional(),reason:F().optional()}),w1=d1.extend({method:j(`notifications/cancelled`),params:dme}),T1=N({icons:M(N({src:F(),mimeType:F().optional(),sizes:M(F()).optional(),theme:we([`light`,`dark`]).optional()})).optional()}),E1=N({name:F(),title:F().optional()}),D1=E1.extend({...E1.shape,...T1.shape,version:F(),websiteUrl:F().optional(),description:F().optional()}),fme=ue(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ge(N({form:ge(N({applyDefaults:k().optional()}),O(F(),A())).optional(),url:r1.optional()}),O(F(),A()).optional())),pme=ce({list:r1.optional(),cancel:r1.optional(),requests:ce({sampling:ce({createMessage:r1.optional()}).optional(),elicitation:ce({create:r1.optional()}).optional()}).optional()}),mme=ce({list:r1.optional(),cancel:r1.optional(),requests:ce({tools:ce({call:r1.optional()}).optional()}).optional()}),hme=N({experimental:O(F(),r1).optional(),sampling:N({context:r1.optional(),tools:r1.optional()}).optional(),elicitation:fme.optional(),roots:N({listChanged:k().optional()}).optional(),tasks:pme.optional(),extensions:O(F(),r1).optional()}),gme=s1.extend({protocolVersion:F(),capabilities:hme,clientInfo:D1}),O1=l1.extend({method:j(`initialize`),params:gme}),k1=e=>O1.safeParse(e).success,_me=N({experimental:O(F(),r1).optional(),logging:r1.optional(),completions:r1.optional(),prompts:N({listChanged:k().optional()}).optional(),resources:N({subscribe:k().optional(),listChanged:k().optional()}).optional(),tools:N({listChanged:k().optional()}).optional(),tasks:mme.optional(),extensions:O(F(),r1).optional()}),vme=f1.extend({protocolVersion:F(),capabilities:_me,serverInfo:D1,instructions:F().optional()}),A1=d1.extend({method:j(`notifications/initialized`),params:u1.optional()}),yme=e=>A1.safeParse(e).success,j1=l1.extend({method:j(`ping`),params:s1.optional()}),bme=N({progress:P(),total:de(P()),message:de(F())}),xme=N({...u1.shape,...bme.shape,progressToken:i1}),M1=d1.extend({method:j(`notifications/progress`),params:xme}),Sme=s1.extend({cursor:a1.optional()}),N1=l1.extend({params:Sme.optional()}),P1=f1.extend({nextCursor:a1.optional()}),Cme=we([`working`,`input_required`,`completed`,`failed`,`cancelled`]),F1=N({taskId:F(),status:Cme,ttl:Ae([P(),ve()]),createdAt:F(),lastUpdatedAt:F(),pollInterval:de(P()),statusMessage:de(F())}),I1=f1.extend({task:F1}),wme=u1.merge(F1),L1=d1.extend({method:j(`notifications/tasks/status`),params:wme}),R1=l1.extend({method:j(`tasks/get`),params:s1.extend({taskId:F()})}),z1=f1.merge(F1),B1=l1.extend({method:j(`tasks/result`),params:s1.extend({taskId:F()})});f1.loose();const V1=N1.extend({method:j(`tasks/list`)}),H1=P1.extend({tasks:M(F1)}),U1=l1.extend({method:j(`tasks/cancel`),params:s1.extend({taskId:F()})}),Tme=f1.merge(F1),W1=N({uri:F(),mimeType:de(F()),_meta:O(F(),A()).optional()}),G1=W1.extend({text:F()}),K1=F().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),q1=W1.extend({blob:K1}),J1=we([`user`,`assistant`]),Y1=N({audience:M(J1).optional(),priority:P().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),X1=N({...E1.shape,...T1.shape,uri:F(),description:de(F()),mimeType:de(F()),size:de(P()),annotations:Y1.optional(),_meta:de(ce({}))}),Eme=N({...E1.shape,...T1.shape,uriTemplate:F(),description:de(F()),mimeType:de(F()),annotations:Y1.optional(),_meta:de(ce({}))}),Z1=N1.extend({method:j(`resources/list`)}),Dme=P1.extend({resources:M(X1)}),Q1=N1.extend({method:j(`resources/templates/list`)}),Ome=P1.extend({resourceTemplates:M(Eme)}),$1=s1.extend({uri:F()}),kme=$1,e0=l1.extend({method:j(`resources/read`),params:kme}),Ame=f1.extend({contents:M(Ae([G1,q1]))}),jme=d1.extend({method:j(`notifications/resources/list_changed`),params:u1.optional()}),Mme=$1,Nme=l1.extend({method:j(`resources/subscribe`),params:Mme}),Pme=$1,Fme=l1.extend({method:j(`resources/unsubscribe`),params:Pme}),Ime=u1.extend({uri:F()}),Lme=d1.extend({method:j(`notifications/resources/updated`),params:Ime}),Rme=N({name:F(),description:de(F()),required:de(k())}),zme=N({...E1.shape,...T1.shape,description:de(F()),arguments:de(M(Rme)),_meta:de(ce({}))}),t0=N1.extend({method:j(`prompts/list`)}),Bme=P1.extend({prompts:M(zme)}),Vme=s1.extend({name:F(),arguments:O(F(),F()).optional()}),n0=l1.extend({method:j(`prompts/get`),params:Vme}),r0=N({type:j(`text`),text:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),i0=N({type:j(`image`),data:K1,mimeType:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),a0=N({type:j(`audio`),data:K1,mimeType:F(),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),Hme=N({type:j(`tool_use`),name:F(),id:F(),input:O(F(),A()),_meta:O(F(),A()).optional()}),Ume=N({type:j(`resource`),resource:Ae([G1,q1]),annotations:Y1.optional(),_meta:O(F(),A()).optional()}),o0=Ae([r0,i0,a0,X1.extend({type:j(`resource_link`)}),Ume]),Wme=N({role:J1,content:o0}),Gme=f1.extend({description:F().optional(),messages:M(Wme)}),Kme=d1.extend({method:j(`notifications/prompts/list_changed`),params:u1.optional()}),qme=N({title:F().optional(),readOnlyHint:k().optional(),destructiveHint:k().optional(),idempotentHint:k().optional(),openWorldHint:k().optional()}),Jme=N({taskSupport:we([`required`,`optional`,`forbidden`]).optional()}),s0=N({...E1.shape,...T1.shape,description:F().optional(),inputSchema:N({type:j(`object`),properties:O(F(),r1).optional(),required:M(F()).optional()}).catchall(A()),outputSchema:N({type:j(`object`),properties:O(F(),r1).optional(),required:M(F()).optional()}).catchall(A()).optional(),annotations:qme.optional(),execution:Jme.optional(),_meta:O(F(),A()).optional()}),c0=N1.extend({method:j(`tools/list`)}),Yme=P1.extend({tools:M(s0)}),l0=f1.extend({content:M(o0).default([]),structuredContent:O(F(),A()).optional(),isError:k().optional()});l0.or(f1.extend({toolResult:A()}));const Xme=c1.extend({name:F(),arguments:O(F(),A()).optional()}),u0=l1.extend({method:j(`tools/call`),params:Xme}),Zme=d1.extend({method:j(`notifications/tools/list_changed`),params:u1.optional()});N({autoRefresh:k().default(!0),debounceMs:P().int().nonnegative().default(300)});const d0=we([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Qme=s1.extend({level:d0}),f0=l1.extend({method:j(`logging/setLevel`),params:Qme}),$me=u1.extend({level:d0,logger:F().optional(),data:A()}),ehe=d1.extend({method:j(`notifications/message`),params:$me}),the=N({hints:M(N({name:F().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),nhe=N({mode:we([`auto`,`required`,`none`]).optional()}),rhe=N({type:j(`tool_result`),toolUseId:F().describe(`The unique identifier for the corresponding tool call.`),content:M(o0).default([]),structuredContent:N({}).loose().optional(),isError:k().optional(),_meta:O(F(),A()).optional()}),ihe=Se(`type`,[r0,i0,a0]),p0=Se(`type`,[r0,i0,a0,Hme,rhe]),ahe=N({role:J1,content:Ae([p0,M(p0)]),_meta:O(F(),A()).optional()}),ohe=c1.extend({messages:M(ahe),modelPreferences:the.optional(),systemPrompt:F().optional(),includeContext:we([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:M(F()).optional(),metadata:r1.optional(),tools:M(s0).optional(),toolChoice:nhe.optional()}),she=l1.extend({method:j(`sampling/createMessage`),params:ohe}),m0=f1.extend({model:F(),stopReason:de(we([`endTurn`,`stopSequence`,`maxTokens`]).or(F())),role:J1,content:ihe}),h0=f1.extend({model:F(),stopReason:de(we([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(F())),role:J1,content:Ae([p0,M(p0)])}),che=N({type:j(`boolean`),title:F().optional(),description:F().optional(),default:k().optional()}),lhe=N({type:j(`string`),title:F().optional(),description:F().optional(),minLength:P().optional(),maxLength:P().optional(),format:we([`email`,`uri`,`date`,`date-time`]).optional(),default:F().optional()}),uhe=N({type:we([`number`,`integer`]),title:F().optional(),description:F().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),dhe=N({type:j(`string`),title:F().optional(),description:F().optional(),enum:M(F()),default:F().optional()}),fhe=N({type:j(`string`),title:F().optional(),description:F().optional(),oneOf:M(N({const:F(),title:F()})),default:F().optional()}),phe=Ae([Ae([N({type:j(`string`),title:F().optional(),description:F().optional(),enum:M(F()),enumNames:M(F()).optional(),default:F().optional()}),Ae([dhe,fhe]),Ae([N({type:j(`array`),title:F().optional(),description:F().optional(),minItems:P().optional(),maxItems:P().optional(),items:N({type:j(`string`),enum:M(F())}),default:M(F()).optional()}),N({type:j(`array`),title:F().optional(),description:F().optional(),minItems:P().optional(),maxItems:P().optional(),items:N({anyOf:M(N({const:F(),title:F()}))}),default:M(F()).optional()})])]),che,lhe,uhe]),mhe=Ae([c1.extend({mode:j(`form`).optional(),message:F(),requestedSchema:N({type:j(`object`),properties:O(F(),phe),required:M(F()).optional()})}),c1.extend({mode:j(`url`),message:F(),elicitationId:F(),url:F().url()})]),hhe=l1.extend({method:j(`elicitation/create`),params:mhe}),ghe=u1.extend({elicitationId:F()}),_he=d1.extend({method:j(`notifications/elicitation/complete`),params:ghe}),g0=f1.extend({action:we([`accept`,`decline`,`cancel`]),content:ue(e=>e===null?void 0:e,O(F(),Ae([F(),P(),k(),M(F())])).optional())}),vhe=N({type:j(`ref/resource`),uri:F()}),yhe=N({type:j(`ref/prompt`),name:F()}),bhe=s1.extend({ref:Ae([yhe,vhe]),argument:N({name:F(),value:F()}),context:N({arguments:O(F(),F()).optional()}).optional()}),_0=l1.extend({method:j(`completion/complete`),params:bhe});function xhe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function She(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Che=f1.extend({completion:ce({values:M(F()).max(100),total:de(P().int()),hasMore:de(k())})}),whe=N({uri:F().startsWith(`file://`),name:F().optional(),_meta:O(F(),A()).optional()}),The=l1.extend({method:j(`roots/list`),params:s1.optional()}),v0=f1.extend({roots:M(whe)}),Ehe=d1.extend({method:j(`notifications/roots/list_changed`),params:u1.optional()});Ae([j1,O1,_0,f0,n0,t0,Z1,Q1,e0,Nme,Fme,u0,c0,R1,B1,V1,U1]),Ae([w1,M1,A1,Ehe,L1]),Ae([C1,m0,h0,g0,v0,z1,H1,I1]),Ae([j1,she,hhe,The,R1,B1,V1,U1]),Ae([w1,M1,ehe,Lme,jme,Zme,Kme,L1,_he]),Ae([C1,vme,Che,Gme,Bme,Dme,Ome,Ame,l0,Yme,z1,H1,I1]);var y0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===y1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Dhe(e.elicitations,n)}return new e(t,n,r)}},Dhe=class extends y0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(y1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function b0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Ohe=Symbol(`Let zodToJsonSchema decide on which parser to use`),x0={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},khe=e=>typeof e==`string`?{...x0,name:e}:{...x0,...e},Ahe=e=>{let t=khe(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function S0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function C0(e,t,n,r,i){e[t]=n,S0(e,t,r,i)}const w0=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function T0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?w0(t,e.currentPath):t.join(`/`)}}function jhe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=R0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&C0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&C0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(C0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),C0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Mhe(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function Nhe(){return{type:`boolean`}}function E0(e,t){return R0(e.type._def,t)}const Phe=(e,t)=>R0(e.innerType._def,t);function D0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>D0(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Fhe(e,t)}}const Fhe=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minimum`,r.value,r.message,t);break;case`max`:C0(n,`maximum`,r.value,r.message,t);break}return n};function Ihe(e,t){return{...R0(e.innerType._def,t),default:e.defaultValue()}}function Lhe(e,t){return t.effectStrategy===`input`?R0(e.schema._def,t):T0(t)}function Rhe(e){return{type:`string`,enum:Array.from(e.values)}}const zhe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Bhe(e,t){let n=[R0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),R0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(zhe(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Vhe(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let O0;const k0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(O0===void 0&&(O0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),O0),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function A0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:M0(n,`email`,r.message,t);break;case`format:idn-email`:M0(n,`idn-email`,r.message,t);break;case`pattern:zod`:N0(n,k0.email,r.message,t);break}break;case`url`:M0(n,`uri`,r.message,t);break;case`uuid`:M0(n,`uuid`,r.message,t);break;case`regex`:N0(n,r.regex,r.message,t);break;case`cuid`:N0(n,k0.cuid,r.message,t);break;case`cuid2`:N0(n,k0.cuid2,r.message,t);break;case`startsWith`:N0(n,RegExp(`^${j0(r.value,t)}`),r.message,t);break;case`endsWith`:N0(n,RegExp(`${j0(r.value,t)}$`),r.message,t);break;case`datetime`:M0(n,`date-time`,r.message,t);break;case`date`:M0(n,`date`,r.message,t);break;case`time`:M0(n,`time`,r.message,t);break;case`duration`:M0(n,`duration`,r.message,t);break;case`length`:C0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),C0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:N0(n,RegExp(j0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&M0(n,`ipv4`,r.message,t),r.version!==`v4`&&M0(n,`ipv6`,r.message,t);break;case`base64url`:N0(n,k0.base64url,r.message,t);break;case`jwt`:N0(n,k0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&N0(n,k0.ipv4Cidr,r.message,t),r.version!==`v4`&&N0(n,k0.ipv6Cidr,r.message,t);break;case`emoji`:N0(n,k0.emoji(),r.message,t);break;case`ulid`:N0(n,k0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:M0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:C0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:N0(n,k0.base64,r.message,t);break}break;case`nanoid`:N0(n,k0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function j0(e,t){return t.patternStrategy===`escape`?Uhe(e):e}const Hhe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Uhe(e){let t=``;for(let n=0;n<e.length;n++)Hhe.has(e[n])||(t+=`\\`),t+=e[n];return t}function M0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):C0(e,`format`,t,n,r)}function N0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:P0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):C0(e,`pattern`,P0(t,r),n,r)}function P0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1218
1218
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1219
1219
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function F0(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Q.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??T0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Q.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=A0(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Q.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=E0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Whe(e,t){return t.mapStrategy===`record`?F0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[R0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||T0(t),R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||T0(t)],minItems:2,maxItems:2}}}function Ghe(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Khe(e){return e.target===`openAi`?void 0:{not:T0({...e,currentPath:[...e.currentPath,`not`]})}}function qhe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const I0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Jhe(e,t){if(t.target===`openApi3`)return L0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in I0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=I0[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return L0(e,t)}const L0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>R0(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Yhe(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:I0[e.innerType._def.typeName],nullable:!0}:{type:[I0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Xhe(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,S0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?C0(n,`minimum`,r.value,r.message,t):C0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),C0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?C0(n,`maximum`,r.value,r.message,t):C0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),C0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:C0(n,`multipleOf`,r.value,r.message,t);break}return n}function Zhe(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=$he(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=R0(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=Qhe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Qhe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return R0(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function $he(e){try{return e.isOptional()}catch{return!0}}const ege=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return R0(e.innerType._def,t);let n=R0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:T0(t)},n]}:T0(t)},tge=(e,t)=>{if(t.pipeStrategy===`input`)return R0(e.in._def,t);if(t.pipeStrategy===`output`)return R0(e.out._def,t);let n=R0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,R0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function nge(e,t){return R0(e.type._def,t)}function rge(e,t){let n={type:`array`,uniqueItems:!0,items:R0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&C0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&C0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function ige(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>R0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:R0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>R0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function age(e){return{not:T0(e)}}function oge(e){return T0(e)}const sge=(e,t)=>R0(e.innerType._def,t),cge=(e,t,n)=>{switch(t){case Q.ZodString:return A0(e,n);case Q.ZodNumber:return Xhe(e,n);case Q.ZodObject:return Zhe(e,n);case Q.ZodBigInt:return Mhe(e,n);case Q.ZodBoolean:return Nhe();case Q.ZodDate:return D0(e,n);case Q.ZodUndefined:return age(n);case Q.ZodNull:return qhe(n);case Q.ZodArray:return jhe(e,n);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return Jhe(e,n);case Q.ZodIntersection:return Bhe(e,n);case Q.ZodTuple:return ige(e,n);case Q.ZodRecord:return F0(e,n);case Q.ZodLiteral:return Vhe(e,n);case Q.ZodEnum:return Rhe(e);case Q.ZodNativeEnum:return Ghe(e);case Q.ZodNullable:return Yhe(e,n);case Q.ZodOptional:return ege(e,n);case Q.ZodMap:return Whe(e,n);case Q.ZodSet:return rge(e,n);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return nge(e,n);case Q.ZodNaN:case Q.ZodNever:return Khe(n);case Q.ZodEffects:return Lhe(e,n);case Q.ZodAny:return T0(n);case Q.ZodUnknown:return oge(n);case Q.ZodDefault:return Ihe(e,n);case Q.ZodBranded:return E0(e,n);case Q.ZodReadonly:return sge(e,n);case Q.ZodCatch:return Phe(e,n);case Q.ZodPipeline:return tge(e,n);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(e=>void 0)(t)}};function R0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Ohe)return i}if(r&&!n){let e=lge(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=cge(e,e.typeName,t),o=typeof a==`function`?R0(a(),t):a;if(o&&uge(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const lge=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:w0(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),T0(t)):t.$refStrategy===`seen`?T0(t):void 0}},uge=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),dge=(e,t)=>{let n=Ahe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:R0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??T0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=R0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??T0(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function fge(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function z0(e,t){return K$(e)?De(e,{target:fge(t?.target),io:t?.pipeStrategy??`input`}):dge(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function B0(e){let t=X$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=$$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function V0(e,t){let n=J$(e,t);if(!n.success)throw n.error;return n.data}var pge=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(w1,e=>{this._oncancel(e)}),this.setNotificationHandler(M1,e=>{this._onprogress(e)}),this.setRequestHandler(j1,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(R1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new y0(y1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(B1,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new y0(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new y0(y1.InvalidParams,`Task not found: ${r}`);if(!b0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(b0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[n1]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(V1,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new y0(y1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(U1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new y0(y1.InvalidParams,`Task not found: ${e.params.taskId}`);if(b0(n.status))throw new y0(y1.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new y0(y1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof y0?e:new y0(y1.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),y0.fromError(y1.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),v1(e)||x1(e)?this._onresponse(e):h1(e)?this._onrequest(e,t):ume(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=y0.fromError(y1.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[n1]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:y1.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=lme(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new y0(y1.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:y1.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),v1(e)?n(e):n(new y0(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(v1(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),v1(e)?r(e):r(y0.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof y0?e:new y0(y1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,I1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new y0(y1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},b0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new y0(y1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new y0(y1.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof y0?e:new y0(y1.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[n1]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof y0?e:new y0(y1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=J$(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(y0.fromError(y1.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},z1,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},H1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Tme,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[n1]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[n1]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[n1]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=B0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=V0(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=B0(e);this._notificationHandlers.set(n,n=>{let r=V0(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&h1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new y0(y1.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new y0(y1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new y0(y1.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new y0(y1.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=L1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),b0(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new y0(y1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(b0(a.status))throw new y0(y1.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=L1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),b0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function H0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mge(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];H0(a)&&H0(i)?n[r]={...a,...i}:n[r]=i}return n}var hge=t(cn(),1),gge=t(en(),1);function _ge(){let e=new hge.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,gge.default)(e),e}var vge=class{constructor(e){this._ajv=e??_ge()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},yge=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},m0,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},g0,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function bge(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`tools/call`:if(!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`);break;default:break}}function xge(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var Sge=class extends pge{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(d0.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new vge,this.setRequestHandler(O1,e=>this._oninitialize(e)),this.setNotificationHandler(A1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(f0,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=d0.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new yge(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mge(this._capabilities,e)}setRequestHandler(e,t){let n=X$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(K$(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=J$(u0,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new y0(y1.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=J$(I1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new y0(y1.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=J$(l0,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new y0(y1.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){xge(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&bge(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:t1.includes(t)?t:e1,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},C1)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},h0,t):this.request({method:`sampling/createMessage`,params:e},m0,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},g0,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},g0,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new y0(y1.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof y0?e:new y0(y1.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},v0,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const U0=Symbol.for(`mcp.completable`);function W0(e){return!!e&&typeof e==`object`&&U0 in e}function Cge(e){return e[U0]?.complete}var wge;(function(e){e.Completable=`McpCompletable`})(wge||={});const Tge=/^[A-Za-z0-9._-]{1,128}$/;function Ege(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Tge.test(e)){let n=e.split(``).filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Dge(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function G0(e){let t=Ege(e);return Dge(e,t.warnings),t.isValid}var Oge=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},K0=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Sge(e,t)}get experimental(){return this._experimental||={tasks:new Oge(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(c0)),this.server.assertCanSetRequestHandler(Z0(u0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(c0,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Z$(t.inputSchema);return e?z0(e,{strictUnions:!0,pipeStrategy:`input`}):kge})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Z$(t.outputSchema);e&&(n.outputSchema=z0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(u0,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new y0(y1.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new y0(y1.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new y0(y1.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new y0(y1.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof y0&&e.code===y1.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Y$(Z$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Q$(`error`in r?r.error:`Unknown error`);throw new y0(y1.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new y0(y1.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Y$(Z$(e.outputSchema),t.structuredContent);if(!r.success){let e=Q$(`error`in r?r.error:`Unknown error`);throw new y0(y1.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new y0(y1.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Z0(_0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(_0,async e=>{switch(e.params.ref.type){case`ref/prompt`:return xhe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return She(e),this.handleResourceCompletion(e,e.params.ref);default:throw new y0(y1.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new y0(y1.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new y0(y1.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return $0;let r=X$(n.argsSchema)?.[e.params.argument.name];if(!W0(r))return $0;let i=Cge(r);return i?Q0(await i(e.params.argument.value,e.params.context)):$0}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return $0;throw new y0(y1.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Q0(await r(e.params.argument.value,e.params.context)):$0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(Z1)),this.server.assertCanSetRequestHandler(Z0(Q1)),this.server.assertCanSetRequestHandler(Z0(e0)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Z1,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Q1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(e0,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new y0(y1.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new y0(y1.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Z0(t0)),this.server.assertCanSetRequestHandler(Z0(n0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(t0,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Age(t.argsSchema):void 0}))})),this.server.setRequestHandler(n0,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new y0(y1.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new y0(y1.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Y$(Z$(n.argsSchema),e.params.arguments);if(!r.success){let t=Q$(`error`in r?r.error:`Unknown error`);throw new y0(y1.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:q$(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=q$(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>W0(e instanceof oe?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){G0(e);let l={title:t,description:n,inputSchema:X0(r),outputSchema:X0(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&G0(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=q$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=q$(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(Y0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Y0(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const kge={type:`object`,properties:{}};function q0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function J0(e){return`_def`in e||`_zod`in e||q0(e)}function Y0(e){return typeof e!=`object`||!e||J0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(q0)}function X0(e){if(e){if(Y0(e))return q$(e);if(!J0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Age(e){let t=X$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:ame(t),required:!ome(t)})):[]}function Z0(e){let t=X$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=$$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Q0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const $0={completion:{values:[],hasMore:!1}};var e2=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},jge=e=>e instanceof e2?e:new e2(e.message,{cause:e}),Mge=global.Request,t2=class extends Mge{constructor(e,t){typeof e==`object`&&r2 in e&&(e=e[r2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Nge=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},n2=Symbol(`wrapBodyStream`),Pge=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new t2(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[n2]){let e;a.body=new ReadableStream({async pull(t){try{e||=Pu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else a.body=Pu.toWeb(r);return new t2(t,a)},r2=Symbol(`getRequestCache`),i2=Symbol(`requestCache`),a2=Symbol(`incomingKey`),o2=Symbol(`urlKey`),Fge=Symbol(`headersKey`),s2=Symbol(`abortControllerKey`),c2={get method(){return this[a2].method||`GET`},get url(){return this[o2]},get headers(){return this[Fge]||=Nge(this[a2])},[Symbol(`getAbortController`)](){return this[r2](),this[s2]},[r2](){return this[s2]||=new AbortController,this[i2]||=Pge(this.method,this[o2],this.headers,this[a2],this[s2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(c2,e,{get(){return this[r2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(c2,e,{value:function(){return this[r2]()[e]()}})}),Object.defineProperty(c2,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[i2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(c2,t2.prototype);var Ige=(e,t)=>{let n=Object.create(c2);n[a2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof Uu)throw new e2(`Absolute URL for :path is not allowed in HTTP/2`);try{n[o2]=new URL(r).href}catch(e){throw new e2(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof Uu?e.authority:e.headers.host)||t;if(!i)throw new e2(`Missing host header`);let a;if(e instanceof Uu){if(a=e.scheme,!(a===`http`||a===`https`))throw new e2(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new e2(`Invalid host header`);return n[o2]=o.href,n},l2=Symbol(`responseCache`),u2=Symbol(`getResponseCache`),d2=Symbol(`cache`),f2=global.Response,p2=class e{#e;#t;[u2](){return delete this[d2],this[l2]||=new f2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[l2];if(e){this.#t=e,this[u2]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[d2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[d2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[u2]().headers}get status(){return this[d2]?.[0]??this[u2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(p2.prototype,e,{get(){return this[u2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(p2.prototype,e,{value:function(){return this[u2]()[e]()}})}),Object.defineProperty(p2.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[l2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(p2,f2),Object.setPrototypeOf(p2.prototype,f2.prototype);async function Lge(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function m2(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function Rge(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:m2(e.getReader(),t)}var h2=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},zge=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=dte);var g2=Symbol(`outgoingEnded`),_2=Symbol(`incomingDraining`),Bge=500,Vge=64*1024*1024,v2=e=>{let t=e;if(e.destroyed||t[_2])return;if(t[_2]=!0,e instanceof Uu){try{e.stream?.close?.(Wu.NGHTTP2_NO_ERROR)}catch{}return}let n=0,r=()=>{clearTimeout(a),e.off(`data`,o),e.off(`end`,r),e.off(`error`,r)},i=()=>{r();let t=e.socket;t&&!t.destroyed&&t.destroySoon()},a=setTimeout(i,Bge);a.unref?.();let o=e=>{n+=e.length,n>Vge&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Hge=()=>new Response(null,{status:400}),y2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),b2=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},x2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},S2=async(e,t)=>{let[n,r,i]=e[d2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=h2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=h2(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(x2(t),await Rge(r,t)?.catch(e=>b2(e,t))),t[g2]?.()},Uge=e=>typeof e.then==`function`,Wge=async(e,t,n={})=>{if(Uge(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(y2);if(d2 in e)return S2(e,t);let r=h2(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Lge(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&x2(t),await m2(n,t,o))}else r[zge]||(t.writeHead(e.status,r),t.end());t[g2]?.()},C2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==t2&&(Object.defineProperty(global,`Request`,{value:t2}),Object.defineProperty(global,`Response`,{value:p2})),async(r,i)=>{let a,o;try{o=Ige(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[n2]=!0,r.on(`end`,()=>{s=!0}),r instanceof Uu&&(i[g2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{v2(r)})})}),i.on(`finish`,()=>{s||v2(r)})),i.on(`close`,()=>{o[s2]&&(r.errored?o[s2].abort(r.errored.toString()):i.writableFinished||o[s2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{v2(r)})})}),a=e(o,{incoming:r,outgoing:i}),d2 in a)return S2(a,i)}catch(e){if(a)return b2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:jge(e)),!a)return}else a=o?y2(e):Hge()}try{return await Wge(a,i,t)}catch(e){return b2(e,i)}}},Gge=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
1220
1220
  `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>S1.parse(e)):[S1.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(k1);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(h1)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>k1(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)h1(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)h1(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;h1(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!t1.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${t1.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${t1.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((v1(e)||x1(e))&&(n=e.id),n===void 0){if(v1(e)||x1(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(v1(e)||x1(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},Kge=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Gge(e),this._requestListener=C2(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await C2(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};function w2(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!qge(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=g(i.error);throw new y0(y1.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function qge(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const T2=2e3,E2=2e3,Jge=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function D2(e){return Jge.some(t=>t.test(e))}function Yge(e){let t=e.trim().split(/\s+/).find(e=>e.startsWith(`--ok-lock-dir-b64=`));if(t==null)return null;let n=t.slice(18);if(!n)return null;try{let e=Buffer.from(n,`base64url`).toString(`utf8`);return Yl(e)?e:null}catch{return null}}function Xge(e){let t=e.indexOf(`--ok-project-path=`);if(t===-1)return null;let n=t+18,r=e.slice(n),i=r.search(/\s--/),a=(i===-1?r:r.slice(0,i)).trim();return a&&Yl(a)?a:null}function Zge(e){let t=[];for(let n of e.split(`
@@ -2027,6 +2027,6 @@ native-divergence-injected
2027
2027
  `,`utf-8`),o&&ee!==void 0){let r=null;try{V(O)&&(r=H(O,`utf-8`))}catch(e){r=null,A7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&Na(r)!==Na(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})),_e(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=Mx(e);if(t.length===0)return;o?.record({event:Mb,docName:i,writerId:bx.id,direction:`b`,site:de,lostLen:t.reduce((e,t)=>e+t.length,0),digest:_t(t.join(`
2028
2028
  `))})}catch(e){A7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},yR)}catch(e){throw t.recordStoreFailure(i,N7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(kae(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let k=`${O}.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 is(k,S,`utf-8`),await Cs(k,O),HR(O,WR(S)),t.clearStoreFailure(i),Pae();try{d?.(i,f,S,ee??null)}catch(e){A7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{us(k)}catch{}throw C.delete(i),t.recordStoreFailure(i,N7(e)),A7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}A7.info({filePath:O,bytes:S.length},`[persistence] Wrote ${O} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){A7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Xo({"persistence.bytes":S.length}),j()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),be?.record((Date.now()-o)/1e3)})}function we({document:e,documentName:n,lastTransactionOrigin:r}){re.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Te(e=`within-branch`){return k?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,k):(k=(async()=>{let n=e;for(;;){let e=[...re.entries()];if(re.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=_t(r),a;try{a=EEe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:_t(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}Aoe(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),A7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,re.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{k=null}),k)}let F={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),Kx(i))return;if(qx(i)){UTe(n,i,h);return}if(Jx(i)){WG(n,i,_);return}if(Yx(i)||Xx(i)){bEe(n,i,v);return}Se();let o=Date.now();return rs(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{A7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=Uk(i,r);if(!V(a))return;let o=a;try{let e=U(a);if(!Wk(e,r)){A7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(ic(e)===`ELOOP`){A7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=mu(o).size;if(s>524288)throw A7.warn({documentName:i,fileSize:s,limit:Pe},`[persistence] Document exceeds open byte limit; refusing to load`),new wEe(i,s);let c=H(a,`utf-8`),l=n.getXmlFragment(`default`);A7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{bR(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(_i,crypto.randomUUID())},yR),A7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{A7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):A7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{P?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!Kx(n)){if(qx(n)){let t=await GTe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){A7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(Jx(n)){if(await qG(e,n,r,_)===`persisted`){let e=j7(r,c);if(e&&e.id!==Sx.id&&!e.id.startsWith(`agent-`)){let t=PG(n);t&&(_M(t.docKey,e.id,e.name,e.id,t.subject),j())}}return}if(Yx(n)||Xx(n)){await xEe(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(){ne&&await ne}async function De(){if(ne){await ne;return}xM()!==0&&(ne=A().finally(()=>{ne=null,O&&(O=!1,j())}),await ne)}function Oe(){return{branchDeferred:re.size,quiescenceDeferred:C.size}}async function ke(e,n){if(!$x(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:oe,flushContributors:De,waitForPendingCommits:Ee,getQueueDepths:Oe,forceStore:ke,configPersistenceCtx:h,managedArtifactCtx:_}}const F7=I(`persistence-staleness`);var I7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function OEe(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??tC,c=new Map,l=!1,u=null;function d(e){return M7(e)}function f(e){return e===void 0?void 0:Na(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&di(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),$x(n)||uS(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&&Jae();let te=!ee&&T?T.firstDetectedAtMs:C,E=C-te,D=null,ne=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(D=`disk-file-never-loaded`):t===null?D=`disk-file-missing`:Na(t)!==S&&(D=`disk-diverged-from-base`)}catch(e){e instanceof I7?(D=`disk-read-refused`,F7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(D=`disk-read-failed`,ne=!0,F7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(D!==null){g++,Xae(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!ne}),F7.warn({docName:n,ageMs:w,staleForMs:E,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:D},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}F7.warn({docName:n,ageMs:w,staleForMs:E,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}),Yae(),h++;try{await e.forceStore(v,n)}catch(e){F7.error({err:e,docName:n,staleForMs:E},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let O=v.getText(`source`).toString(),k=i(n),re=d(O);p(re,f(k),O,k)&&re===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:te,declined:!0}),F7.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?F7.info(v,`[persistence-staleness] sweep complete`):F7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{F7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function kEe(e){try{let t=zs({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 L7(e){let t=PA(e),n=B(t,`principal.json`),{name:r,email:i}=await kEe(e);if(V(n)){let e;try{e=JSON.parse(H(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Mu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?Zm(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?Zm(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return gu(n,JSON.stringify(s,null,2),`utf-8`),s}ou(t,{recursive:!0});let a=`principal-${Mu()}`,o=a.slice(10,18),s={id:a,display_name:r?Zm(r):`Local User`,display_email:i?Zm(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return gu(n,JSON.stringify(s,null,2),`utf-8`),s}var AEe=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 R7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function jEe(e,t){try{if(Zx(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(R7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw Qb(),Xo({"auth.reason":`doc-deleted`}),new TQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){Poe(),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 Zb(),Xo({"auth.reason":`rename-redirect`}),new TQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw R7(t,i)?(t.recentlyRemovedDocs.delete(i),Zb(),Xo({"auth.reason":`rename-redirect`}),new TQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(Qb(),Xo({"auth.reason":`doc-deleted`}),new TQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof TQ)throw t;Noe(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const z7=I(`removed-docs-journal`);function B7(e){return R(PA(e),`removed-docs.json`)}function MEe(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 NEe(e){let t=B7(e);if(!V(t))return[];try{let e=JSON.parse(H(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return z7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!MEe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return z7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function V7(e,t){let n=B7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};hs(L(n),{recursive:!0});let i=`${n}.tmp`;ws(i,JSON.stringify(r),`utf-8`),cs(i,n)}const H7=I(`server-observers`);function U7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(Kx(r)||qx(r)||Yx(r)||Xx(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=Mw({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 H7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),Jb(`a`),Jb(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(H7.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){H7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const W7=`state.json`;function G7(e){return e.lockDir,V(e.shadowRepoDir)?`adopt`:`fresh`}function K7(e){return B(e,W7)}function PEe(e,t){return e===t||e===0&&t===1}var q7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function FEe(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 J7(e){let t=K7(e);if(!V(t))return{status:`absent`};let n;try{n=H(t,`utf-8`)}catch(e){throw new q7({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 q7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!FEe(r))throw new q7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function Y7(e,t){let n=K7(e);ou(L(n),{recursive:!0}),gu(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function X7(e){let t=I(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Xs,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=K7(e.lockDir),s=J7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!PEe(c.stateSchemaVersion,n))throw new q7({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 Y7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(G7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return Y7(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 Y7(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 IEe(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 LEe(e){return e.git?.toString()??e.message??``}function Z7(e,t){return t.some(t=>t.test(e))}const REe={"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`},zEe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],Q7=[/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],BEe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],VEe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],HEe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],UEe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],WEe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],GEe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],KEe=[/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],qEe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],JEe=[/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],YEe=[/\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],XEe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function $7(e){let t=ZEe(e);return{...t,userFacingCode:IEe(t.class,t.subclass)}}function ZEe(e){let t=e instanceof Error?e:Error(String(e)),n=LEe(t),r=`${t.message}\n${n}`.toLowerCase();if(Z7(r,GEe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Z7(r,KEe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Z7(r,qEe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=Wa(t);return i.kind===`auth`?i.subclass===`403`&&Z7(r,Q7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:REe[i.subclass],rawStderr:n}:Z7(r,Q7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Z7(r,zEe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Z7(r,BEe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Z7(r,VEe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Z7(r,HEe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Z7(r,WEe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Z7(r,UEe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Z7(r,XEe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Z7(r,YEe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Z7(r,JEe)?/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 QEe(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 e9=I(`github-permissions`);function $Ee(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function eDe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function tDe(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 nDe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return e9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=tDe(t);return n===null?(e9.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 e9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function rDe(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){e9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function iDe(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 rDe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(e9.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`}):(e9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${$Ee(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;e9.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:eDe(l)}),t=await nDe(e,l!==void 0);return e9.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?(e9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(e9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function aDe(e){let t=performance.now(),n=await iDe(e);return lDe(n,performance.now()-t),n}function oDe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let t9=null;function sDe(){return t9||=Ds().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}.`}),t9}let n9=null;function cDe(){return n9||=Ds().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),n9}function lDe(e,t){let n=oDe(e);sDe().add(1,n),cDe().record(t,{outcome:n.outcome})}function r9(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 uDe(e,t){return t===`anonymous`?Math.max(180,e):e}const i9=I(`sync-engine`),a9=/^[0-9a-f]{40}$/i,dDe=Ru(Vl);function fDe(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 pDe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function o9(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 s9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function c9(e){let t=Zu(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 mDe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const l9=12e4;var hDe=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=QEe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??aDe,this.statePath=B(PA(this.projectDir),`sync-state.json`),this.conflictStore=new kQ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return SF(this.projectDir)}gitHandle(e){return Hs(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){i9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),i9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){i9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=ud(this.projectDir),n=t?R(t,`MERGE_HEAD`):null,r=n!==null&&V(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){i9.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 zb(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&&i9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){i9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){i9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){i9.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`),i9.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=r9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=r9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),i9.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,i9.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){i9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Lu(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||c9(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||c9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){i9.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){i9.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 Bs(()=>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,i9.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`,i9.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`?i9.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}`):i9.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 i9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||c9(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?Vde(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 Hz(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=xF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,o9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,i9.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){i9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=pDe(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,i9.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,i9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!o9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,i9.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(!V(R(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return i9.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=ud(this.projectDir),r=n?R(n,`MERGE_HEAD`):null;if(r!==null&&V(r))try{let n=this.gitHandle(),r=new Set(await zb(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&&i9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){i9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{i9.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&&(i9.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=>{i9.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??s9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{i9.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){i9.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`?uDe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=mDe(this.consecutiveFailures);return s9(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(c9(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`,i9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError($7(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=$7(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=$7(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`),i9.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 zb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await zb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError($7(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($7(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){i9.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 i9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError($7(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 i9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(i9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError($7(Error(`git merge --ff-only timed out after ${l9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),i9.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 i9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError($7(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 i9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError($7(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 i9.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 dDe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:l9}),{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:fDe({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(!V(R(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),i9.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=H(R(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`&&i9.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=Vr(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){i9.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=R(this.projectDir,t);eL(e,this.projectDir),ws(e,n)}for(let e of t){let t=R(this.projectDir,e);eL(t,this.projectDir);try{us(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=R(this.projectDir,e),n=Vk(z(this.contentDir,t));return!n.startsWith(`..`)&&Px(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 zb(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(c9(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=R(xu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Bs(async()=>{let e=this.gitHandle(n);if(c9(this.projectDir)){i9.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)){i9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError($7(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){i9.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}i9.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 zb(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)??Vk(z(this.contentDir,R(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 Hz(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`;Ws(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(!_||!a9.test(_)){i9.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=$7(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){i9.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=$7(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}i9.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{hu(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=R(xu(),`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 zb(a.git,[`diff-tree`,`--name-only`,`-r`,t,s])}catch{c=n.map(e=>e.projectRelPath).concat(o)}let l=await Hz(this.projectDir),u=l?.name??`OpenKnowledge`,d=l?.email??`sync@open-knowledge.local`;Ws(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||!a9.test(f)?(i9.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{hu(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await zb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return i9.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 zb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return i9.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(),i9.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 i9.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){i9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=lu(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=R(n,i.name);if(i.isDirectory()){let e=Vk(z(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=Vk(z(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=Vk(z(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return V(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await zb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=R(this.projectDir,e),r=Vk(z(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 zb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){i9.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){i9.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=R(this.projectDir,e),i=Vk(z(this.contentDir,t));!i.startsWith(`..`)&&Px(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]),i9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){i9.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){i9.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(),i9.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`),i9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=ud(this.projectDir);t=n===null||!V(R(n,`MERGE_HEAD`))}catch(e){i9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),i9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){i9.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`),i9.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){i9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){i9.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),i9.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,i9.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)};gu(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){i9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(V(this.statePath))try{let e=H(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){i9.warn({err:e},`[sync] failed to load sync state`)}}};Go();const gDe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _De(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Kx(e)||qx(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&gDe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Qo(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Ko.with(Uo.extract(Ko.active(),r),e)}else e()}catch(e){I(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let u9=!1;function d9(){if(u9)return;let e=qu;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){u9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),u9=!0}catch(e){I(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const vDe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function yDe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(v8).join(` `)} auth git-credential`]}function bDe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Wl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],xN({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return I(`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 I(`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(`
2029
2029
  `)){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=B(e,r);if(!Wk(a,t))continue;let s=tz(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function f9(e){d9();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=I(`server`),x=new c7,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),E=()=>x.isBatchInProgress();function ne(){let e=$o({absPath:ts(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=se(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 O(){let e=$o({absPath:ts(`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=$o({absPath:ts(`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:D(r.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){let e=$o({absPath:ts(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Ze(e):ho}function re(){return $o({absPath:ts(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function A(){return WM(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function ie(){let e=$o({absPath:ts(`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 j(){return Zo({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function oe(){for(let e of j().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 ce(e){return`${PM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function le(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=O();t=n.mode,ft?.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=A();Ae.applyConfig({enabled:n.enabled,providerFingerprint:ce(n)}),e===`__config__/project`&&we?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}Es();let ue=Mu(),de=PA(n),fe=new Xd({localDir:de,log:I(`acp-registry`)}),M=new Hd(de,I(`acp-permissions`));if(tc(de,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!g)try{X7({lockDir:de,shadowRepoDir:dd(n)})}catch(e){throw Ks(de),e}let pe=La(),me=(e,t)=>pe.resolveEmbed(e,t),he=(e,n)=>{let r=pe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=B(t,r);if(!Hk(i,B(t)))return null;try{let e=mu(i);return e.isFile()?e.size:null}catch{return null}},ge,N,_e,ve,ye,P,be,xe,Se,Ce,we=null,Te=null,F=null,Ee=null,De=null,Oe=null,ke=A(),Ae=new Jle({loadEmbedder:e.embedderLoader??(()=>{let t=A();return Ple({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:R(PA(n),`embeddings`),enabled:ke.enabled,providerFingerprint:ce(ke)}),je=null,Me=new Set,Ne=!1,Pe=[],Fe,Ie,Le,Re=new Promise((e,t)=>{Ie=e,Le=t});function ze(e){we?.signal(e)}let Be=null,Ve=!1,He=()=>{try{V7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ue=new AEe(void 0,{onEviction:()=>joe(),onSizeChange:e=>Moe(e),onMutate:()=>{!Ve||Be!==null||(Be=setTimeout(()=>{Be=null,He()},2e3))}});for(let[e,r]of NEe(n))Zx(e)||gQ(e)&&([`.md`,`.mdx`].some(n=>{let r=B(t,`${e}${n}`);return Hk(r,B(t))&&V(r)})||Ue.restore(e,r));Ve=!0;let We={current:null},Ge=(e,t)=>{Zx(e)||Ue.setRenamed(e,t)},Ke=e=>{if(!Zx(e)){if(Ue.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ue.setDeleted(e),We.current?.deleted(e)}},qe=e=>{Zx(e)||Ue.delete(e)};try{ge=hP({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:$I(t),rescanInPlaceSkillDirs:()=>$I(t),onAfterRebuild:()=>{N.refreshContentScope().catch(e=>{I(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),wz(ut).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?I(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):I(`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=>{I(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),N=new vR({projectDir:n,contentDir:t,contentFilter:ge,getGlobalSkillRoots:()=>IG(ye.managedArtifactCtx),signalChannel:ze}),_e={current:d},ve=o?_Ee({getShadow:()=>_e.current??null,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:ud(n)??void 0,isWriterLive:e=>{if(!Ee&&!xe)return I(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ee?.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,ye=P7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:_e,ephemeral:v,contentRoot:f,derivedDocumentIndex:N,configHomedirOverride:l,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,getPrincipal:()=>je,onAgentCommit:()=>we?.signal(`session-activity`),onFlushCommit:()=>ve?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{we?.emitDiskAck(e,t),!Zx(e)&&Mse(r,n)&&(De?.(),ze(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),onConfigPersisted:le,isRecentlyRemoved:e=>Ue.has(e),mdManager:e.mdManager,getLossRing:()=>P,durabilityState:x}),be=new NTe({quiet:r,debounce:i,maxDebounce:a,extensions:[ye.extension]});let p=be;Pe.push(tw(()=>p.documents.size),nw(()=>ye.getQueueDepths()),iw(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),ow(),v||(Oe=OEe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>ye.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=Uk(e,t),r,i;try{r=U(n),i=mu(r).size}catch(t){let n=ic(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new I7(`symlink cycle at content path: ${e}`):t}if(!Wk(r,t))throw new I7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new I7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(ic(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=be.shouldUnloadDocument.bind(be);be.shouldUnloadDocument=e=>{if(Me.has(e)||Ne&&g(e))return!0;let t=e.name;return Zx(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Fe=async e=>{Me.add(e);try{await be.unloadDocument(e)}finally{Me.delete(e)}},we=new eS(be),F=new _D(be),Ee=new yD(be),xe=new $w(be,e.agentSessionOptions);let b=xe;Pe.push(aw(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=f7({derivedDocumentIndex:N,onDocumentSettled:e=>We.current?.changed(e)});be.configuration.extensions.push(w),be.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=EQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ue)throw new TQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ue}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new TQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(je&&n.principalId===je.id?o.principalId=je.id:je?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:je.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),be.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!qx(t.documentName)&&!Jx(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!Wz(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&&Xz(a,e.remotePublicHost);if(!Gz(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=B(t);function ee(e){if(!gQ(e))return null;let t=B(T,Ux(e));return Hk(t,T)?t:null}be.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await jEe(e.documentName,{recentlyRemovedDocs:Ue,resolveFilePath:ee,fileExists:V})}}),be.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=EQ(e.token);YTe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>be.documents.get(e)})}}),be.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ti} rejected — server-only channel`)}});let te=_Q({hocuspocus:be,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:xe,commentDocHooksRef:We,contentDir:t,contentFilter:ge,serverInstanceId:ue,getFileIndex:()=>ut?ut.getFileIndex():new Map,getAttachmentFolderPath:ne,getAllFilesIndex:()=>ut?ut.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ut?.getFileIndexGeneration()??0,mutateFileIndex:e=>ut?.mutateFileIndex(e),getFolderIndex:()=>ut?ut.getFolderIndex():new Map,getAliasMap:()=>ut?ut.getAliasMap():new Map,getFolderAliasIndex:()=>ut?ut.getFolderAliasIndex():new Map,rescanFiles:()=>ut?.rescanFromDisk(),enableTestRoutes:u,shadowRef:_e,flushGitCommit:()=>ye.flushPendingGitCommit(),flushContributors:()=>ye.flushContributors(),getCurrentBranch:()=>dt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:N,signalChannel:ze,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ft,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:me,getBridgeLossReporter:()=>Ce,getPrincipal:()=>je,acpRegistry:fe,loadAcpCustomAgents:()=>Zd(de,I(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Fe,ready:Re,recentlyRemovedDocs:Ue,serializeDoc:$e,evictManagedArtifactLkg:e=>{ye.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ae,getSemanticSimilarityFloor:()=>A().similarityFloor,getLinterBaseConfig:()=>k(),getLinksValidationSetting:()=>re(),getLinkPreviewsEnabled:ie,getConfigDiagnostics:j,embeddingsSecretsFile:VM(l),readSemanticProviderConfig:A,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{De=e}});be.configuration.extensions.push(te),Se=te.nativeApi;let E=$o({absPath:ts(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),D=E.value.bridge.deferGuard.enabled,O=E.value.bridge.fixedPoint.enabled,ae=E.value.bridge.preDrain.enabled;P=E.value.lossCapture.enabled?new bae({projectDir:n,maxBytes:E.value.lossCapture.maxBytes}):void 0,E.value.bridge.lossDetector.enabled&&(Ce=dse({shadow:()=>_e.current,ring:P,getBranch:()=>dt?.getLastKnownBranch()??`main`,contentRoot:f??``}),xe.attachBridgeLossReporter(Ce)),be.configuration.extensions.push(U7({mdManager:Jo,schema:qo,shadowRef:_e,contentRoot:f,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,deferGuardEnabled:D,lossDetectorEnabled:E.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:O,preDrainEnabled:ae,lossRing:P})),be.configuration.extensions.push(_De()),be.configuration.extensions.push(JTe({getSyncEngine:()=>ft,projectDir:n,contentDir:t}))}catch(e){for(let e of Pe.splice(0))e();throw Oe?.dispose(),Oe=null,Ks(de),e}let Je=null,Ye=new Map,Xe=[];function Qe(e,t){let n=B(e,`rescue`),r=B(n,Ux(t));return Hk(r,n)?r:null}function $e(e){let t=be.documents.get(e);return t?jR(t):null}let et=(e,t)=>OR(x,be,e,t,me,he,Ce);function tt(e){if(!lS(e)||ft?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let nt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of be.documents){if(Zx(n))continue;let r=be.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{bR(r,i,me,n)},yR)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rt=null,it=e=>{e&&(rt===null&&(rt=new Set,setImmediate(()=>{let e=rt;if(rt=null,e)try{for(let t of e)nt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rt.add(e))};function at(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 LR(e)}}async function ot(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await N.recordDiskUpsert(e.docName,e.content),ze(`files`),qe(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=be.documents.get(t);if(!r){await N.recordDiskUpsert(t,n);return}let i=C(t)??``,a=$e(t)??i,o=wR({docName:t,base:i,ours:a,theirs:n}),s=WR(i).slice(0,6),c=WR(a).slice(0,6),l=WR(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`:tt(r),await N.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Bb(),tt(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),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{et(t,o.newContent),w(t,n),Bb(),tt(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),tt(r)}e&&await N.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Bb(),Vb(),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 N.recordDiskUpsert(t,n);break}case`refused`:{Vb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=be.documents.get(t);if(!n){await N.recordDiskDelete(t),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=$e(t)??``,a=i!==r;if(a&&_e.current){let e=_e.current,n=dt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Dx(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Ub(),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 N.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),be.closeConnections(t),await Fe(n),ze(`files`),Ke(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=be.documents.get(t);if(T(t),w(n,r),await N.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}`),ze(`files`),Ge(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=be.documents.get(t);if(!n)return;let r=$e(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`:pe.add(e.relativePath),ze(`files`),it(Kl(e.relativePath));break;case`asset-delete`:pe.remove(e.relativePath),ze(`files`),it(Kl(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;case`file-create`:case`file-update`:case`file-delete`:ze(`files`);break;default:LR(e)}}catch(t){let n=at(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let st=[];async function ct(e){if(E()){st.push(e);return}await ot(e)}async function lt(){let e=st.splice(0,st.length);for(let t of e)await ot(t)}let ut=null,dt=null,ft=null,pt=null;async function mt(e){if(be.documents.size===0)return;let t=!1,n=new Promise(e=>{be.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(be.documents.keys());be.closeConnections(),be.flushPendingStores();for(let e of be.documents.values())e.getConnectionsCount()===0&&be.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(be.documents.keys()),i=[],o=[];if(_e.current){for(let e of n)if(!Zx(e))try{let t=$e(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Qe(_e.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:_e.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}ou(L(n),{recursive:!0}),gu(n,t,`utf-8`),Ub(),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 ht(){return pt||(pt=(async()=>{let e=Date.now(),t=[];Ne=!0;for(let e of Pe.splice(0))e();try{await Oe?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Oe=null;try{nc(de)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Be!==null&&(clearTimeout(Be),Be=null),Ve)try{V7(n,Ue.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([Re.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=be.documents.size;ve?.destroy();try{try{try{Te&&=(clearTimeout(Te),null),dt&&=(await dt.unsubscribe(),null),ut&&=(await ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Xe)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Xe.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{we?.destroy(),Ee?.destroy(),Je&&=(await Je.disconnect(),null);for(let[e,t]of Ye)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ye.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 GS()}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 mt(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`)}N.close();let e;try{await Promise.race([(async()=>{await ye.flushPendingGitCommit(),await ye.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{ft&&=(await ft.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(_e.current){try{let e=(await zs({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&gu(B(_e.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Koe(_e.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{Ks(de,{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 Ts()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),pt)}let gt=[];async function _t(){try{je=await L7(n),y.info({principalId:je.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!_e.current)try{_e.current=await px(n),y.info({gitDir:_e.current.gitDir},`[server] history repo initialized at ${_e.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),gt.push(`shadow-repo`)}if(_e.current){let e=null;try{e=OK(_e.current.gitDir),ZK(_e.current.gitDir,e),NK(_e.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([QK(_e.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 ve?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(_e.current)try{await dx(_e.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{_e.current=await px(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),_e.current=void 0,gt.includes(`shadow-repo`)||gt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(_e.current)try{let e=B(_e.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await zs({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await zs({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 wx(_e.current,f??``,t,r,e),Hb()}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{gu(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=mK(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`),gt.push(`managed-rename-recovery`)}try{let e=hL(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`),gt.push(`upload-tempfile-sweep`)}try{Je=await be.openDirectConnection(Ti),we?.emitServerInfo(ue,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),gt.push(`cc1-push`)}let r=v?[]:Ba;for(let e of r)try{let t=await be.openDirectConnection(e);Ye.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),gt.push(`config-doc:${e}`)}let i=new Map([[Jr,ts(`project`,n)],[Aa,ts(`project-local`,n)],[Ga,ts(`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 X5(t,t=>{let n=be.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,ye.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),le(e)});Xe.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}`),gt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=UG(e,ye.managedArtifactCtx);if(!n)return;let r=JG(be.documents.get(n)??null,n,t,ye.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),ze(`files`),Br(n)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=UG(e,ye.managedArtifactCtx);ze(`files`),t&&Br(t)&&N.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=IG(ye.managedArtifactCtx),r=await w7(n,e,void 0,t);Xe.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`),gt.push(`managed-artifact-watcher:skills`)}try{let e=B(NG(ye.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{ze(`files`)});Xe.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`),gt.push(`skill-state-watcher`)}try{let t=new Set([``]);try{for(let e of(await Oj(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?B(n,e,`.ok`,`templates`):B(n,`.ok`,`templates`)),i=await w7(r,e,yEe);Xe.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`),gt.push(`managed-artifact-watcher:templates`)}}try{let e=B(t,`.okignore`),r=B(n,`.gitignore`),i=null;try{let e=Wl(`git`,[`rev-parse`,`--git-common-dir`],xN({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=R(B(n,e.stdout.trim()),`info`,`exclude`);V(L(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 zTe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(be.documents.get(`__config__/okignore`)??null,qi,r,ye.configPersistenceCtx);o.info({docName:qi,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:z(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:z(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=z(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:z(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Xe.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`),gt.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;ee(a);let o=N.beginStartup(a),s=!1,c=performance.now();try{await rs(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&gt.push(`backlink-index`);let i=0;for(let t of e)Zx(t)||Ue.peek(t)?.kind!==`renamed`&&(Ue.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=ge?$I(t):new Set,d=e=>{e.some(e=>c.test(z(t,e).split(Ql).join(`/`)))&&(Te&&clearTimeout(Te),Te=setTimeout(()=>{Te=null;try{ZX(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),we?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=$I(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,ge.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),we?.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))};ut=await rs(`ok.boot.seed-walk`,void 0,async()=>Cz(t,ct,ge,{onRawBatch:d})),ZX(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??vu();ZX(e,e,ZI(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`))}tR(`seedWalkMs`,Math.round(performance.now()-a));{let e=B(t),n=0;for(let[t]of Ue.entries()){if(!gQ(t))continue;let r=B(e,`${t}${Vx(t)}`);Hk(r,e)&&V(r)&&(Ue.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 N.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&gt.push(`tag-index`);let p=0;try{_===void 0?await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Spe({contentDir:t,basenameIndex:pe,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`),gt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),gt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),gt.push(`file-watcher`),!s){let e=await N.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&gt.push(`tag-index`)}}finally{tR(`indexesMs`,Math.round(performance.now()-c)),ut&&nR(`fileCount`,ut.getFileIndex().size)}try{dt=await eEe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),Oae(),be.flushPendingStores(),await ye.flushPendingGitCommit(),te(!0),_e.current){let e=S(),t=d7(n).branch??e,r=[];for(let[e,t]of be.documents){if(Zx(e))continue;let n=null;if(t.transact(()=>{n=$e(e)},vDe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await nse(_e.current,e,Sx.id,r,t);n&&(jae(),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=st.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 lt(),e.headMoved&&e.newHead){let r=bDe(n,B(t),e.oldHead,e.newHead);if(r.size>0){sle(r.keys());for(let[e,t]of r)_M(e,sd(t.email),t.name,t.email,kd(e));await ye.flushContributors()}}if(await ye.flushDeferredStores(`within-branch`),ft!==null)try{await ft.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Aae(),st.splice(0,st.length);let n=!1,r;try{ee(i),r=await N.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;pe.clear(),await bQ({contentDir:t,contentFilter:ge,basenameIndex:pe,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`),gt.includes(`basename-index-partial`)||gt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of be.documents)if(!Zx(e))try{let r=Uk(e,t);if(!V(r)){let t=C(e)??``,r=$e(e)??``;if(r!==t&&_e.current){let t=_e.current;queueMicrotask(()=>{Dx(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Ub(),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=H(r,`utf-8`);et(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:be.documents.size},`[branch-switch] loaded branch ${i} (${be.documents.size} docs)`);try{await N.settleBranchFromDisk(r)}catch(e){N.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(_e.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of be.documents)if(!Zx(t))try{let n=await ise(_e.current,i,Sx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=wR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:et(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:et(t,a.newContent),w(t,a.newContent),Vb(),e++;{let e=be.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-`)&&_e.current)try{let t=dx(_e.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await sx(_e.current).withMutator(async()=>{for(let e of n.split(`
2030
- `))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 ye.flushDeferredStores(`discard-stale`),n=!0,we?.emitBranchSwitched(i)}finally{N.abortBranchSwitch(r),n||(te(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&_e.current&&r>0){let t=f??`.`;try{let n=await wx(_e.current,t,e.oldHead,e.newHead,i);Hb(),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`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Vk(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=Ix(e),a=be.documents.get(i);if(!a)continue;let o=$e(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=Vk(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=be.documents.get(Ix(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=yDe(m),h=O();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new hDe({projectDir:n,contentDir:t,contentFilter:ge,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||ye.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=_e.current;n&&await Ex(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=_e.current;n&&await Ex(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 ms({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ae(t.error),configPath:ts(`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 ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}ze(`files`),N.announceReadyViews();let g=eR();g!==void 0&&tR(`readyMs`,g),oe()}return _t().then(Ie,e=>{N.close(),Le(e)}),{hocuspocus:be,durabilityState:x,sessionManager:xe,nativeApi:Se,cc1Broadcaster:we,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,maintenanceCoordinator:ve,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:ht,ready:Re,degraded:gt,lockDir:de,get syncEngine(){return ft},getLinkPreviewsEnabled:ie,resolveEmbed:me,acpRegistry:fe,acpPermissions:M}}function p9(e){return e/1048576}function xDe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:p9(e.rss),heapTotalMb:p9(e.heapTotal),heapUsedMb:p9(e.heapUsed),externalMb:p9(e.external),arrayBuffersMb:p9(e.arrayBuffers)}}}let m9=null,h9=null,g9=null;const _9=1e6;let v9=null,y9=null;ns(()=>{m9=null,h9=null,g9=null,v9?.disable(),v9=null,y9=null});function SDe(){if(m9)return;let e=Ds().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}=xDe();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`})}),m9=e}function CDe(){if(!h9){let e=Ds().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(!v9){v9=pte({resolution:20}),v9.enable();return}e.observe(v9.percentile(50)/_9,{stat:`p50`}),e.observe(v9.percentile(99)/_9,{stat:`p99`}),v9.reset()}),h9=e}if(!g9){let e=Ds().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=y9;if(y9={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`}))}),g9=e}}const b9=I(`skill-migrate`);function x9(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=fO.indexOf(e.host),r=fO.indexOf(t.host);return(n===-1?fO.length:n)-(r===-1?fO.length:r)||e.host.localeCompare(t.host)})}const wDe=x9(Fa),TDe=x9(Ht);function EDe(e,t){hs(L(t),{recursive:!0});try{cs(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;vs(e,t,{recursive:!0}),ys(e,{recursive:!0,force:!0})}}function DDe(e,t,n){let r=mI(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 S9(e,t){let n;try{n=U(B(e,`.ok`,`skills`))}catch{n=B(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(B(e,t.dir)).startsWith(n+Ql)}catch{return!0}}).map(e=>e.name))}async function C9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??wDe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=lu(n)}catch{return a}let s=z(t,n).split(Ql).join(`/`),c=new Set;for(let[e,n]of Object.entries(JX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!mi.test(e)||FF.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=B(n,e);if(!V(R(o,`SKILL.md`)))continue;let s=tO(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=B(t,r);return{host:n,root:r,path:R(i,e),escapes:SI(t,i),state:DDe(R(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`&&V(B(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`?ys(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ys(d.path,{recursive:!0,force:!0}),EDe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ys(e.path,{recursive:!0,force:!0}),vs(d.path,e.path,{recursive:!0}));await XN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),b9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),b9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const w9=I(`skill-reconcile`),ODe=FF;function T9(){let e=[];for(let t of _r){let n=Fa[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function kDe(e,t){let n=z(e,B(t));return Yl(n)?B(t):n}function E9(e){let{frontmatter:t,body:n}=Mo(e),r={};if(t!==``)try{let e=(0,kk.parse)(Qr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function ADe(e,t){let n=E9(e),r=E9(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 D9(e,t){let n=O9(e),r=O9(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=R(e,o),c=R(t,o);if(i+=mu(s).size+mu(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!ADe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function O9(e,t=``){let n=[];for(let r of lu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...O9(R(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function k9(e,t,n){ys(t,{recursive:!0,force:!0}),hs(e,{recursive:!0}),ds(kDe(e,n),t,`dir`)}function A9(e,t){try{let n=uu(e);return B(Yl(n)?n:B(L(e),n))===B(t)}catch{return!1}}function jDe(e,t){try{let n=uu(e),r=Yl(n)?B(n):B(L(e),n);if(!V(r))return!1;let i=z(B(t),r);return i!==``&&(i.startsWith(`..`)||Yl(i))}catch(t){return w9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const MDe=[..._r,`agents`];function NDe(e){for(let t of MDe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function PDe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=lu(n)}catch{return}let i=T9();for(let e of r){let r=NDe(e);if(r===null)continue;let a=B(n,e),o=B(n,r);if(V(o))try{let n=au(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(R(a,`SKILL.md`))||!V(R(o,`SKILL.md`))||!D9(o,a))continue;for(let{rel:n}of i){let r=B(t,n);if(SI(t,r))continue;let i=R(r,e);A9(i,a)&&k9(r,i,o)}ys(a,{recursive:!0,force:!0}),w9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){w9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function FDe(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 T9()){let o=B(t,e);if(!V(o)||SI(t,o))continue;let s;try{s=lu(o)}catch(e){w9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(ODe.has(e))continue;let t=R(o,e),s=B(n,e),c=V(s);try{let l=au(t);if(l.isSymbolicLink()){if(A9(t,s)&&c)continue;if(jDe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(k9(o,t,s),r.healed.push({name:e,editor:i})):(ys(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!mi.test(e)){w9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&D9(t,s)){k9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){w9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=qN(t);for(let[r,a]of i){let i=B(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await YN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??_I(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){w9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{PDe({projectDir:t,skillsRoot:n})}catch(e){w9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let j9=null,M9=!1;function N9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function P9(e){if(!N9())return;let t=PA(e);j9=new Is({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ka(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};j9?.append(`${JSON.stringify(t)}\n`).catch(e=>{M9||(M9=!0,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function F9(){Ka(null),await j9?.drain(),j9=null,M9=!1}Go();const IDe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LDe=[`cache`,`tmp`];function RDe(e){let t=B(e,_e);if(!(()=>{if(!V(t))return!0;try{return lu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of IDe)V(B(e,t))&&n.push(t);for(let t of LDe){let r=B(e,t);try{V(r)&&mu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zDe(e){let t=ld(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 I9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function BDe(e){$L();let t=e.projectDir??e.contentDir,n=kpe({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}})}Es({localSink:n?.telemetry}),P9(t),SDe(),CDe();let{kind:r,gitdir:i}=zDe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=_s(i));let o=Dpe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>rs(`ok.boot`,{attributes:a},async()=>VDe(e)),l=()=>{if(s)try{let e=Uo.extract(Ko.active(),{traceparent:s});return Ko.with(e,c)}catch(e){I(`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 VDe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??I(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?qz(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new Kz("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-BRHlHA0v.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=B(m,`.ok`);if(!V(B(h,`config.yml`)))throw new Y8(V(h)?`config`:`okdir`,m);let g=B(h,`.gitignore`);V(g)||I(`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??ZW;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof JW||e instanceof YW){let t=e instanceof YW?e.detected:``,n=e instanceof YW?`too_old`:`not_available`;gG(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 Ts(),await Promise.race([F9(),new Promise(e=>setTimeout(e,I9))]),e}let v=RDe(h);v.length>0&&I(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${_e}/.`);let y=f9({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:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne}=y,O=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),k=e.port??0,re=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${O}:${k}`,log:r}),A=l();A.headersTimeout=3e4,A.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:vQ({contentFilter:y.contentFilter,contentSirv:cc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),ae=!1;if(e.reactShellDistDir)try{nL(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof tL)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 j=e.reactShellDistDir?cc(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,oe=e.ephemeral?null:new tD({contentDir:e.contentDir,localDir:T,globalDir:B(vu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:D,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://${O}:${k}`,getMcpStdioCommand:()=>eD(e.localOpCliArgs,k),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});oe!==null&&await oe.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let se=`pending`;C.then(()=>{se=`ready`},()=>{se=`failed`});let ce=q8({httpServer:A,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:re,remoteAccess:i,health:{readiness:()=>se,degraded:()=>w},log:r,sessionManager:te,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:j,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;a!==null&&(ue=MQ({httpServer:A,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await L9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);A.once(`error`,r),A.listen(e.port,e.host,()=>{A.removeListener(`error`,r),t()})})}catch(e){if(ae)try{aL(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let de=eR();de!==void 0&&tR(`httpListenMs`,de);let fe=A.address(),M=typeof fe==`object`&&fe?fe.port:e.port??0;if(k=M,f(T,M),ae&&rL(T,M),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${I9}ms`))},I9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(pe)return;pe=!0,se=`draining`;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),ae&&Vfe(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`mount.shutdown`,()=>ce.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{A.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{A.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),ae&&await t(`releaseUiLock`,async()=>aL(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Ts()),await t(`teardownToleranceTelemetry`,()=>F9()),await t(`flushLogFileSinks`,()=>Ms.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await C9({projectDir:m,skillsRoot:B(e.contentDir,`.ok`,`skills`),inPlaceNames:S9(e.contentDir,XI(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?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=vu(),t=await C9({projectDir:e,skillsRoot:B(e,`.ok`,`skills`),hostRoots:TDe,inPlaceNames:S9(e,ZI(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?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await FDe({projectDir:m,skillsRoot:B(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:A,destroy:le,lockDir:T,contentDir:e.contentDir,port:M,ready:C,degraded:w,didAutoInit:p,serverInstance:y,runtime:Iwe(y,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:oe}}async function L9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new kQ(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=ud(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(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=Vs({baseDir:n,timeout:{block:5e3}});s=new Set(await zb(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=Ix(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 HDe=ke;function UDe(e={}){let t=e.home??vu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}var R9=t(Fs(),1);const z9=R(vu(),`.ok`,`logs`),WDe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function GDe(){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 KDe(e){ou(e,{recursive:!0})}function B9(){return new Date().toISOString().slice(0,10)}function qDe(e){try{if(mu(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{du(n,r)}catch{}}try{hu(`${e}.3`)}catch{}}function JDe(e){try{let t=Date.now(),n=10080*60*1e3,r=lu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=mu(R(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{hu(R(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{hu(R(e,t.name)),a-=t.size}catch{}}}catch{}}function YDe(e){KDe(z9);let t=B9(),n=e.filePath??R(z9,`${e.name}.${t}.log`);qDe(n),(e._setTimeout??setTimeout)(()=>JDe(z9),5e3).unref();let r=R9.default.destination({dest:n,append:!0,sync:!0});return(0,R9.default)({level:GDe(),name:e.name,redact:{paths:WDe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:R9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function XDe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[R9.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 ZDe(e){return R(z9,`${e}.${B9()}.log`)}function QDe(){return z9}function $De(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=L(t);if(r===t)return null;t=r,n+=1}return null}const V9=Ru(Vl),H9=I(`project-git`);var U9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function W9(e,t){try{let{stdout:n}=await V9(e,[`rev-parse`,`--is-inside-work-tree`],xN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function eOe(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!mu(n).isDirectory()||V(r))return{didInit:!1};H9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=ZW()}catch(e){throw e instanceof JW||e instanceof YW?(gG(e),H9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof YW?`too_old`:`not_available`,detectedVersion:e instanceof YW?e.detected:``},e instanceof YW?`git binary too old`:`git binary not found`)):H9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await W9(o,t))return{didInit:!1};let s=``;try{s=(await V9(o,[`init`,`--initial-branch=main`,t],xN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new U9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!V(r))throw new U9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(H9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(H9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,tOe=jr.map(e=>e.replace(/\/$/,``));async function nOe(e){let t=ud(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(oOe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Hs(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Bs(async()=>{let t=await rOe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await iOe(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=Hs(e,{gitIndexFile:R(xu(),`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 aOe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await Hz(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ws(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 \`${kn}\` 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 tOe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function rOe(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 iOe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function aOe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function oOe(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function sOe(e,t){let n;try{n=Bl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=L(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await Tu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=L(t);if(r===t)return;t=r}}const cOe=[{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 cOe)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 lOe(e){if(!Px(e))throw new $9(e);let t;try{t=U(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!mu(t).isFile())throw new Q9(e);let n=L(t),r=Ez(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Ix(z(uOe(e),t).split(Ql).join(`/`)),canonicalFilePath:t}}let i=Kl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Ix(i)}}function uOe(e){return B(e,$o({absPath:ts(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function dOe(e){let t=su(B(xu(),`ok-ephemeral-`)),n=B(t,`.ok`);return ou(n,{recursive:!0}),gu(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),gu(B(n,`.gitignore`),`local/
2030
+ `))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 ye.flushDeferredStores(`discard-stale`),n=!0,we?.emitBranchSwitched(i)}finally{N.abortBranchSwitch(r),n||(te(!1),await ye.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&_e.current&&r>0){let t=f??`.`;try{let n=await wx(_e.current,t,e.oldHead,e.newHead,i);Hb(),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`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=Vk(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=Ix(e),a=be.documents.get(i);if(!a)continue;let o=$e(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=Vk(z(t,R(n,r)));if(e.startsWith(`..`))continue;let i=be.documents.get(Ix(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=yDe(m),h=O();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new hDe({projectDir:n,contentDir:t,contentFilter:ge,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{te(e),e||ye.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=_e.current;n&&await Ex(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=_e.current;n&&await Ex(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 ms({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ae(t.error),configPath:ts(`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 ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}ze(`files`),N.announceReadyViews();let g=eR();g!==void 0&&tR(`readyMs`,g),oe()}return _t().then(Ie,e=>{N.close(),Le(e)}),{hocuspocus:be,durabilityState:x,sessionManager:xe,nativeApi:Se,cc1Broadcaster:we,agentFocusBroadcaster:F,agentPresenceBroadcaster:Ee,maintenanceCoordinator:ve,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:ht,ready:Re,degraded:gt,lockDir:de,get syncEngine(){return ft},getLinkPreviewsEnabled:ie,resolveEmbed:me,acpRegistry:fe,acpPermissions:M}}function p9(e){return e/1048576}function xDe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:p9(e.rss),heapTotalMb:p9(e.heapTotal),heapUsedMb:p9(e.heapUsed),externalMb:p9(e.external),arrayBuffersMb:p9(e.arrayBuffers)}}}let m9=null,h9=null,g9=null;const _9=1e6;let v9=null,y9=null;ns(()=>{m9=null,h9=null,g9=null,v9?.disable(),v9=null,y9=null});function SDe(){if(m9)return;let e=Ds().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}=xDe();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`})}),m9=e}function CDe(){if(!h9){let e=Ds().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(!v9){v9=pte({resolution:20}),v9.enable();return}e.observe(v9.percentile(50)/_9,{stat:`p50`}),e.observe(v9.percentile(99)/_9,{stat:`p99`}),v9.reset()}),h9=e}if(!g9){let e=Ds().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=y9;if(y9={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`}))}),g9=e}}const b9=I(`skill-migrate`);function x9(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=fO.indexOf(e.host),r=fO.indexOf(t.host);return(n===-1?fO.length:n)-(r===-1?fO.length:r)||e.host.localeCompare(t.host)})}const wDe=x9(Fa),TDe=x9(Ht);function EDe(e,t){hs(L(t),{recursive:!0});try{cs(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;vs(e,t,{recursive:!0}),ys(e,{recursive:!0,force:!0})}}function DDe(e,t,n){let r=mI(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 S9(e,t){let n;try{n=U(B(e,`.ok`,`skills`))}catch{n=B(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(B(e,t.dir)).startsWith(n+Ql)}catch{return!0}}).map(e=>e.name))}async function C9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??wDe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=lu(n)}catch{return a}let s=z(t,n).split(Ql).join(`/`),c=new Set;for(let[e,n]of Object.entries(JX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!mi.test(e)||FF.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=B(n,e);if(!V(R(o,`SKILL.md`)))continue;let s=tO(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=B(t,r);return{host:n,root:r,path:R(i,e),escapes:SI(t,i),state:DDe(R(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`&&V(B(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`?ys(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ys(d.path,{recursive:!0,force:!0}),EDe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ys(e.path,{recursive:!0,force:!0}),vs(d.path,e.path,{recursive:!0}));await XN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),b9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),b9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const w9=I(`skill-reconcile`),ODe=FF;function T9(){let e=[];for(let t of _r){let n=Fa[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function kDe(e,t){let n=z(e,B(t));return Yl(n)?B(t):n}function E9(e){let{frontmatter:t,body:n}=Mo(e),r={};if(t!==``)try{let e=(0,kk.parse)(Qr(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function ADe(e,t){let n=E9(e),r=E9(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 D9(e,t){let n=O9(e),r=O9(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=R(e,o),c=R(t,o);if(i+=mu(s).size+mu(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!ADe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function O9(e,t=``){let n=[];for(let r of lu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...O9(R(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function k9(e,t,n){ys(t,{recursive:!0,force:!0}),hs(e,{recursive:!0}),ds(kDe(e,n),t,`dir`)}function A9(e,t){try{let n=uu(e);return B(Yl(n)?n:B(L(e),n))===B(t)}catch{return!1}}function jDe(e,t){try{let n=uu(e),r=Yl(n)?B(n):B(L(e),n);if(!V(r))return!1;let i=z(B(t),r);return i!==``&&(i.startsWith(`..`)||Yl(i))}catch(t){return w9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const MDe=[..._r,`agents`];function NDe(e){for(let t of MDe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function PDe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=lu(n)}catch{return}let i=T9();for(let e of r){let r=NDe(e);if(r===null)continue;let a=B(n,e),o=B(n,r);if(V(o))try{let n=au(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(R(a,`SKILL.md`))||!V(R(o,`SKILL.md`))||!D9(o,a))continue;for(let{rel:n}of i){let r=B(t,n);if(SI(t,r))continue;let i=R(r,e);A9(i,a)&&k9(r,i,o)}ys(a,{recursive:!0,force:!0}),w9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){w9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function FDe(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 T9()){let o=B(t,e);if(!V(o)||SI(t,o))continue;let s;try{s=lu(o)}catch(e){w9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(ODe.has(e))continue;let t=R(o,e),s=B(n,e),c=V(s);try{let l=au(t);if(l.isSymbolicLink()){if(A9(t,s)&&c)continue;if(jDe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(k9(o,t,s),r.healed.push({name:e,editor:i})):(ys(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!mi.test(e)){w9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&D9(t,s)){k9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){w9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=qN(t);for(let[r,a]of i){let i=B(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await YN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??_I(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){w9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{PDe({projectDir:t,skillsRoot:n})}catch(e){w9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let j9=null,M9=!1;function N9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function P9(e){if(!N9())return;let t=PA(e);j9=new Is({currentPath:B(t,`tolerance-telemetry.jsonl`),previousPath:B(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Ka(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};j9?.append(`${JSON.stringify(t)}\n`).catch(e=>{M9||(M9=!0,I(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function F9(){Ka(null),await j9?.drain(),j9=null,M9=!1}Go();const IDe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],LDe=[`cache`,`tmp`];function RDe(e){let t=B(e,_e);if(!(()=>{if(!V(t))return!0;try{return lu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of IDe)V(B(e,t))&&n.push(t);for(let t of LDe){let r=B(e,t);try{V(r)&&mu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function zDe(e){let t=ld(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 I9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function BDe(e){$L();let t=e.projectDir??e.contentDir,n=kpe({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}})}Es({localSink:n?.telemetry}),P9(t),SDe(),CDe();let{kind:r,gitdir:i}=zDe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=_s(i));let o=Dpe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>rs(`ok.boot`,{attributes:a},async()=>VDe(e)),l=()=>{if(s)try{let e=Uo.extract(Ko.active(),{traceparent:s});return Ko.with(e,c)}catch(e){I(`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 VDe(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??I(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?qz(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new Kz("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-f0YUD9MT.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=B(m,`.ok`);if(!V(B(h,`config.yml`)))throw new Y8(V(h)?`config`:`okdir`,m);let g=B(h,`.gitignore`);V(g)||I(`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??ZW;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof JW||e instanceof YW){let t=e instanceof YW?e.detected:``,n=e instanceof YW?`too_old`:`not_available`;gG(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 Ts(),await Promise.race([F9(),new Promise(e=>setTimeout(e,I9))]),e}let v=RDe(h);v.length>0&&I(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${_e}/.`);let y=f9({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:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne}=y,O=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),k=e.port??0,re=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${O}:${k}`,log:r}),A=l();A.headersTimeout=3e4,A.requestTimeout=6e4;let ie=e.serveContentAssets===!1?void 0:vQ({contentFilter:y.contentFilter,contentSirv:cc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:ee,assetExtensions:c,blocklistExtensions:x}),ae=!1;if(e.reactShellDistDir)try{nL(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ae=!0}catch(e){if(e instanceof tL)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 j=e.reactShellDistDir?cc(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,oe=e.ephemeral?null:new tD({contentDir:e.contentDir,localDir:T,globalDir:B(vu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:te,agentPresenceBroadcaster:D,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://${O}:${k}`,getMcpStdioCommand:()=>eD(e.localOpCliArgs,k),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});oe!==null&&await oe.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let se=`pending`;C.then(()=>{se=`ready`},()=>{se=`failed`});let ce=q8({httpServer:A,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:re,remoteAccess:i,health:{readiness:()=>se,degraded:()=>w},log:r,sessionManager:te,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ie,reactShellMiddleware:j,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;a!==null&&(ue=MQ({httpServer:A,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await L9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);A.once(`error`,r),A.listen(e.port,e.host,()=>{A.removeListener(`error`,r),t()})})}catch(e){if(ae)try{aL(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let de=eR();de!==void 0&&tR(`httpListenMs`,de);let fe=A.address(),M=typeof fe==`object`&&fe?fe.port:e.port??0;if(k=M,f(T,M),ae&&rL(T,M),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${I9}ms`))},I9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(pe)return;pe=!0,se=`draining`;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),ae&&Vfe(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`mount.shutdown`,()=>ce.shutdown()),re!==void 0&&await t(`mcpHttpHandler.close`,()=>re.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{A.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{A.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),ae&&await t(`releaseUiLock`,async()=>aL(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>Ts()),await t(`teardownToleranceTelemetry`,()=>F9()),await t(`flushLogFileSinks`,()=>Ms.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await C9({projectDir:m,skillsRoot:B(e.contentDir,`.ok`,`skills`),inPlaceNames:S9(e.contentDir,XI(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?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=vu(),t=await C9({projectDir:e,skillsRoot:B(e,`.ok`,`skills`),hostRoots:TDe,inPlaceNames:S9(e,ZI(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?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await FDe({projectDir:m,skillsRoot:B(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:A,destroy:le,lockDir:T,contentDir:e.contentDir,port:M,ready:C,degraded:w,didAutoInit:p,serverInstance:y,runtime:Iwe(y,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:oe}}async function L9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new kQ(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=ud(n),t=e?R(e,`MERGE_HEAD`):null;if(!t||!V(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=Vs({baseDir:n,timeout:{block:5e3}});s=new Set(await zb(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=Ix(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 HDe=ke;function UDe(e={}){let t=e.home??vu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(R(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(R(r.APPDATA??R(t,`AppData`,`Roaming`),`Claude`)):!1}var R9=t(Fs(),1);const z9=R(vu(),`.ok`,`logs`),WDe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function GDe(){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 KDe(e){ou(e,{recursive:!0})}function B9(){return new Date().toISOString().slice(0,10)}function qDe(e){try{if(mu(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{du(n,r)}catch{}}try{hu(`${e}.3`)}catch{}}function JDe(e){try{let t=Date.now(),n=10080*60*1e3,r=lu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=mu(R(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{hu(R(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{hu(R(e,t.name)),a-=t.size}catch{}}}catch{}}function YDe(e){KDe(z9);let t=B9(),n=e.filePath??R(z9,`${e.name}.${t}.log`);qDe(n),(e._setTimeout??setTimeout)(()=>JDe(z9),5e3).unref();let r=R9.default.destination({dest:n,append:!0,sync:!0});return(0,R9.default)({level:GDe(),name:e.name,redact:{paths:WDe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:R9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function XDe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[R9.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 ZDe(e){return R(z9,`${e}.${B9()}.log`)}function QDe(){return z9}function $De(e){let t=B(e),n=0;for(;n<30;){let e=!1;try{e=V(B(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=L(t);if(r===t)return null;t=r,n+=1}return null}const V9=Ru(Vl),H9=I(`project-git`);var U9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function W9(e,t){try{let{stdout:n}=await V9(e,[`rev-parse`,`--is-inside-work-tree`],xN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function eOe(e){let t=B(e),n=B(t,`.git`),r=B(n,`HEAD`),i=!1;if(V(n)){if(!mu(n).isDirectory()||V(r))return{didInit:!1};H9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=ZW()}catch(e){throw e instanceof JW||e instanceof YW?(gG(e),H9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof YW?`too_old`:`not_available`,detectedVersion:e instanceof YW?e.detected:``},e instanceof YW?`git binary too old`:`git binary not found`)):H9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await W9(o,t))return{didInit:!1};let s=``;try{s=(await V9(o,[`init`,`--initial-branch=main`,t],xN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new U9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!V(r))throw new U9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(H9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(H9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=I(`project-skill-git`),K9=/^[0-9a-f]{40}$/,tOe=jr.map(e=>e.replace(/\/$/,``));async function nOe(e){let t=ud(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(oOe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Hs(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Bs(async()=>{let t=await rOe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await iOe(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=Hs(e,{gitIndexFile:R(xu(),`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 aOe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await Hz(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Ws(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 \`${kn}\` 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 tOe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function rOe(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 iOe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function aOe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function oOe(e){return V(R(e,`MERGE_HEAD`))||V(R(e,`rebase-merge`))||V(R(e,`rebase-apply`))||V(R(e,`CHERRY_PICK_HEAD`))||V(R(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function sOe(e,t){let n;try{n=Bl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=L(n),r=0;r<32;r+=1){let n=R(t,`package.json`);if(V(n))try{let t=JSON.parse(await Tu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=L(t);if(r===t)return;t=r}}const cOe=[{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 cOe)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 lOe(e){if(!Px(e))throw new $9(e);let t;try{t=U(B(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!mu(t).isFile())throw new Q9(e);let n=L(t),r=Ez(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Ix(z(uOe(e),t).split(Ql).join(`/`)),canonicalFilePath:t}}let i=Kl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Ix(i)}}function uOe(e){return B(e,$o({absPath:ts(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function dOe(e){let t=su(B(xu(),`ok-ephemeral-`)),n=B(t,`.ok`);return ou(n,{recursive:!0}),gu(B(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),gu(B(n,`.gitignore`),`local/
2031
2031
  `,`utf-8`),t}export{Y2 as $,Ax as $i,rL as $n,BM as $r,JW as $t,Y7 as A,Jw as Ai,UR as An,WP as Ar,hQ as At,d7 as B,qx as Bi,kR as Bn,AN as Br,Oq as Bt,f9 as C,Qu as Ca,qE as Ci,Gz as Cn,SF as Cr,bQ as Ct,X7 as D,Pw as Di,LR as Dn,$P as Dr,spe as Dt,q7 as E,nT as Ei,Tz as En,QP as Er,RZ as Et,pEe as F,Mw as Fi,cz as Fn,HP as Fr,Cq as Ft,K8 as G,kx as Gi,yR as Gn,DN as Gr,Nq as Gt,J8 as H,Jx as Hi,SR as Hn,NN as Hr,zq as Ht,b7 as I,cS as Ii,Cz as In,VP as Ir,Lq as It,z8 as J,Sx as Ji,HL as Jn,xN as Jr,bq as Jt,W8 as K,bx as Ki,fR as Kn,SN as Kr,kq as Kt,y7 as L,K as Li,sz as Ln,ade as Lr,Fq as Lt,L7 as M,Bw as Mi,oz as Mn,GP as Mr,Xq as Mt,P7 as N,lw as Ni,tz as Nn,UP as Nr,qq as Nt,G7 as O,Xw as Oi,lz as On,XP as Or,cpe as Ot,v7 as P,uw as Pi,HR as Pn,ode as Pr,Hq as Pt,W2 as Q,yx as Qi,aL as Qn,UM as Qr,gG as Qt,tEe as R,sS as Ri,BR as Rn,hP as Rr,Rq as Rt,F9 as S,dd as Sa,tD as Si,qz as Sn,Qde as Sr,EQ as St,W7 as T,eT as Ti,Ez as Tn,ZP as Tr,zZ as Tt,Y8 as U,Zx as Ui,wR as Un,jN as Ur,jq as Ut,c7 as V,Qx as Vi,xR as Vn,kN as Vr,Iq as Vt,q8 as W,Kx as Wi,CR as Wn,MN as Wr,Aq as Wt,H2 as X,wx as Xi,nL as Xn,oN as Xr,vG as Xt,k8 as Y,_x as Yi,tL as Yn,sN as Yr,bG as Yt,U2 as Z,hx as Zi,iL as Zn,WM as Zr,hG as Zt,HDe as _,Zd as _a,Uk as _i,EU as _n,WF as _r,TQ as _t,lOe as a,dx as aa,kM as ai,rG as an,iI as ar,t_e as at,P9 as b,hd as ba,_D as bi,eB as bn,PF as br,CQ as bt,nOe as c,ex as ca,xM as ci,HW as cn,nI as cr,K0 as ct,$De as d,$m as da,_M as di,CU as dn,rI as dr,yme as dt,px as ea,Vle as ei,YW as en,pI as er,p_e as et,YDe as f,Qm as fa,yM as fi,wU as fn,JF as fr,h1 as ft,UDe as g,Ud as ga,FA as gi,_U as gn,HF as gr,SQ as gt,QDe as h,Xd as ha,NA as hi,TU as hn,GF as hr,DQ as ht,dOe as i,jx as ia,Ole as ii,XW as in,sI as ir,e_e as it,U7 as j,Yw as ji,uz as jn,KP as jr,HZ as jt,J7 as k,$w as ki,WR as kn,dde as kr,_Q as kt,U9 as l,qb as la,cle as li,zW as ln,tI as lr,S1 as lt,ZDe as m,eh as ma,PA as mi,OU as mn,qF as mr,MQ as mt,Z9 as n,Ex as na,Ble as ni,ZW as nn,gfe as nr,F2 as nt,X9 as o,ix as oa,IM as oi,$W as on,aI as or,n_e as ot,XDe as p,th as pa,vM as pi,yU as pn,KF as pr,v1 as pt,H8 as q,xx as qi,XL as qn,TN as qr,yq as qt,$9 as r,Dx as ra,zle as ri,mG as rn,lI as rr,A2 as rt,sOe as s,nx as sa,ule as si,UW as sn,oI as sr,w2 as st,Q9 as t,Ox as ta,Rle as ti,KW as tn,fI as tr,I2 as tt,eOe as u,zoe as ua,bM as ui,hU as un,ife as ur,e1 as ut,BDe as v,Hd as va,ok as vi,tB as vn,LF as vr,xQ as vt,d9 as w,Zu as wa,eD as wi,Wz as wn,dF as wr,vQ as wt,N9 as x,zd as xa,hD as xi,Qz as xn,zF as xr,Cpe as xt,L9 as y,gd as ya,yD as yi,Kz as yn,RF as yr,wQ as yt,f7 as z,eS as zi,OR as zn,Wue as zr,Dq as zt};
2032
- //# sourceMappingURL=src-CSv3k56d.mjs.map
2032
+ //# sourceMappingURL=src-BxACkU3c.mjs.map