@inkeep/open-knowledge 0.64.0-beta.3 → 0.64.0-beta.5

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 (380) hide show
  1. package/dist/{acp-harness-probe-DDqiQmm_.mjs → acp-harness-probe-Bz_Xfqhw.mjs} +2 -2
  2. package/dist/cli.mjs +6 -6
  3. package/dist/constants-BgJb28Cb.mjs +2 -0
  4. package/dist/git-handle-Bh1alj7a.mjs +1 -0
  5. package/dist/{git-handle-29BNYqgw.mjs → git-handle-UnQwrdlT.mjs} +2 -2
  6. package/dist/index.d.mts +69 -21
  7. package/dist/index.mjs +157 -157
  8. package/dist/init-Cpnor43q.mjs +1 -0
  9. package/dist/{init-8KXad73_.mjs → init-JIlCRbdu.mjs} +3 -3
  10. package/dist/{launch-json-removal-BwH0QFXd.mjs → launch-json-removal-D1H1a769.mjs} +2 -2
  11. package/dist/{loader-COdw9cCC.mjs → loader-BkOiHFr0.mjs} +2 -2
  12. package/dist/loader-ROlCo-Nz.mjs +1 -0
  13. package/dist/md-manager-BJ88tow5.mjs +2 -0
  14. package/dist/{open-browser-aU_PSdrG.mjs → open-browser-CrMsTPIV.mjs} +2 -2
  15. package/dist/parse-worker.mjs +1 -1
  16. package/dist/{preview-DLUqlPI6.mjs → preview-BF5V_rVP.mjs} +2 -2
  17. package/dist/preview-PgQuIcNJ.mjs +1 -0
  18. package/dist/public/assets/{ActivityModeContent-DVp1gZjW.js → ActivityModeContent-CauWCpUS.js} +1 -1
  19. package/dist/public/assets/{AddPropertiesButton-B4mgksK9.js → AddPropertiesButton-BNouQBfs.js} +1 -1
  20. package/dist/public/assets/{AgentDiffPane-CxHgKni7.js → AgentDiffPane-DXQNRZ8O.js} +1 -1
  21. package/dist/public/assets/{AgentThreadClientBinder-DjPyJZC2.js → AgentThreadClientBinder-5zJFp5cf.js} +1 -1
  22. package/dist/public/assets/{AppMenubar-D2MAtGAz.js → AppMenubar-ywn95n5_.js} +1 -1
  23. package/dist/public/assets/{BugReportHistory-CVve2Axu.js → BugReportHistory-BATOeSHw.js} +1 -1
  24. package/dist/public/assets/{BugReportHistoryDialog-Ba061U9i.js → BugReportHistoryDialog-sIMmVxt-.js} +1 -1
  25. package/dist/public/assets/CodeMirrorPropInput-DX8Yunfs.js +3 -0
  26. package/dist/public/assets/{ConfigSharingInfoTooltip-BAHlj9xZ.js → ConfigSharingInfoTooltip-CmY8gl8k.js} +1 -1
  27. package/dist/public/assets/{ConsentDialogBody-CzH4EuI3.js → ConsentDialogBody-C4z025ef.js} +1 -1
  28. package/dist/public/assets/{DiffView-D8XUmPm-.js → DiffView-BgxYEqNK.js} +1 -1
  29. package/dist/public/assets/{DocumentContext-DKudm1-z.js → DocumentContext-BV7jb-np.js} +20 -20
  30. package/dist/public/assets/{EditorModeToggle-D6L8r63B.js → EditorModeToggle-B8yEewMp.js} +1 -1
  31. package/dist/public/assets/{EnableSyncConfirmDialog-BZuygRVh.js → EnableSyncConfirmDialog-uAw_zEkg.js} +1 -1
  32. package/dist/public/assets/{ExcalidrawDocEditor-D2QIjqhX.js → ExcalidrawDocEditor-DhTxtSyA.js} +4 -4
  33. package/dist/public/assets/FeedbackForm-DJ9TwFhA.js +1 -0
  34. package/dist/public/assets/{GraphPanel-ByInPd3a.js → GraphPanel-Brg6YDja.js} +2 -2
  35. package/dist/public/assets/{ImportSkillDialog-BAk-BVT8.js → ImportSkillDialog-BYfuLW-m.js} +1 -1
  36. package/dist/public/assets/{LintConfigEditor-a6yi3Ww5.js → LintConfigEditor-pJBzAP1G.js} +1 -1
  37. package/dist/public/assets/ManagedArtifactProperties-CFDGVAK1.js +1 -0
  38. package/dist/public/assets/{ManagedArtifactProperties-D8geiZjG.js → ManagedArtifactProperties-D1f8Frip.js} +1 -1
  39. package/dist/public/assets/{McpConsentDialogBody-DVBhoRAw.js → McpConsentDialogBody-Da_YGlKw.js} +1 -1
  40. package/dist/public/assets/{Mermaid-C9X7cjZ1.js → Mermaid-BAKMqFxz.js} +2 -2
  41. package/dist/public/assets/{MermaidDocEditor-04iIKbvP.js → MermaidDocEditor-DVxgZCM4.js} +1 -1
  42. package/dist/public/assets/{PropertyDisplayRow-Cn7uHncy.js → PropertyDisplayRow-9aYyPFhc.js} +2 -2
  43. package/dist/public/assets/{RegisteredAgentIcon-DIfsdEiW.js → RegisteredAgentIcon-C5l0ngck.js} +1 -1
  44. package/dist/public/assets/ReportBugDialogBody-YQEEGPWa.js +3 -0
  45. package/dist/public/assets/ReportBugMenuTrigger-BYHhqbyX.js +2 -0
  46. package/dist/public/assets/{RowDisclosure-BTtG2df8.js → RowDisclosure-BD4HJbRH.js} +1 -1
  47. package/dist/public/assets/{SchemaConfigEditor-fWpkoH9e.js → SchemaConfigEditor-0hGeiywr.js} +1 -1
  48. package/dist/public/assets/{SessionsHost-BbabLBoa.js → SessionsHost-BegjN_Wv.js} +2 -2
  49. package/dist/public/assets/SettingsDialogBody-Bng9Ek1r.js +12 -0
  50. package/dist/public/assets/{ShareBranchSwitchDialog-CPFRMiPb.js → ShareBranchSwitchDialog-DNMbGcR3.js} +1 -1
  51. package/dist/public/assets/{ShareReceiveDialog-DHygzplb.js → ShareReceiveDialog-CxRzoJmJ.js} +1 -1
  52. package/dist/public/assets/{ShareReceiveMissDialog-DDYsfJz-.js → ShareReceiveMissDialog-C2M-0S6A.js} +1 -1
  53. package/dist/public/assets/{SkillCostValue-Dh3W83GI.js → SkillCostValue-0sdQK-kg.js} +1 -1
  54. package/dist/public/assets/{SkillEditBanner-Dmd9x2GL.js → SkillEditBanner-BIAkDbBb.js} +1 -1
  55. package/dist/public/assets/SkillInstallMenu-C5Y79gdz.js +2 -0
  56. package/dist/public/assets/{SkillOriginInline-DPbc95eY.js → SkillOriginInline-C35IR2C_.js} +1 -1
  57. package/dist/public/assets/{SkillToolbarControls-CiKYhqeu.js → SkillToolbarControls-DEiTj33j.js} +1 -1
  58. package/dist/public/assets/{SlidesToolbarControls-DukKIknR.js → SlidesToolbarControls-Bua5dOtR.js} +1 -1
  59. package/dist/public/assets/SourceEditor-DzxE90kB.js +1 -0
  60. package/dist/public/assets/{TerminalPanel-niWqOudS.js → TerminalPanel-EZTkF_Im.js} +3 -3
  61. package/dist/public/assets/{TerminalStartingNotice-LVCAO53j.js → TerminalStartingNotice-5YXAirXU.js} +1 -1
  62. package/dist/public/assets/TerminalWindowApp-zabnp2hc.js +1 -0
  63. package/dist/public/assets/{TextDocEditor-DYyxuF3J.js → TextDocEditor-5pSurn6C.js} +1 -1
  64. package/dist/public/assets/{ThemePicker-DXALMWUA.js → ThemePicker-BEVvKk5L.js} +1 -1
  65. package/dist/public/assets/{ThreadView-Dg2ocFRD.js → ThreadView-DY925XKN.js} +7 -7
  66. package/dist/public/assets/{TimelineDiffPane-Dq7qjm7t.js → TimelineDiffPane-BOSthuzR.js} +1 -1
  67. package/dist/public/assets/{abnfDiagram-N423BO3Z-CcNzibSW.js → abnfDiagram-N423BO3Z-DBJ3AZ9J.js} +1 -1
  68. package/dist/public/assets/{agent-diff-store-B3dLX7vR.js → agent-diff-store-CWlSMAcS.js} +1 -1
  69. package/dist/public/assets/{alert-dialog-v-lStrvw.js → alert-dialog-BV3f4Vr2.js} +1 -1
  70. package/dist/public/assets/{architectureDiagram-T3A2C74G-x7KhBP2B.js → architectureDiagram-T3A2C74G-DHhiMV1e.js} +1 -1
  71. package/dist/public/assets/arrow-up-right-BTi7mHwL.js +1 -0
  72. package/dist/public/assets/auth-state-cache-DN_6SHvB.js +11 -0
  73. package/dist/public/assets/{badge-zJWUwhkd.js → badge-52pHek8I.js} +1 -1
  74. package/dist/public/assets/{blockDiagram-VBNYF7ZC-_DUjKmqC.js → blockDiagram-VBNYF7ZC-B0XVQOlY.js} +1 -1
  75. package/dist/public/assets/{braces-DmS8bWjv.js → braces-Bzye844v.js} +1 -1
  76. package/dist/public/assets/{bug-report-send-manager-CXIJIjU-.js → bug-report-send-manager-idwD-g0s.js} +1 -1
  77. package/dist/public/assets/{button-CA0dewJJ.js → button-Cym3gapE.js} +1 -1
  78. package/dist/public/assets/{c4Diagram-5PPSVZJV-BvXPINTk.js → c4Diagram-5PPSVZJV-C0fXVzxK.js} +1 -1
  79. package/dist/public/assets/{calendar-D-m9ekuo.js → calendar-P1YHNDVH.js} +1 -1
  80. package/dist/public/assets/{case-sensitive-m-hzm2Fd.js → case-sensitive-BwklrMJw.js} +1 -1
  81. package/dist/public/assets/channel-Bw1oZ3oX.js +1 -0
  82. package/dist/public/assets/check-Dut4Aov8.js +1 -0
  83. package/dist/public/assets/{checkbox-C60ghXVs.js → checkbox-UfDS9TpS.js} +1 -1
  84. package/dist/public/assets/{chevron-down-Dkq_Sx62.js → chevron-down-DNO3PgI_.js} +1 -1
  85. package/dist/public/assets/chevron-left-Dhf0Sw0W.js +1 -0
  86. package/dist/public/assets/chevron-right-4mYNnAZZ.js +1 -0
  87. package/dist/public/assets/{chunk-2GRJ4B5K-Cj6-Oom3.js → chunk-2GRJ4B5K-I9g7v43C.js} +1 -1
  88. package/dist/public/assets/{chunk-3NCLNEKW-Bd-QhfAE.js → chunk-3NCLNEKW-CIPZUTs2.js} +1 -1
  89. package/dist/public/assets/{chunk-4I5QYGJK-DTmx7k3q.js → chunk-4I5QYGJK-CJSo7JWo.js} +1 -1
  90. package/dist/public/assets/{chunk-5RXB4S5H-szWjFIhQ.js → chunk-5RXB4S5H-CV_VIHj4.js} +1 -1
  91. package/dist/public/assets/{chunk-6Q2QTUOP-vClzZXZJ.js → chunk-6Q2QTUOP-HonjM1WC.js} +1 -1
  92. package/dist/public/assets/{chunk-7Z6QIM7H-CG3W4Gq4.js → chunk-7Z6QIM7H-C7MoQiZ1.js} +1 -1
  93. package/dist/public/assets/{chunk-BO2N2NFS-DhLAiJRz.js → chunk-BO2N2NFS-D2iiEks4.js} +4 -4
  94. package/dist/public/assets/{chunk-GF5L2VYU-D2VOXB1D.js → chunk-GF5L2VYU-DMKobWUK.js} +1 -1
  95. package/dist/public/assets/{chunk-I66GZJ75-BIJACljW.js → chunk-I66GZJ75-BUquu3u4.js} +1 -1
  96. package/dist/public/assets/{chunk-J7OUQ5F2-IIkcOqGv.js → chunk-J7OUQ5F2-D_xZJOyH.js} +2 -2
  97. package/dist/public/assets/{chunk-JQJVKLGR-QOce9PgS.js → chunk-JQJVKLGR-DEq8-3eQ.js} +1 -1
  98. package/dist/public/assets/{chunk-KBJHAD2P-B80ctoly.js → chunk-KBJHAD2P-D4Yduc8o.js} +1 -1
  99. package/dist/public/assets/{chunk-NSK5VX7P-DLJZ8VNx.js → chunk-NSK5VX7P-BW0NvKtJ.js} +1 -1
  100. package/dist/public/assets/{chunk-QR6OTTB3-DfBTRDdj.js → chunk-QR6OTTB3-BAd_wKMz.js} +1 -1
  101. package/dist/public/assets/{chunk-UBXNYLIW-zy0cmc7-.js → chunk-UBXNYLIW-xJmEmvG8.js} +1 -1
  102. package/dist/public/assets/{chunk-W5SLKNZC-dHRGG7r8.js → chunk-W5SLKNZC-9q5ZT0Or.js} +1 -1
  103. package/dist/public/assets/{chunk-WRU74C26-DC6Jygyt.js → chunk-WRU74C26-DEuLBlab.js} +1 -1
  104. package/dist/public/assets/{circle-alert-CeU2sqgg.js → circle-alert-b-E0_BIP.js} +1 -1
  105. package/dist/public/assets/classDiagram-JCYQIIEL-CrlbOdYD.js +1 -0
  106. package/dist/public/assets/classDiagram-v2-OCEON4UE-CrkjdB4S.js +1 -0
  107. package/dist/public/assets/client-version-BBQwLhqb.js +1 -0
  108. package/dist/public/assets/{cm-theme-CUQw2QSJ.js → cm-theme-CvD6eMwN.js} +1 -1
  109. package/dist/public/assets/{code-highlighter-impl-DQmjHoA2.js → code-highlighter-impl-CGDVGaGi.js} +1 -1
  110. package/dist/public/assets/{collapsible-COrqeoHr.js → collapsible-DYySK8La.js} +1 -1
  111. package/dist/public/assets/comment-chips-BtWBKUUL.js +5 -0
  112. package/dist/public/assets/{config-provider-DyH_5S1M.js → config-provider-BXiukxwE.js} +3 -3
  113. package/dist/public/assets/context-api-dUnlgSJr.js +1 -0
  114. package/dist/public/assets/{cynefinDiagram-MW4NZA55-CqGzh2Za.js → cynefinDiagram-MW4NZA55-Vp3Z3EOq.js} +1 -1
  115. package/dist/public/assets/{dagre-VZM6K2ZE-1ir2rJwc.js → dagre-VZM6K2ZE-BsNhh3lr.js} +1 -1
  116. package/dist/public/assets/{diagram-7IWD3JNH-Bj6PNtgh.js → diagram-7IWD3JNH-CntjEuMQ.js} +1 -1
  117. package/dist/public/assets/{diagram-B4RE2ZJO-Dz4Gdk3e.js → diagram-B4RE2ZJO-CxKY34wz.js} +1 -1
  118. package/dist/public/assets/{diagram-LBJQPF4R-DwZPbSOO.js → diagram-LBJQPF4R-CAoRKtuu.js} +1 -1
  119. package/dist/public/assets/{diagram-Q27KOJAE-DpBefHrG.js → diagram-Q27KOJAE-Bexqwg9W.js} +1 -1
  120. package/dist/public/assets/{diagram-UB23O5K3-CnYsy3bR.js → diagram-UB23O5K3-BO3f0yq6.js} +1 -1
  121. package/dist/public/assets/{dialog-CkCtHEOY.js → dialog-Ba9N5nEw.js} +1 -1
  122. package/dist/public/assets/{dist-BNjWPf5h.js → dist-4YFTUwt_.js} +1 -1
  123. package/dist/public/assets/{dist-BpVYX4pM2.js → dist-B6U1sHwQ2.js} +1 -1
  124. package/dist/public/assets/{dist-DJUH3LhV.js → dist-BDna-dOq.js} +1 -1
  125. package/dist/public/assets/{dist-C2xqTq7L.js → dist-BXlOzfrR.js} +1 -1
  126. package/dist/public/assets/dist-BY_vnlVW2.js +1 -0
  127. package/dist/public/assets/{dist-DsLZcVyZ.js → dist-BcvirUWL.js} +1 -1
  128. package/dist/public/assets/{dist-BF2Tao7_.js → dist-Bd3O90Cl.js} +1 -1
  129. package/dist/public/assets/{dist-gTGB_-tT.js → dist-Bn0BEeMP.js} +1 -1
  130. package/dist/public/assets/{dist-CSCWMTfQ.js → dist-CMrReMig.js} +1 -1
  131. package/dist/public/assets/{dist-Bun0_jqP.js → dist-CWL3ooGG.js} +1 -1
  132. package/dist/public/assets/{dist-aPIbpbAV.js → dist-CZYk4Gmy.js} +1 -1
  133. package/dist/public/assets/{dist-BTeDUJz7.js → dist-C_QZEaeX.js} +87 -87
  134. package/dist/public/assets/{dist-D_jhHcmP.js → dist-CfolydxL.js} +1 -1
  135. package/dist/public/assets/{dist-CUculQn6.js → dist-CkzVKD46.js} +1 -1
  136. package/dist/public/assets/{dist-BvwnbioL.js → dist-DRO03ovd.js} +1 -1
  137. package/dist/public/assets/{dist-D6nD_291.js → dist-DXjgrsHI.js} +1 -1
  138. package/dist/public/assets/{dist-DOg6TrZ3.js → dist-DatS2_-H.js} +1 -1
  139. package/dist/public/assets/{dist-BcWdMddd.js → dist-Dhtu02232.js} +1 -1
  140. package/dist/public/assets/{dist-DbEdNEy-2.js → dist-DnnH0RLX2.js} +1 -1
  141. package/dist/public/assets/{dist-C1JnQAE8.js → dist-Ds0ot8zG.js} +1 -1
  142. package/dist/public/assets/{dist-Cu8jzM5J.js → dist-GoOli512.js} +1 -1
  143. package/dist/public/assets/{dist-CtBjTqZn.js → dist-MhaicsMV.js} +1 -1
  144. package/dist/public/assets/dist-wcXwpuqG.js +1 -0
  145. package/dist/public/assets/{dist-DkdJazl9.js → dist-xXHzlM2r.js} +1 -1
  146. package/dist/public/assets/{doc-paths-DRMElswC.js → doc-paths-DMctW8qz.js} +1 -1
  147. package/dist/public/assets/{documents-events-DhF_sptK.js → documents-events-CwqQxQT5.js} +1 -1
  148. package/dist/public/assets/dropdown-menu-CRvS0_4-.js +1 -0
  149. package/dist/public/assets/{ebnfDiagram-BXEA7PRR-CbFOpeAM.js → ebnfDiagram-BXEA7PRR-DC58rQAn.js} +1 -1
  150. package/dist/public/assets/{erDiagram-JOGREHBK-CZ9JcnST.js → erDiagram-JOGREHBK-CUz9pdjc.js} +1 -1
  151. package/dist/public/assets/{es2015-wpLRKwCl.js → es2015-B9_uRFGw.js} +1 -1
  152. package/dist/public/assets/{eye-DrF_XrDR.js → eye-7pio2q9G.js} +1 -1
  153. package/dist/public/assets/{field-Ml4KaP--.js → field-XqXEu64v.js} +1 -1
  154. package/dist/public/assets/{file-tree-adapter-hJoW3AuD.js → file-tree-adapter-CpTo1U5h.js} +1 -1
  155. package/dist/public/assets/{file-tree-utils-Cb7_vXe_.js → file-tree-utils-DrK6l51M.js} +1 -1
  156. package/dist/public/assets/flowDiagram-UKHOOZJN-DHMrplYi.js +1 -0
  157. package/dist/public/assets/{folder-config-api-CBCo8vGy.js → folder-config-api-Dxuhqlqr.js} +1 -1
  158. package/dist/public/assets/{folder-open-BGKIxsBF.js → folder-open-BWpLO6wT.js} +1 -1
  159. package/dist/public/assets/{form-DWhbcQ6z.js → form-BntZOc7C.js} +1 -1
  160. package/dist/public/assets/{ganttDiagram-PKOTCBZU-BHB-hUMH.js → ganttDiagram-PKOTCBZU-C2NMWsS0.js} +1 -1
  161. package/dist/public/assets/{git-branch-CYpvbxHz.js → git-branch-3CSRgL0o.js} +1 -1
  162. package/dist/public/assets/{gitGraphDiagram-DS77QQ5N-ZJ5Y224L.js → gitGraphDiagram-DS77QQ5N-CVdMqGMX.js} +1 -1
  163. package/dist/public/assets/{globals-BuFIIVIr.css → globals-20k8qIHJ.css} +1 -1
  164. package/dist/public/assets/{hash-DdgzU_HC.js → hash-3VQG5UJ7.js} +1 -1
  165. package/dist/public/assets/{highlighted-body-OFNGDK62-PeS0VpT5.js → highlighted-body-OFNGDK62-UCUIw0Lt.js} +1 -1
  166. package/dist/public/assets/i18n-CHdOLU04.js +1 -0
  167. package/dist/public/assets/index-CEIpyn32.js +2204 -0
  168. package/dist/public/assets/{info-YXcJ2AqB.js → info-SlzbpjOb.js} +1 -1
  169. package/dist/public/assets/{infoDiagram-6WML65LV-BG7MF-gX.js → infoDiagram-6WML65LV-D2JV8LcI.js} +1 -1
  170. package/dist/public/assets/{input-group-Co1pGUva.js → input-group-DpVg5lNG.js} +1 -1
  171. package/dist/public/assets/{ishikawaDiagram-WSZJBQD7-B0JcQQJV.js → ishikawaDiagram-WSZJBQD7-YJJMNAlB.js} +1 -1
  172. package/dist/public/assets/{journeyDiagram-NVQOT4AX-CU6rukz3.js → journeyDiagram-NVQOT4AX-NC-EWDbF.js} +1 -1
  173. package/dist/public/assets/{kanban-definition-27J2QSJJ-XgZkt40N.js → kanban-definition-27J2QSJJ-A5wz4I7T.js} +1 -1
  174. package/dist/public/assets/{label-Bbz2bT-a.js → label-D-K3fWtj.js} +1 -1
  175. package/dist/public/assets/{launch-agent-thread-b9-Dv6tT.js → launch-agent-thread-J0X5JOlh.js} +1 -1
  176. package/dist/public/assets/{launcher-selection-Bld0AvL_.js → launcher-selection-Btzbq8G9.js} +1 -1
  177. package/dist/public/assets/{lib-BoSom6iA.js → lib-DmueaA5E.js} +1 -1
  178. package/dist/public/assets/{lib-D6L_wV12.js → lib-vOz_s3tj.js} +1 -1
  179. package/dist/public/assets/{line-B4oNUbqJ.js → line-BURCYBOK.js} +1 -1
  180. package/dist/public/assets/lint-config-client-pNtVqn1v.js +1 -0
  181. package/dist/public/assets/{lint-plugin-meta-C39uvKXt.js → lint-plugin-meta-LEBWvINg.js} +1 -1
  182. package/dist/public/assets/{list-plus-DZ9qXaBL.js → list-plus-nPRgk4Qi.js} +1 -1
  183. package/dist/public/assets/{local-menu-action-bus-CXdHCOml.js → local-menu-action-bus-BLEUyEvu.js} +1 -1
  184. package/dist/public/assets/{markdownlint-rule-browser-CajbFe11.js → markdownlint-rule-browser-IpH2V17S.js} +1 -1
  185. package/dist/public/assets/mermaid-GHXKKRXX-BmYrNHJr.js +1 -0
  186. package/dist/public/assets/{mermaid.core-CRAU02Cc.js → mermaid.core-C0IvVkS9.js} +3 -3
  187. package/dist/public/assets/mermaid.core-DhUKqb7Q.js +1 -0
  188. package/dist/public/assets/messages-B9v-Dl6o.js +1 -0
  189. package/dist/public/assets/messages-BNKgouAQ.js +1 -0
  190. package/dist/public/assets/messages-BWVpwygE.js +1 -0
  191. package/dist/public/assets/messages-BdoFX7Ke.js +1 -0
  192. package/dist/public/assets/messages-BozLzcJu.js +1 -0
  193. package/dist/public/assets/messages-C0rOkBCJ.js +1 -0
  194. package/dist/public/assets/messages-CF7zITDG.js +1 -0
  195. package/dist/public/assets/messages-CIBqdK6N.js +1 -0
  196. package/dist/public/assets/messages-CfXBJncQ.js +1 -0
  197. package/dist/public/assets/messages-DXdzgbRq.js +1 -0
  198. package/dist/public/assets/messages-G8fhkSEs.js +1 -0
  199. package/dist/public/assets/messages-z_LlF45n.js +1 -0
  200. package/dist/public/assets/{mindmap-definition-FAOFIHXS-CbNRnPS1.js → mindmap-definition-FAOFIHXS-CKQxgOGt.js} +1 -1
  201. package/dist/public/assets/minus-VHw16jS_.js +1 -0
  202. package/dist/public/assets/{miss-dialog-store-DtLnMdOO.js → miss-dialog-store-DVpIaq34.js} +1 -1
  203. package/dist/public/assets/{ok-B0nm7wTQ.js → ok-Z-u-nHAF.js} +1 -1
  204. package/dist/public/assets/{package-CisN94Rd.js → package-B5dxtZEP.js} +1 -1
  205. package/dist/public/assets/page-list-cache-DambRQ7B.js +1 -0
  206. package/dist/public/assets/{panel-right-open-BgAOqW9e.js → panel-right-open-B0h13QHr.js} +1 -1
  207. package/dist/public/assets/{paperclip-DTGtQ_JR.js → paperclip-ChAyZqn8.js} +1 -1
  208. package/dist/public/assets/{pegDiagram-VL7TDLO6-1D9kW7ay.js → pegDiagram-VL7TDLO6-BHV9FATd.js} +1 -1
  209. package/dist/public/assets/{pending-receive-nav-store-Dgzal0Jj.js → pending-receive-nav-store-DLOxz1b_.js} +1 -1
  210. package/dist/public/assets/{pieDiagram-7S7Q4E2Y-CAWP7eNl.js → pieDiagram-7S7Q4E2Y-vlst6sEu.js} +1 -1
  211. package/dist/public/assets/{platform-labels-CQrhw-5Z.js → platform-labels-DdSSzvdg.js} +1 -1
  212. package/dist/public/assets/{popover-BlSDN3zW.js → popover-B7jXm65e.js} +1 -1
  213. package/dist/public/assets/{progress-Bssl1FLe.js → progress-BtHJSSZk.js} +3 -3
  214. package/dist/public/assets/{project-paths-CBkV3-Ol.js → project-paths-BN2qP-Oz.js} +1 -1
  215. package/dist/public/assets/{prop-types-BGEVLmnR.js → prop-types-Boc_oFTG.js} +1 -1
  216. package/dist/public/assets/{propagation-api-BqnX4XED.js → propagation-api-DC5404fy.js} +1 -1
  217. package/dist/public/assets/{quadrantDiagram-CIZ2JOQS-Z4KSVoW4.js → quadrantDiagram-CIZ2JOQS-aZGa0dqP.js} +1 -1
  218. package/dist/public/assets/radio-group-npdxiS6E.js +1 -0
  219. package/dist/public/assets/{railroadDiagram-AXF67PYL-BP83q5bW.js → railroadDiagram-AXF67PYL-Daf6Zy7e.js} +1 -1
  220. package/dist/public/assets/{receive-store-SbtZ93F8.js → receive-store-Rla0xjPc.js} +1 -1
  221. package/dist/public/assets/{refresh-cw-BaBMjcrv.js → refresh-cw-DwRz6AkS.js} +1 -1
  222. package/dist/public/assets/{requirementDiagram-LRYGKXZP--AY3V6V9.js → requirementDiagram-LRYGKXZP-C8dZAU1p.js} +1 -1
  223. package/dist/public/assets/{sankeyDiagram-W5VNT64P-B-TG-dlh.js → sankeyDiagram-W5VNT64P-DSVSXy_1.js} +1 -1
  224. package/dist/public/assets/{select-Bs8KgWvR.js → select-XEGYznMI.js} +1 -1
  225. package/dist/public/assets/{selection-context-BbFFffLG.js → selection-context-C0Dh06ez.js} +1 -1
  226. package/dist/public/assets/{separator-B8dpHmeD.js → separator-C6x7j8mC.js} +1 -1
  227. package/dist/public/assets/{sequenceDiagram-SI44F4Z6-CXQngtIb.js → sequenceDiagram-SI44F4Z6-Bnbh_rO1.js} +1 -1
  228. package/dist/public/assets/{skill-scope-D3YD_IZ5.js → skill-scope-C2Q18Fyo.js} +1 -1
  229. package/dist/public/assets/{skills-api-BHMzgYxx.js → skills-api-Du0yE_Ea.js} +1 -1
  230. package/dist/public/assets/{spinner-OTMpJ3P-.js → spinner-t7GahFcQ.js} +1 -1
  231. package/dist/public/assets/{square-pen-CBDgB7xx.js → square-pen-K4JT0cp9.js} +1 -1
  232. package/dist/public/assets/{src-B7bXrIgD.js → src-XvoJ42p_.js} +1 -1
  233. package/dist/public/assets/startup-marks-Cw2UqI10.js +1 -0
  234. package/dist/public/assets/{stateDiagram-OKZ733FA-DjmKNgc-.js → stateDiagram-OKZ733FA-DS5XYAjU.js} +1 -1
  235. package/dist/public/assets/stateDiagram-v2-UEYNNEHI-BWm5URXG.js +1 -0
  236. package/dist/public/assets/{swimlanes-SLNWSIFB-W7I7Md-O.js → swimlanes-SLNWSIFB-BGX6QMGe.js} +1 -1
  237. package/dist/public/assets/swimlanesDiagram-ULZ7WXOC-CQ5DIVBE.js +8 -0
  238. package/dist/public/assets/{switch-BeP1gMN6.js → switch-iwBsEWej.js} +1 -1
  239. package/dist/public/assets/{tabs-r9BJxNSQ.js → tabs-BNfoCymd.js} +1 -1
  240. package/dist/public/assets/{tag-pill-input-CIT-G8TJ.js → tag-pill-input-BWs4IhME.js} +1 -1
  241. package/dist/public/assets/{target-navigation-intent-BePi2-hy.js → target-navigation-intent-C_Ucfr51.js} +1 -1
  242. package/dist/public/assets/{telemetry-impl-C53i8fXP.js → telemetry-impl-DLl1oxED.js} +1 -1
  243. package/dist/public/assets/{telemetry-startup-BuxfLmwJ.js → telemetry-startup-k7vK2L8Z.js} +1 -1
  244. package/dist/public/assets/{terminal-tB03Ykfq.js → terminal-D4HSnHXf.js} +1 -1
  245. package/dist/public/assets/terminal-cli-display-CrkxgiPR.js +1 -0
  246. package/dist/public/assets/{terminal-launch-events-D3fBT3uk.js → terminal-launch-events-BgzVfom1.js} +1 -1
  247. package/dist/public/assets/{terminal-telemetry-DogVmcEg.js → terminal-telemetry-CWD0Kbui.js} +1 -1
  248. package/dist/public/assets/{text-viewer-languages-CmBalDDz.js → text-viewer-languages-DRp_Y82n.js} +2 -2
  249. package/dist/public/assets/{thread-client-DG1ERL6y.js → thread-client-CyOBKqv0.js} +1 -1
  250. package/dist/public/assets/{timeline-definition-Z64GVDOM-Cl223Ubn.js → timeline-definition-Z64GVDOM-BKNoWHPk.js} +1 -1
  251. package/dist/public/assets/toggle-group-C2_37kV5.js +1 -0
  252. package/dist/public/assets/{tooltip-DPvMEqsq.js → tooltip-DttaCTqz.js} +1 -1
  253. package/dist/public/assets/{trash-2-BvCgdeps.js → trash-2-CePzTX_C.js} +1 -1
  254. package/dist/public/assets/{triangle-alert-BMtjvBBD.js → triangle-alert-D0n54WVY.js} +1 -1
  255. package/dist/public/assets/typing-burst-detector-CtCPp1ik.js +8 -0
  256. package/dist/public/assets/{undo-2-DI8uqzmR.js → undo-2-BOBiJGd5.js} +1 -1
  257. package/dist/public/assets/{uninstall-DreCX4_1.js → uninstall-Be_VK869.js} +1 -1
  258. package/dist/public/assets/{use-activity-panel-CR337nsy.js → use-activity-panel-Bat2VfJF.js} +1 -1
  259. package/dist/public/assets/{use-apply-config-color-theme-D4rPvW8P.js → use-apply-config-color-theme-3_75T4Q8.js} +1 -1
  260. package/dist/public/assets/{use-collab-url-D5rWSAYA.js → use-collab-url-9MxkxDjK.js} +1 -1
  261. package/dist/public/assets/{use-live-xterm-theme-DeqoKEyE.js → use-live-xterm-theme-BjybDd5E.js} +1 -1
  262. package/dist/public/assets/{use-open-skill-B6OWc3jt.js → use-open-skill-B004qnQw.js} +1 -1
  263. package/dist/public/assets/use-settings-route-6Aa41RPQ.js +1 -0
  264. package/dist/public/assets/{use-skill-origin-QOgMC_cx.js → use-skill-origin-C0RzVLGk.js} +1 -1
  265. package/dist/public/assets/{use-skills-CUyxM_-s.js → use-skills-BkWQHhha.js} +1 -1
  266. package/dist/public/assets/{use-terminal-enabled-BUJSR3VC.js → use-terminal-enabled-ST2-eUch.js} +1 -1
  267. package/dist/public/assets/use-timeline-entry-diff-C-o8h9N3.js +6 -0
  268. package/dist/public/assets/{use-workspace-DHq4JpK0.js → use-workspace-7B06onC_.js} +1 -1
  269. package/dist/public/assets/{vennDiagram-T6HMQDX7-B_vlI0S5.js → vennDiagram-T6HMQDX7-CRzUxobP.js} +1 -1
  270. package/dist/public/assets/{wardleyDiagram-T6FBY63Y-D3R5qk6E.js → wardleyDiagram-T6FBY63Y-CoEGckrX.js} +1 -1
  271. package/dist/public/assets/{wrench-DtgyRnkw.js → wrench-ZOpNzIoC.js} +1 -1
  272. package/dist/public/assets/x-C0WDbk6g.js +1 -0
  273. package/dist/public/assets/{xychartDiagram-ELKLHX3M-Btdla0qC.js → xychartDiagram-ELKLHX3M-BlVTFSNG.js} +1 -1
  274. package/dist/public/index.html +155 -155
  275. package/dist/public/uninstall.html +29 -29
  276. package/dist/{repair-launch-json-srmUn2hE.mjs → repair-launch-json-BVjKD52o.mjs} +2 -2
  277. package/dist/{repair-mcp-configs-I0KtICul.mjs → repair-mcp-configs-BQ7U1U_I.mjs} +2 -2
  278. package/dist/repair-skills-DIytACob.mjs +1 -0
  279. package/dist/{repair-skills-CRG-r1Xh.mjs → repair-skills-DPyYfXHX.mjs} +2 -2
  280. package/dist/{resolve-project-root-urAKqvDX.mjs → resolve-project-root-suxWrGvT.mjs} +2 -2
  281. package/dist/{server-lock-_JWkU2Mh.mjs → server-lock-CcnGITIh.mjs} +2 -2
  282. package/dist/server-lock-D8d0WVYU.mjs +1 -0
  283. package/dist/{skill-teardown-CVMrfSeZ.mjs → skill-teardown-D4qifTbZ.mjs} +2 -2
  284. package/dist/src-7XhmCEkb.mjs +1 -0
  285. package/dist/{src-BRlSw7bk.mjs → src-C8wtGJxJ.mjs} +1 -1
  286. package/dist/{src-CjFV1e1Z.mjs → src-CNSuUQTi.mjs} +4 -4
  287. package/dist/{src-DhKkOAcb.mjs → src-CaLoSvK5.mjs} +2 -2
  288. package/dist/src-CnywvEPN.mjs +20 -0
  289. package/dist/{start-1qNjbPX9.mjs → start-ClCOtrI0.mjs} +3 -3
  290. package/dist/start-CxNMq7dN.mjs +1 -0
  291. package/package.json +4 -4
  292. package/dist/constants-vY0RbDo-.mjs +0 -2
  293. package/dist/git-handle-DfQBBy3_.mjs +0 -1
  294. package/dist/init-CQuP4oZS.mjs +0 -1
  295. package/dist/loader-DPUVbNgg.mjs +0 -1
  296. package/dist/md-manager-CZcRasmz.mjs +0 -2
  297. package/dist/preview-Tkr1Psqx.mjs +0 -1
  298. package/dist/public/assets/CodeMirrorPropInput-BL-5Q3Jo.js +0 -3
  299. package/dist/public/assets/FeedbackForm-DFqW8szu.js +0 -1
  300. package/dist/public/assets/ManagedArtifactProperties-DqX6bBKJ.js +0 -1
  301. package/dist/public/assets/ReportBugDialogBody-DsOp1u-j.js +0 -3
  302. package/dist/public/assets/SettingsDialogBody-Dd2GkDtz.js +0 -12
  303. package/dist/public/assets/SkillInstallMenu-Bj4eanWC.js +0 -2
  304. package/dist/public/assets/SourceEditor-ChRbLJso.js +0 -1
  305. package/dist/public/assets/TerminalWindowApp-CWKtaPQf.js +0 -1
  306. package/dist/public/assets/arrow-up-right-BATFT-Sr.js +0 -1
  307. package/dist/public/assets/auth-state-cache-D7CM6sAp.js +0 -11
  308. package/dist/public/assets/channel-CPB7MoVI.js +0 -1
  309. package/dist/public/assets/check-_e5AYsE9.js +0 -1
  310. package/dist/public/assets/chevron-left-C3qnVWRd.js +0 -1
  311. package/dist/public/assets/chevron-right-BBMR0NbW.js +0 -1
  312. package/dist/public/assets/classDiagram-JCYQIIEL-Co922tiB.js +0 -1
  313. package/dist/public/assets/classDiagram-v2-OCEON4UE-CUyubUTn.js +0 -1
  314. package/dist/public/assets/client-version-Cr4yDTzO.js +0 -1
  315. package/dist/public/assets/comment-chips-BPjveL06.js +0 -5
  316. package/dist/public/assets/context-api-7lTvMdKG.js +0 -1
  317. package/dist/public/assets/dist-Be8lWZxP2.js +0 -1
  318. package/dist/public/assets/dist-pKYOq3XC2.js +0 -1
  319. package/dist/public/assets/dropdown-menu-JsEh078s.js +0 -1
  320. package/dist/public/assets/flowDiagram-UKHOOZJN-CFTGjA42.js +0 -1
  321. package/dist/public/assets/i18n-B28KWA_H.js +0 -1
  322. package/dist/public/assets/index-D7ftC-TA.js +0 -2204
  323. package/dist/public/assets/lint-config-client-DEbFKblI.js +0 -1
  324. package/dist/public/assets/mermaid-GHXKKRXX-f4wv8zwP.js +0 -1
  325. package/dist/public/assets/mermaid.core-wyUsrdV8.js +0 -1
  326. package/dist/public/assets/messages-BNqWoTE7.js +0 -1
  327. package/dist/public/assets/messages-BVQV1WJj.js +0 -1
  328. package/dist/public/assets/messages-Bu3H835T.js +0 -1
  329. package/dist/public/assets/messages-C2YnjINV.js +0 -1
  330. package/dist/public/assets/messages-CDgZBFJp.js +0 -1
  331. package/dist/public/assets/messages-D81fhPOK.js +0 -1
  332. package/dist/public/assets/messages-DRSi5QzW.js +0 -1
  333. package/dist/public/assets/messages-DmpME-BQ.js +0 -1
  334. package/dist/public/assets/messages-Drz1dYnk.js +0 -1
  335. package/dist/public/assets/messages-Ds1yna2Q.js +0 -1
  336. package/dist/public/assets/messages-N6kgiusx.js +0 -1
  337. package/dist/public/assets/messages-wwtrT-dP.js +0 -1
  338. package/dist/public/assets/minus-Dz9yQFxH.js +0 -1
  339. package/dist/public/assets/page-list-cache-QK9n5Q5R.js +0 -1
  340. package/dist/public/assets/radio-group-BsZGGl8l.js +0 -1
  341. package/dist/public/assets/startup-marks-BPO-vrjH.js +0 -1
  342. package/dist/public/assets/stateDiagram-v2-UEYNNEHI-DYowbT5J.js +0 -1
  343. package/dist/public/assets/swimlanesDiagram-ULZ7WXOC-Hyp8OggN.js +0 -8
  344. package/dist/public/assets/terminal-cli-display-Ch5uUFIR.js +0 -1
  345. package/dist/public/assets/toggle-group-BlEg4yJE.js +0 -1
  346. package/dist/public/assets/typing-burst-detector-BQPFhb8j.js +0 -8
  347. package/dist/public/assets/use-installed-clis-vg6izNL9.js +0 -1
  348. package/dist/public/assets/use-settings-route-9Zx6tEdn.js +0 -1
  349. package/dist/public/assets/use-timeline-entry-diff-BwGOAWfO.js +0 -6
  350. package/dist/public/assets/x-BAYve4SL.js +0 -1
  351. package/dist/repair-skills-BABpOhB_.mjs +0 -1
  352. package/dist/server-lock-C_5VGPQF.mjs +0 -1
  353. package/dist/src-BMK0mOrM.mjs +0 -20
  354. package/dist/src-ByMg6cEv.mjs +0 -1
  355. package/dist/start-BBP7vc3m.mjs +0 -1
  356. /package/dist/public/assets/{asset-dispatch-D3iE-ozy.js → asset-dispatch-CD6rGcnF.js} +0 -0
  357. /package/dist/public/assets/{auth-prompt-store-BXeyTyYx.js → auth-prompt-store-vAFATIFt.js} +0 -0
  358. /package/dist/public/assets/{createLucideIcon-CfxA0Qtb.js → createLucideIcon-BulbvLvN.js} +0 -0
  359. /package/dist/public/assets/{desktop-bridge-types-rBjHIYSI.js → desktop-bridge-types-oYPdTDmz.js} +0 -0
  360. /package/dist/public/assets/{dist-mv8e6dBX.js → dist-BHv-mziD.js} +0 -0
  361. /package/dist/public/assets/{dist-Cm417ZCm.js → dist-Bd_yyADX.js} +0 -0
  362. /package/dist/public/assets/{dist-DTX2HxC82.js → dist-CJhtNlOm2.js} +0 -0
  363. /package/dist/public/assets/{dist-BgXDUIPy.js → dist-Cr4-nBVI.js} +0 -0
  364. /package/dist/public/assets/{documents-fetch-B1PtbYbS.js → documents-fetch-Bw4lKnRN.js} +0 -0
  365. /package/dist/public/assets/{external-link-D2rJDkPo.js → external-link-DGqXfQJy.js} +0 -0
  366. /package/dist/public/assets/{file-tree-rename-validation-D2G4Kbju.js → file-tree-rename-validation-DmGgIR2S.js} +0 -0
  367. /package/dist/public/assets/{floating-ui.dom-Dk5WJYh0.js → floating-ui.dom-BcZPrP06.js} +0 -0
  368. /package/dist/public/assets/{globals-Cu_E7Ptz.js → globals-CTSydwqe.js} +0 -0
  369. /package/dist/public/assets/{html-void-elements-Biw85x38.js → html-void-elements-zEl0KGqf.js} +0 -0
  370. /package/dist/public/assets/{input-BZhIrrdB.js → input-Cy2M_Avq.js} +0 -0
  371. /package/dist/public/assets/{katex-DJlTj0sX.js → katex-CcPk1vJT.js} +0 -0
  372. /package/dist/public/assets/{markdownit-BZnioq-C.js → markdownit-CugClK-K.js} +0 -0
  373. /package/dist/public/assets/{note-window-mode-BXAdiDXS.js → note-window-mode-CsmLTxU_.js} +0 -0
  374. /package/dist/public/assets/{parse-api-error-Cmyw9Afr.js → parse-api-error-Dd8VI2eu.js} +0 -0
  375. /package/dist/public/assets/{stex-PMopVeEZ.js → stex-s_JxeNEZ.js} +0 -0
  376. /package/dist/public/assets/{tool-list-format-CGMeWIgE.js → tool-list-format-HdFmW82S.js} +0 -0
  377. /package/dist/public/assets/{trace-api-CEY5PfXs.js → trace-api-BP9dN1Hz.js} +0 -0
  378. /package/dist/public/assets/{use-apply-config-theme-PILfflfB.js → use-apply-config-theme-CBmHKD_B.js} +0 -0
  379. /package/dist/public/assets/{w3c-keyname-DlL_314g.js → w3c-keyname-C7Rznu6R.js} +0 -0
  380. /package/dist/public/assets/{workspace-paths-F2vuFWEQ.js → workspace-paths-CAsMig07.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,A as i,At as a,B as o,Bt as s,Ct as c,D as l,Dt as u,Et as d,Gt as f,H as p,Ht as m,I as h,It as g,J as _,Jt as v,K as y,Kt as b,Lt as x,Mt as S,Nt as C,O as w,Pt as T,Qt as E,R as D,Rt as O,St as ee,Tt as te,U as k,Ut as A,V as ne,Vt as re,W as ie,Wt as j,Yt as ae,_ as oe,_t as M,an as se,b as ce,cn as le,d as ue,dt as de,en as fe,f as pe,ft as me,gt as he,ht as ge,in as _e,it as ve,j as ye,jt as be,k as xe,kt as N,ln as Se,n as Ce,nn as we,on as Te,p as Ee,pt as De,qt as Oe,rn as ke,sn as Ae,st as je,t as Me,tn as Ne,u as Pe,ut as Fe,vt as Ie,xt as Le,y as Re,yt as ze,z as Be,zt as P}from"./sleep-DyLEGHvt.mjs";import{$ as Ve,$a as He,$i as Ue,$n as We,$r as Ge,$t as Ke,A as qe,Aa as Je,Ai as Ye,An as Xe,Ao as Ze,Ar as Qe,As as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Cc as dt,Ci as ft,Cn as pt,Co as mt,Cr as ht,Cs as gt,Ct as _t,D as vt,Da as yt,Di as bt,Dn as xt,Do as St,Dr as Ct,Ds as wt,Dt as Tt,E as Et,Ea as Dt,Ei as Ot,En as kt,Eo as At,Er as jt,Es as Mt,Et as Nt,F as Pt,Fa as Ft,Fi as It,Fn as Lt,Fo as Rt,Fr as zt,Fs as Bt,Ft as Vt,G as Ht,Ga as Ut,Gi as Wt,Gn as Gt,Go as Kt,Gr as qt,Gs as Jt,Gt as Yt,H as Xt,Ha as Zt,Hi as Qt,Hn as $t,Ho as en,Hr as tn,I as nn,Ia as rn,Ii as an,In as on,Io as sn,Ir as cn,Is as ln,It as un,Ja as dn,Ji as fn,Jn as eee,Jo as pn,Jr as mn,Js as hn,Jt as gn,K as _n,Ka as tee,Ki as vn,Kn as nee,Ko as ree,Kr as yn,Kt as bn,L as xn,La as Sn,Lc as Cn,Li as wn,Ln as iee,Lo as Tn,Lr as En,Ls as Dn,Lt as On,M as kn,Ma as An,Mc as jn,Mi as Mn,Mn as Nn,Mo as Pn,Mr as Fn,Ms as In,Mt as Ln,N as Rn,Na as zn,Nc as Bn,Ni as Vn,Nn as Hn,No as Un,Nr as Wn,Ns as Gn,Nt as Kn,O as qn,Oa as Jn,Oi as aee,On as oee,Or as see,Os as Yn,Ot as Xn,P as Zn,Pa as Qn,Pc as $n,Pi as er,Pn as tr,Po as nr,Pr as rr,Pt as ir,Qa as ar,Qi as or,Qn as sr,Qo as cr,Qr as cee,Qs as lr,Qt as ur,R as dr,Ra as fr,Ri as pr,Rn as lee,Ro as uee,Rr as dee,Rt as fee,S as mr,Sa as hr,Sc as gr,Si as pee,Sn as mee,So as _r,Sr as hee,Ss as vr,St as yr,T as br,Ta as xr,Ti as Sr,Tn as Cr,To as wr,Tr,Ts as Er,Tt as Dr,U as Or,Ua as kr,Ui as Ar,Un as jr,Uo as Mr,Ur as Nr,Us as Pr,Ut as Fr,V as Ir,Va as Lr,Vi as gee,Vn as Rr,Vo as zr,Vr as _ee,Vs as Br,W as Vr,Wa as vee,Wi as Hr,Wn as Ur,Wo as Wr,Wr as Gr,Ws as Kr,Wt as qr,X as yee,Xa as Jr,Xi as Yr,Xn as Xr,Xo as Zr,Xr as Qr,Xs as $r,Xt as ei,Y as ti,Ya as ni,Yi as ri,Yn as ii,Yo as ai,Yr as oi,Ys as si,Yt as ci,Z as li,Za as ui,Zi as di,Zn as bee,Zo as fi,Zr as xee,Zs as pi,Zt as mi,_ as hi,_a as gi,_c as _i,_i as vi,_n as See,_o as yi,_r as Cee,_s as bi,_t as xi,a as Si,aa as Ci,ac as wi,ai as Ti,an as Ei,ao as Di,ar as wee,as as Oi,at as ki,b as Ai,ba as ji,bc as Mi,bi as Ni,bn as Pi,bo as Fi,br as Tee,bs as Ii,bt as Li,c as Ri,ca as Eee,cc as zi,ci as Dee,cn as Oee,co as Bi,cr as kee,cs as Vi,ct as Hi,d as Ui,da as Wi,dc as Gi,di as Aee,dn as jee,do as Ki,dr as qi,ds as Ji,dt as Yi,ea as Xi,ec as Zi,ei as Mee,en as Nee,eo as Pee,er as Qi,es as Fee,et as $i,f as ea,fa as ta,fc as na,fi as ra,fn as ia,fo as aa,fr as oa,ft as sa,g as ca,ga as la,gc as ua,gi as da,gn as fa,go as pa,gr as Iee,gs as ma,gt as ha,h as ga,ha as _a,hc as va,hi as Lee,hn as Ree,ho as ya,hr as zee,ht as ba,i as xa,ia as Sa,ic as Ca,ii as wa,in as Ta,io as Ea,ir as Bee,it as Da,j as Oa,ja as ka,jc as Aa,ji as ja,jn as Vee,jo as Ma,jr as Na,jt as Pa,k as Fa,ka as Ia,ki as La,kn as Ra,ko as za,kr as Ba,ks as Va,kt as Ha,l as Ua,la as Wa,lc as Ga,li as Ka,ln as qa,lo as Ja,lr as Ya,ls as Xa,lt as Za,m as Qa,ma as $a,mc as eo,mi as to,mn as no,mo as ro,mr as io,ms as ao,mt as oo,n as so,na as co,nc as lo,ni as uo,nn as Hee,no as fo,nr as Uee,ns as po,nt as mo,o as ho,oa as go,oc as _o,oi as vo,on as yo,oo as bo,or as Wee,ot as xo,p as So,pa as Co,pc as wo,pi as To,pn as Gee,po as Eo,pr as Kee,ps as Do,pt as Oo,q as ko,qa as qee,qi as Ao,qn as Jee,qo as Yee,qr as Xee,qs as Zee,qt as jo,r as Mo,ra as No,rc as Po,ri as Fo,rn as Io,ro as Lo,rr as Qee,rs as Ro,rt as zo,s as Bo,sa as $ee,si as Vo,sn as Ho,so as Uo,sr as ete,st as Wo,t as Go,ta as Ko,tc as qo,ti as Jo,tn as tte,to as Yo,tr as nte,ts as Xo,tt as Zo,u as Qo,ua as $o,uc as rte,ui as ite,un as ate,uo as es,ur as ts,us as ns,ut as rs,v as is,va as as,vc as os,vi as ss,vn as ote,vr as ste,vt as cs,w as ls,wa as us,wc as ds,wi as cte,wn as fs,wo as ps,wr as lte,wt as ms,x as hs,xa as gs,xi as _s,xn as ute,xo as vs,xr as ys,xs as bs,xt as xs,y as Ss,ya as Cs,yc as dte,yi as fte,yn as ws,yo as Ts,yr as pte,ys as Es,yt as Ds,z as Os,za as ks,zi as As,zn as mte,zo as hte,zr as js,zs as Ms,zt as Ns}from"./src-DhKkOAcb.mjs";import{c as Ps,i as Fs,l as Is,n as Ls,s as Rs}from"./esm-DxvI2ZVA.mjs";import{n as zs,t as Bs}from"./md-manager-CZcRasmz.mjs";import{A as Vs,C as Hs,E as Us,F as Ws,L as Gs,M as Ks,N as qs,S as Js,T as Ys,_ as Xs,a as Zs,b as Qs,c as $s,d as ec,f as tc,g as nc,h as rc,i as ic,j as ac,k as oc,l as sc,m as cc,n as lc,o as uc,p as dc,r as fc,s as pc,t as mc,u as hc,v as gc,w as _c,x as vc,y as yc}from"./fs-traced-C5oeVBiQ.mjs";import{E as gte,T as _te,a as bc,b as xc,l as vte,p as yte,r as F,s as Sc,v as bte,w as xte,x as Cc,y as wc}from"./logger-Dq-cRhcP.mjs";import{a as Tc,c as Ste,i as Ec,l as Cte,o as wte,r as Dc,s as Oc,t as kc}from"./git-handle-29BNYqgw.mjs";import{C as Tte,S as Ac,a as jc,b as Mc,d as Nc,i as Ete,n as Pc,o as Fc,r as Ic,v as Lc,y as Rc}from"./server-lock-_JWkU2Mh.mjs";import{t as zc}from"./libesm-DzwC_yFw.mjs";import{t as Bc}from"./yazl-DejPO9b3.mjs";import{t as Vc}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as Hc,c as Uc,d as Wc,f as Gc,h as Kc,i as qc,l as Jc,m as Yc,n as Xc,o as Zc,p as Qc,r as $c,s as el,t as tl,u as nl}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as rl,B as il,C as al,D as ol,E as sl,F as cl,H as ll,I as ul,L as dl,M as fl,N as pl,O as ml,P as hl,S as gl,T as _l,V as vl,_ as yl,a as bl,b as xl,c as Sl,d as Cl,f as wl,g as Tl,h as El,i as Dl,j as Ol,k as kl,l as Al,m as Dte,n as Ote,o as jl,p as Ml,r as Nl,s as Pl,t as kte,u as Fl,v as Il,w as Ll,x as Rl,y as zl,z as Bl}from"./chunk-BGSUD5R5-Cj4a16wX.mjs";import{a as Vl,c as Hl,d as Ul,i as Wl,l as Gl,n as Ate,o as jte,r as Mte,s as Kl,t as Nte,u as ql}from"./chunk-KX3P26DQ-KA7oOKfS.mjs";import{n as Jl,r as Yl,t as Xl}from"./chunk-R6VWJ2ZL-B9eBwYXQ.mjs";import{r as Zl}from"./chunk-CWQS3NFK-BmYxhDXa.mjs";import{t as Ql}from"./chunk-DXB73IDG-Dx7prHrO.mjs";import{n as $l,t as eu}from"./chunk-5QMZ5MUS-BliBLsUm.mjs";import{n as Pte,t as Fte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as tu,r as nu,t as ru}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Ite,t as iu}from"./chunk-24IMIIXA-C3WrrB2N.mjs";import{n as au}from"./chunk-3THT3N7L-Be-SmWEj.mjs";import{t as ou}from"./chunk-44UOCSGV-CZohvp0c.mjs";import{t as Lte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as su}from"node:module";import{execFile as cu,execFileSync as Rte,spawn as lu,spawnSync as uu}from"node:child_process";import*as du from"node:path";import{basename as fu,delimiter as pu,dirname as I,extname as mu,isAbsolute as hu,join as L,normalize as gu,parse as _u,posix as vu,relative as R,resolve as z,sep as B,win32 as zte}from"node:path";import{URLSearchParams as Bte,fileURLToPath as yu,pathToFileURL as bu}from"node:url";import*as xu from"node:fs";import{appendFileSync as Vte,chmodSync as Su,closeSync as Cu,constants as wu,createReadStream as Tu,createWriteStream as Eu,existsSync as V,fstatSync as Hte,lstatSync as Du,mkdirSync as Ou,mkdtempSync as ku,openSync as Au,opendirSync as ju,readFile as Ute,readFileSync as H,readSync as Mu,readdirSync as Nu,readlinkSync as Pu,realpathSync as U,renameSync as Fu,rmSync as Iu,rmdirSync as Lu,statSync as Ru,unlinkSync as zu,writeFileSync as Bu,writeSync as Wte}from"node:fs";import{arch as Vu,availableParallelism as Gte,homedir as Hu,hostname as Uu,platform as Wu,tmpdir as Gu}from"node:os";import{access as Ku,chmod as Kte,constants as qu,lstat as Ju,readFile as Yu,readdir as Xu,realpath as Zu,stat as Qu,writeFile as qte}from"node:fs/promises";import{Readable as $u,Transform as Jte,Writable as Yte}from"node:stream";import ed,{createHash as td,randomUUID as nd,webcrypto as rd}from"node:crypto";import Xte from"crypto";import{Readable as id}from"stream";import{EventEmitter as Zte}from"node:events";import{readdirSync as Qte,statSync as $te}from"fs";import{join as ad,resolve as ene}from"path";import{Worker as tne}from"node:worker_threads";import{monitorEventLoopDelay as nne,performance as od}from"node:perf_hooks";import{createInterface as rne}from"node:readline";import{pipeline as sd}from"node:stream/promises";import{setImmediate as ine,setTimeout as cd}from"node:timers/promises";import{promisify as ld}from"node:util";import{request as ane}from"node:http";import{Http2ServerRequest as ud,constants as one}from"node:http2";import{lookup as sne}from"node:dns/promises";import{request as cne}from"node:https";import{createBrotliDecompress as lne,createGunzip as une,createInflate as dne}from"node:zlib";import*as fne from"node:querystring";import{Http2ServerRequest as dd,constants as pne}from"http2";import{AsyncLocalStorage as mne}from"node:async_hooks";import{lookup as hne}from"node:dns";import gne from"node:tls";var fd=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(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=hu(t)?t:z(this.gitDir,t))}catch(e){if(!gd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return gd(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]}:vd(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(L(t.path,`config`),`utf-8`)}catch(e){return gd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=_ne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!_d(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=z(t.path,e),r=R(t.path,n);if(r.startsWith(`..`)||hu(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=bne(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!gd(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(L(t.path,`packed-refs`),`utf-8`)}catch(e){return gd(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 vd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function pd(e){return hd(z(e),``)}function md(e){let t=z(e),n=z(Hu());if(t===n)return{kind:`absent`};let r=hd(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=I(i);if(e===i||e===n)return{kind:`absent`};let r=hd(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function hd(e,t){let n=L(e,`.git`),r;try{r=Ru(n)}catch(e){return gd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new fd(`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=hu(o)?o:z(e,o);try{if(!Ru(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 fd(`linked`,e,t,n,s)}}function _ne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=vne(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=yne(i[1]);if(a.length>0)return a}return null}function vne(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function yne(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function gd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function _d(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function bne(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?_d(t[1])?{kind:`symbolic`,target:t[1]}:null:vd(e)?{kind:`oid`,oid:e}:null}function vd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const yd=`ok-generator`;function xne(e){return`git-author-${un(e.trim().toLowerCase())}`}const Sne=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function bd(e){let t=md(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 xd(e){let t=bd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Sd(e){let t=bd(e);switch(t.kind){case`directory`:return z(t.path,Cd(t.projectSubPath));case`linked`:if(!V(t.path))throw new wd(t.gitPath,t.path);return z(t.path,Cd(t.projectSubPath));case`malformed-pointer`:throw new wd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Td(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Cd(e){return e===``?`ok`:`ok-${Cne(e)}`}function Cne(e){let t=e.split(B).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=wne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function wne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var wd=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}},Td=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 Tne(e){let t;try{t=Sd(e)}catch(e){if(e instanceof wd||e instanceof Td)return null;throw e}return V(z(t,`HEAD`))?t:null}function Ed(e){return`refs/wip/${e}/`}function Ene(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{$t as r,A as i,At as a,B as o,Bt as s,Ct as c,D as l,Dt as u,Et as d,Gt as f,H as p,Ht as m,I as h,It as g,J as _,Jt as v,K as y,Kt as b,Lt as x,Mt as S,Nt as C,O as w,Pt as T,Qt as E,R as D,Rt as O,St as ee,Tt as te,U as k,Ut as A,V as ne,Vt as re,W as ie,Wt as j,Yt as ae,_ as oe,_t as M,an as se,b as ce,cn as le,d as ue,dt as de,en as fe,f as pe,ft as me,gt as he,ht as ge,in as _e,it as ve,j as ye,jt as be,k as xe,kt as N,ln as Se,n as Ce,nn as we,on as Te,p as Ee,pt as De,qt as Oe,rn as ke,sn as Ae,st as je,t as Me,tn as Ne,u as Pe,ut as Fe,vt as Ie,xt as Le,y as Re,yt as ze,z as Be,zt as P}from"./sleep-DyLEGHvt.mjs";import{$ as Ve,$a as He,$i as Ue,$n as We,$r as Ge,$t as Ke,A as qe,Aa as Je,Ai as Ye,An as Xe,Ao as Ze,Ar as Qe,As as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Cc as dt,Ci as ft,Cn as pt,Co as mt,Cr as ht,Cs as gt,Ct as _t,D as vt,Da as yt,Di as bt,Dn as xt,Do as St,Dr as Ct,Ds as wt,Dt as Tt,E as Et,Ea as Dt,Ei as Ot,En as kt,Eo as At,Er as jt,Es as Mt,Et as Nt,F as Pt,Fa as Ft,Fi as It,Fn as Lt,Fo as Rt,Fr as zt,Fs as Bt,Ft as Vt,G as Ht,Ga as Ut,Gi as Wt,Gn as Gt,Go as Kt,Gr as qt,Gs as Jt,Gt as Yt,H as Xt,Ha as Zt,Hi as Qt,Hn as $t,Ho as en,Hr as tn,I as nn,Ia as rn,Ii as an,In as on,Io as sn,Ir as cn,Is as ln,It as un,Ja as dn,Ji as fn,Jn as eee,Jo as pn,Jr as mn,Js as hn,Jt as gn,K as _n,Ka as tee,Ki as vn,Kn as nee,Ko as ree,Kr as yn,Kt as bn,L as xn,La as Sn,Lc as Cn,Li as wn,Ln as iee,Lo as Tn,Lr as En,Ls as Dn,Lt as On,M as kn,Ma as An,Mc as jn,Mi as Mn,Mn as Nn,Mo as Pn,Mr as Fn,Ms as In,Mt as Ln,N as Rn,Na as zn,Nc as Bn,Ni as Vn,Nn as Hn,No as Un,Nr as Wn,Ns as Gn,Nt as Kn,O as qn,Oa as Jn,Oi as aee,On as oee,Or as see,Os as Yn,Ot as Xn,P as Zn,Pa as Qn,Pc as $n,Pi as er,Pn as tr,Po as nr,Pr as rr,Pt as ir,Qa as ar,Qi as or,Qn as sr,Qo as cr,Qr as cee,Qs as lr,Qt as ur,R as dr,Ra as fr,Ri as pr,Rn as lee,Ro as uee,Rr as dee,Rt as fee,S as mr,Sa as hr,Sc as gr,Si as pee,Sn as mee,So as _r,Sr as hee,Ss as vr,St as yr,T as br,Ta as xr,Ti as Sr,Tn as Cr,To as wr,Tr,Ts as Er,Tt as Dr,U as Or,Ua as kr,Ui as Ar,Un as jr,Uo as Mr,Ur as Nr,Us as Pr,Ut as Fr,V as Ir,Va as Lr,Vi as gee,Vn as Rr,Vo as zr,Vr as _ee,Vs as Br,W as Vr,Wa as vee,Wi as Hr,Wn as Ur,Wo as Wr,Wr as Gr,Ws as Kr,Wt as qr,X as yee,Xa as Jr,Xi as Yr,Xn as Xr,Xo as Zr,Xr as Qr,Xs as $r,Xt as ei,Y as ti,Ya as ni,Yi as ri,Yn as ii,Yo as ai,Yr as oi,Ys as si,Yt as ci,Z as li,Za as ui,Zi as di,Zn as bee,Zo as fi,Zr as xee,Zs as pi,Zt as mi,_ as hi,_a as gi,_c as _i,_i as vi,_n as See,_o as yi,_r as Cee,_s as bi,_t as xi,a as Si,aa as Ci,ac as wi,ai as Ti,an as Ei,ao as Di,ar as wee,as as Oi,at as ki,b as Ai,ba as ji,bc as Mi,bi as Ni,bn as Pi,bo as Fi,br as Tee,bs as Ii,bt as Li,c as Ri,ca as Eee,cc as zi,ci as Dee,cn as Oee,co as Bi,cr as kee,cs as Vi,ct as Hi,d as Ui,da as Wi,dc as Gi,di as Aee,dn as jee,do as Ki,dr as qi,ds as Ji,dt as Yi,ea as Xi,ec as Zi,ei as Mee,en as Nee,eo as Pee,er as Qi,es as Fee,et as $i,f as ea,fa as ta,fc as na,fi as ra,fn as ia,fo as aa,fr as oa,ft as sa,g as ca,ga as la,gc as ua,gi as da,gn as fa,go as pa,gr as Iee,gs as ma,gt as ha,h as ga,ha as _a,hc as va,hi as Lee,hn as Ree,ho as ya,hr as zee,ht as ba,i as xa,ia as Sa,ic as Ca,ii as wa,in as Ta,io as Ea,ir as Bee,it as Da,j as Oa,ja as ka,jc as Aa,ji as ja,jn as Vee,jo as Ma,jr as Na,jt as Pa,k as Fa,ka as Ia,ki as La,kn as Ra,ko as za,kr as Ba,ks as Va,kt as Ha,l as Ua,la as Wa,lc as Ga,li as Ka,ln as qa,lo as Ja,lr as Ya,ls as Xa,lt as Za,m as Qa,ma as $a,mc as eo,mi as to,mn as no,mo as ro,mr as io,ms as ao,mt as oo,n as so,na as co,nc as lo,ni as uo,nn as Hee,no as fo,nr as Uee,ns as po,nt as mo,o as ho,oa as go,oc as _o,oi as vo,on as yo,oo as bo,or as Wee,ot as xo,p as So,pa as Co,pc as wo,pi as To,pn as Gee,po as Eo,pr as Kee,ps as Do,pt as Oo,q as ko,qa as qee,qi as Ao,qn as Jee,qo as Yee,qr as Xee,qs as Zee,qt as jo,r as Mo,ra as No,rc as Po,ri as Fo,rn as Io,ro as Lo,rr as Qee,rs as Ro,rt as zo,s as Bo,sa as $ee,si as Vo,sn as Ho,so as Uo,sr as ete,st as Wo,t as Go,ta as Ko,tc as qo,ti as Jo,tn as tte,to as Yo,tr as nte,ts as Xo,tt as Zo,u as Qo,ua as $o,uc as rte,ui as ite,un as ate,uo as es,ur as ts,us as ns,ut as rs,v as is,va as as,vc as os,vi as ss,vn as ote,vr as ste,vt as cs,w as ls,wa as us,wc as ds,wi as cte,wn as fs,wo as ps,wr as lte,wt as ms,x as hs,xa as gs,xi as _s,xn as ute,xo as vs,xr as ys,xs as bs,xt as xs,y as Ss,ya as Cs,yc as dte,yi as fte,yn as ws,yo as Ts,yr as pte,ys as Es,yt as Ds,z as Os,za as ks,zi as As,zn as mte,zo as hte,zr as js,zs as Ms,zt as Ns}from"./src-CaLoSvK5.mjs";import{c as Ps,i as Fs,l as Is,n as Ls,s as Rs}from"./esm-DxvI2ZVA.mjs";import{n as zs,t as Bs}from"./md-manager-BJ88tow5.mjs";import{A as Vs,C as Hs,E as Us,F as Ws,L as Gs,M as Ks,N as qs,S as Js,T as Ys,_ as Xs,a as Zs,b as Qs,c as $s,d as ec,f as tc,g as nc,h as rc,i as ic,j as ac,k as oc,l as sc,m as cc,n as lc,o as uc,p as dc,r as fc,s as pc,t as mc,u as hc,v as gc,w as _c,x as vc,y as yc}from"./fs-traced-C5oeVBiQ.mjs";import{E as gte,T as _te,a as bc,b as xc,l as vte,p as yte,r as F,s as Sc,v as bte,w as xte,x as Cc,y as wc}from"./logger-Dq-cRhcP.mjs";import{a as Tc,c as Ste,i as Ec,l as Cte,o as wte,r as Dc,s as Oc,t as kc}from"./git-handle-UnQwrdlT.mjs";import{C as Tte,S as Ac,a as jc,b as Mc,d as Nc,i as Ete,n as Pc,o as Fc,r as Ic,v as Lc,y as Rc}from"./server-lock-CcnGITIh.mjs";import{t as zc}from"./libesm-DzwC_yFw.mjs";import{t as Bc}from"./yazl-DejPO9b3.mjs";import{t as Vc}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as Hc,c as Uc,d as Wc,f as Gc,h as Kc,i as qc,l as Jc,m as Yc,n as Xc,o as Zc,p as Qc,r as $c,s as el,t as tl,u as nl}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as rl,B as il,C as al,D as ol,E as sl,F as cl,H as ll,I as ul,L as dl,M as fl,N as pl,O as ml,P as hl,S as gl,T as _l,V as vl,_ as yl,a as bl,b as xl,c as Sl,d as Cl,f as wl,g as Tl,h as El,i as Dl,j as Ol,k as kl,l as Al,m as Dte,n as Ote,o as jl,p as Ml,r as Nl,s as Pl,t as kte,u as Fl,v as Il,w as Ll,x as Rl,y as zl,z as Bl}from"./chunk-BGSUD5R5-Cj4a16wX.mjs";import{a as Vl,c as Hl,d as Ul,i as Wl,l as Gl,n as Ate,o as jte,r as Mte,s as Kl,t as Nte,u as ql}from"./chunk-KX3P26DQ-KA7oOKfS.mjs";import{n as Jl,r as Yl,t as Xl}from"./chunk-R6VWJ2ZL-B9eBwYXQ.mjs";import{r as Zl}from"./chunk-CWQS3NFK-BmYxhDXa.mjs";import{t as Ql}from"./chunk-DXB73IDG-Dx7prHrO.mjs";import{n as $l,t as eu}from"./chunk-5QMZ5MUS-BliBLsUm.mjs";import{n as Pte,t as Fte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as tu,r as nu,t as ru}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Ite,t as iu}from"./chunk-24IMIIXA-C3WrrB2N.mjs";import{n as au}from"./chunk-3THT3N7L-Be-SmWEj.mjs";import{t as ou}from"./chunk-44UOCSGV-CZohvp0c.mjs";import{t as Lte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as su}from"node:module";import{execFile as cu,execFileSync as Rte,spawn as lu,spawnSync as uu}from"node:child_process";import*as du from"node:path";import{basename as fu,delimiter as pu,dirname as I,extname as mu,isAbsolute as hu,join as L,normalize as gu,parse as _u,posix as vu,relative as R,resolve as z,sep as B,win32 as zte}from"node:path";import{URLSearchParams as Bte,fileURLToPath as yu,pathToFileURL as bu}from"node:url";import*as xu from"node:fs";import{appendFileSync as Vte,chmodSync as Su,closeSync as Cu,constants as wu,createReadStream as Tu,createWriteStream as Eu,existsSync as V,fstatSync as Hte,lstatSync as Du,mkdirSync as Ou,mkdtempSync as ku,openSync as Au,opendirSync as ju,readFile as Ute,readFileSync as H,readSync as Mu,readdirSync as Nu,readlinkSync as Pu,realpathSync as U,renameSync as Fu,rmSync as Iu,rmdirSync as Lu,statSync as Ru,unlinkSync as zu,writeFileSync as Bu,writeSync as Wte}from"node:fs";import{arch as Vu,availableParallelism as Gte,homedir as Hu,hostname as Uu,platform as Wu,tmpdir as Gu}from"node:os";import{access as Ku,chmod as Kte,constants as qu,lstat as Ju,readFile as Yu,readdir as Xu,realpath as Zu,stat as Qu,writeFile as qte}from"node:fs/promises";import{Readable as $u,Transform as Jte,Writable as Yte}from"node:stream";import ed,{createHash as td,randomUUID as nd,webcrypto as rd}from"node:crypto";import Xte from"crypto";import{Readable as id}from"stream";import{EventEmitter as Zte}from"node:events";import{readdirSync as Qte,statSync as $te}from"fs";import{join as ad,resolve as ene}from"path";import{Worker as tne}from"node:worker_threads";import{monitorEventLoopDelay as nne,performance as od}from"node:perf_hooks";import{createInterface as rne}from"node:readline";import{pipeline as sd}from"node:stream/promises";import{setImmediate as ine,setTimeout as cd}from"node:timers/promises";import{promisify as ld}from"node:util";import{request as ane}from"node:http";import{Http2ServerRequest as ud,constants as one}from"node:http2";import{lookup as sne}from"node:dns/promises";import{request as cne}from"node:https";import{createBrotliDecompress as lne,createGunzip as une,createInflate as dne}from"node:zlib";import*as fne from"node:querystring";import{Http2ServerRequest as dd,constants as pne}from"http2";import{AsyncLocalStorage as mne}from"node:async_hooks";import{lookup as hne}from"node:dns";import gne from"node:tls";var fd=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(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=hu(t)?t:z(this.gitDir,t))}catch(e){if(!gd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=H(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return gd(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]}:vd(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(L(t.path,`config`),`utf-8`)}catch(e){return gd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=_ne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!_d(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=z(t.path,e),r=R(t.path,n);if(r.startsWith(`..`)||hu(r))return{kind:`invalid`};try{let e=H(n,`utf-8`).trim(),t=bne(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!gd(e))return{kind:`unreadable`,cause:e}}let i;try{i=H(L(t.path,`packed-refs`),`utf-8`)}catch(e){return gd(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 vd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function pd(e){return hd(z(e),``)}function md(e){let t=z(e),n=z(Hu());if(t===n)return{kind:`absent`};let r=hd(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=I(i);if(e===i||e===n)return{kind:`absent`};let r=hd(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function hd(e,t){let n=L(e,`.git`),r;try{r=Ru(n)}catch(e){return gd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new fd(`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=hu(o)?o:z(e,o);try{if(!Ru(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 fd(`linked`,e,t,n,s)}}function _ne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=vne(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=yne(i[1]);if(a.length>0)return a}return null}function vne(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function yne(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function gd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function _d(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function bne(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?_d(t[1])?{kind:`symbolic`,target:t[1]}:null:vd(e)?{kind:`oid`,oid:e}:null}function vd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const yd=`ok-generator`;function xne(e){return`git-author-${un(e.trim().toLowerCase())}`}const Sne=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function bd(e){let t=md(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 xd(e){let t=bd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function Sd(e){let t=bd(e);switch(t.kind){case`directory`:return z(t.path,Cd(t.projectSubPath));case`linked`:if(!V(t.path))throw new wd(t.gitPath,t.path);return z(t.path,Cd(t.projectSubPath));case`malformed-pointer`:throw new wd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Td(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Cd(e){return e===``?`ok`:`ok-${Cne(e)}`}function Cne(e){let t=e.split(B).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=wne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function wne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var wd=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}},Td=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 Tne(e){let t;try{t=Sd(e)}catch(e){if(e instanceof wd||e instanceof Td)return null;throw e}return V(z(t,`HEAD`))?t:null}function Ed(e){return`refs/wip/${e}/`}function Ene(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 Dd=`ok-actor: `;function Od(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),`${Dd}${JSON.stringify(i)}`}function kd(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=Dne(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 Dne(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 One(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(Dd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:kd(n)}return null}function Ad(e){if(!e)return[];let t=[];for(let n of e.split(`
4
4
  `)){let e=n.trim();if(!e.startsWith(Dd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=kd(r);i&&t.push(i)}return t}function kne(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 jd(e){let t=Ad(e);return t.length>0?t.map(kne):Ene(e)}function Md(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Nd(e){return`reconcile: ${e}`}function Pd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Ane(e,t){return`park: ${e} -> ${t}`}function Fd(e,t){return`rename: ${e} -> ${t}`}function Id(e){return`checkpoint: ${e}`}function jne(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Mne=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Ld(e){return e.replace(Mne,` `)}function Nne(e,t){let n=Ld(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=Ld(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 Sne.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}:e===`ok-generator`?{id:e,classification:`classified-ok-generator`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function zd(e){let t=bd(e);if(t.kind!==`linked`)return z(e);try{let n=H(L(t.path,`commondir`),`utf-8`).trim();return n===``?z(e):z(I(z(t.path,n)),t.projectSubPath)}catch{return z(e)}}function Bd(e){return e.kind??`other`}function Pne(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Vd=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Bd(t),i=Pne(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-DiZ_Z58g.mjs`);await e(L(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 Hd=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Ud={"claude-acp":`claude`,"codex-acp":`codex`,opencode:`opencode`,"pi-acp":`pi`},Wd=`acp-agents.json`,Gd=`acp-registry-cache.json`;function Kd(){let e=Wu(),t=Vu(),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}`}const qd=new Set([`goose`,`fast-agent`,`crow-cli`]);function Jd(e,t){let n=t.trim();return n.length===0?e:qd.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Yd(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 Xd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Yd).map(e=>({...e,name:Jd(e.id,e.name)})):null}var Zd=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=Xd(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-DiZ_Z58g.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,Gd),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=Xd(await Yu(L(this.localDir,Gd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Qd(e,t){let n;try{n=await Yu(L(e,Wd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Wd} 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 ${Wd} entry`)}return i}const $d={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`},ef={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`},Fne={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 f().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Se):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 f().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Se}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 N(e.catch(tf)).transform(e=>e.filter(e=>e!==tf))}const cf=j([O(),A()]).nullable(),lf=A(),uf=P({sessionId:lf,path:A(),content:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),df=P({sessionId:lf,path:A(),line:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),ff=A(),pf=j([g(`read`),g(`edit`),g(`delete`),g(`move`),g(`search`),g(`execute`),g(`think`),g(`fetch`),g(`switch_mode`),g(`other`)]),mf=j([g(`pending`),g(`in_progress`),g(`completed`),g(`failed`)]),hf=P({audience:W(sf(j([g(`assistant`),g(`user`)])).nullish(),()=>void 0),lastModified:W(A().nullish(),()=>void 0),priority:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),gf=P({annotations:W(hf.nullish(),()=>void 0),text:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),_f=P({annotations:W(hf.nullish(),()=>void 0),data:A(),mimeType:A(),uri:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),vf=P({annotations:W(hf.nullish(),()=>void 0),data:A(),mimeType:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),yf=P({annotations:W(hf.nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),mimeType:W(A().nullish(),()=>void 0),name:A(),size:W(O().nullish(),()=>void 0),title:W(A().nullish(),()=>void 0),uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),bf=j([P({mimeType:W(A().nullish(),()=>void 0),text:A(),uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),P({blob:A(),mimeType:W(A().nullish(),()=>void 0),uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)})]),xf=P({annotations:W(hf.nullish(),()=>void 0),resource:bf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Sf=j([gf.and(P({type:g(`text`)})),_f.and(P({type:g(`image`)})),vf.and(P({type:g(`audio`)})),yf.and(P({type:g(`resource_link`)})),xf.and(P({type:g(`resource`)}))]),Cf=P({content:Sf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),wf=P({path:A(),oldText:W(A().nullish(),()=>void 0),newText:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Tf=A(),Ine=P({terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ef=j([Cf.and(P({type:g(`content`)})),wf.and(P({type:g(`diff`)})),Ine.and(P({type:g(`terminal`)}))]),Df=P({path:A(),line:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Of=P({toolCallId:ff,kind:W(pf.nullish(),()=>void 0),status:W(mf.nullish(),()=>void 0),title:W(A().nullish(),()=>void 0),content:W(sf(Ef).nullish(),()=>void 0),locations:W(sf(Df).nullish(),()=>void 0),rawInput:W(f().optional(),()=>void 0),rawOutput:W(f().optional(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),kf=A(),Lne=j([g(`allow_once`),g(`allow_always`),g(`reject_once`),g(`reject_always`)]),Af=P({sessionId:lf,toolCall:Of,options:N(P({optionId:kf,name:A(),kind:Lne,_meta:W(m(A(),f()).nullish(),()=>void 0)})),_meta:W(m(A(),f()).nullish(),()=>void 0)}),jf=P({name:A(),value:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Mf=P({sessionId:lf,command:A(),args:W(sf(A()).optional(),()=>[]),env:W(sf(jf).optional(),()=>[]),cwd:W(A().nullish(),()=>void 0),outputByteLimit:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Nf=P({sessionId:lf,terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Pf=P({sessionId:lf,terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ff=P({sessionId:lf,terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),If=P({sessionId:lf,terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Lf=P({sessionId:lf,toolCallId:W(ff.nullish(),()=>void 0)}),Rf=P({requestId:cf}),Rne=g(`object`),zne=j([g(`email`),g(`uri`),g(`date`),g(`date-time`)]),zf=P({const:A(),title:A(),description:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Bf=P({title:W(A().nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),minLength:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:A().nullish(),format:zne.nullish(),default:W(A().nullish(),()=>void 0),enum:N(A()).nullish(),oneOf:N(zf).nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Vf=P({title:W(A().nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),minimum:O().nullish(),maximum:O().nullish(),default:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Hf=P({title:W(A().nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),minimum:O().nullish(),maximum:O().nullish(),default:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Uf=P({title:W(A().nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),default:W(a().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Wf=P({enum:N(A()),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Bne=P({anyOf:N(zf),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Vne=of(j([Wf.and(P({type:g(`string`)})),af(P({type:A()}),`type`,[`string`]),Bne]),`type`,[`string`]),Gf=P({title:W(A().nullish(),()=>void 0),description:W(A().nullish(),()=>void 0),minItems:O().nullish(),maxItems:O().nullish(),items:Vne,default:W(sf(A()).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Hne=of(j([Bf.and(P({type:g(`string`)})),Vf.and(P({type:g(`number`)})),Hf.and(P({type:g(`integer`)})),Uf.and(P({type:g(`boolean`)})),Gf.and(P({type:g(`array`)})),af(P({type:A()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Une=P({type:W(Rne.optional().default(`object`),()=>`object`),title:W(A().nullish(),()=>void 0),properties:m(A(),Hne).optional().default({}),required:N(A()).nullish(),description:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Kf=T(j([Lf,Rf]),P({requestedSchema:Une})),qf=A(),Jf=T(j([Lf,Rf]),P({elicitationId:qf,url:b()})),Yf=of(T(j([Kf.and(P({mode:g(`form`)})),Jf.and(P({mode:g(`url`)})),af(T(j([Lf,Rf]),P({mode:A()})),`mode`,[`form`,`url`])]),P({message:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Xf=A(),Wne=P({serverId:Xf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Zf=A(),Qf=P({connectionId:Zf,method:A(),params:m(A(),f()).nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Gne=P({connectionId:Zf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),$f=f();P({id:cf,method:A(),params:j([uf,df,Af,Mf,Nf,Pf,Ff,If,Yf,Wne,Qf,Gne,$f]).nullish()});const ep=C().gte(0).lte(65535),Kne=P({image:W(a().optional().default(!1),()=>!1),audio:W(a().optional().default(!1),()=>!1),embeddedContext:W(a().optional().default(!1),()=>!1),_meta:W(m(A(),f()).nullish(),()=>void 0)}),qne=P({http:W(a().optional().default(!1),()=>!1),sse:W(a().optional().default(!1),()=>!1),acp:W(a().optional().default(!1),()=>!1),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Jne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Yne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Xne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Zne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Qne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),$ne=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),ere=P({list:W(Jne.nullish(),()=>void 0),delete:W(Yne.nullish(),()=>void 0),additionalDirectories:W(Xne.nullish(),()=>void 0),fork:W(Zne.nullish(),()=>void 0),resume:W(Qne.nullish(),()=>void 0),close:W($ne.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),tre=P({logout:W(P({_meta:W(m(A(),f()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),nre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),rre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),ire=P({syncKind:j([g(`full`),g(`incremental`)]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),are=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),ore=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),sre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),cre=P({document:W(P({didOpen:W(rre.nullish(),()=>void 0),didChange:W(ire.nullish(),()=>void 0),didClose:W(are.nullish(),()=>void 0),didSave:W(ore.nullish(),()=>void 0),didFocus:W(sre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),lre=P({maxCount:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),ure=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),dre=P({maxCount:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),fre=P({maxCount:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),pre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),mre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),hre=P({recentFiles:W(lre.nullish(),()=>void 0),relatedSnippets:W(ure.nullish(),()=>void 0),editHistory:W(dre.nullish(),()=>void 0),userActions:W(fre.nullish(),()=>void 0),openFiles:W(pre.nullish(),()=>void 0),diagnostics:W(mre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),gre=P({events:W(cre.nullish(),()=>void 0),context:W(hre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),tp=j([g(`utf-16`),g(`utf-32`),g(`utf-8`)]),_re=P({loadSession:W(a().optional().default(!1),()=>!1),promptCapabilities:W(Kne.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(qne.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(ere.optional().default({}),()=>({})),auth:W(tre.optional().default({}),()=>({})),providers:W(nre.nullish(),()=>void 0),nes:W(gre.nullish(),()=>void 0),positionEncoding:W(tp.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),np=A(),vre=P({name:A(),label:W(A().nullish(),()=>void 0),secret:W(a().optional().default(!0),()=>!0),optional:W(a().optional().default(!1),()=>!1),_meta:W(m(A(),f()).nullish(),()=>void 0)}),yre=P({id:np,name:A(),description:W(A().nullish(),()=>void 0),vars:nf(sf(vre),()=>[]),link:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),rp=P({id:np,name:A(),description:W(A().nullish(),()=>void 0),args:W(sf(A()).optional(),()=>[]),env:W(m(A(),A()).optional(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),ip=P({id:np,name:A(),description:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),ap=j([yre.and(P({type:g(`env_var`)})),rp.and(P({type:g(`terminal`)})),ip]),op=P({name:A(),title:W(A().nullish(),()=>void 0),version:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),sp=P({protocolVersion:ep,agentCapabilities:W(_re.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(ap).optional().default([]),()=>[]),agentInfo:W(op.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),cp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),lp=A(),up=j([g(`anthropic`),g(`openai`),g(`azure`),g(`vertex`),g(`bedrock`),A()]),dp=P({apiType:up,baseUrl:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),fp=P({providers:N(P({providerId:lp,supported:nf(sf(up),()=>[]),required:a(),current:dp.nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)})),_meta:W(m(A(),f()).nullish(),()=>void 0)}),pp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),mp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),hp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),gp=A(),_p=P({currentModeId:gp,availableModes:nf(sf(P({id:gp,name:A(),description:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)})),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),vp=A(),yp=j([g(`mode`),g(`model`),g(`model_config`),g(`thought_level`),A()]),bp=A(),xp=P({value:bp,name:A(),description:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Sp=P({group:A(),name:A(),options:nf(sf(xp),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Cp=P({currentValue:bp,options:j([N(xp),N(Sp)])}),wp=P({currentValue:a()}),Tp=T(j([Cp.and(P({type:g(`select`)})),wp.and(P({type:g(`boolean`)}))]),P({id:vp,name:A(),description:W(A().nullish(),()=>void 0),category:W(yp.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)})),Ep=P({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(Tp).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Dp=P({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(Tp).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Op=P({sessions:nf(sf(P({sessionId:lf,cwd:A(),additionalDirectories:W(sf(A()).optional(),()=>[]),title:W(A().nullish(),()=>void 0),updatedAt:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),kp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ap=P({sessionId:lf,modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(Tp).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),jp=P({modes:W(_p.nullish(),()=>void 0),configOptions:W(sf(Tp).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Mp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Np=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Pp=P({configOptions:nf(sf(Tp),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Fp=P({stopReason:j([g(`end_turn`),g(`max_tokens`),g(`max_turn_requests`),g(`refusal`),g(`cancelled`)]),usage:W(P({totalTokens:O(),inputTokens:O(),outputTokens:O(),thoughtTokens:W(O().nullish(),()=>void 0),cachedReadTokens:W(O().nullish(),()=>void 0),cachedWriteTokens:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ip=P({sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Lp=A(),Rp=P({line:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(m(A(),f()).nullish(),()=>void 0)}),zp=P({start:Rp,end:Rp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Bp=P({range:zp,newText:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Vp=P({id:Lp,uri:A(),edits:N(Bp),cursorPosition:W(Rp.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Hp=P({id:Lp,uri:A(),position:Rp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Up=P({id:Lp,uri:A(),position:Rp,newName:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Wp=P({id:Lp,uri:A(),search:A(),replace:A(),isRegex:a().nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Gp=P({suggestions:N(j([Vp.and(P({kind:g(`edit`)})),Hp.and(P({kind:g(`jump`)})),Up.and(P({kind:g(`rename`)})),Wp.and(P({kind:g(`searchAndReplace`)}))])),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Kp=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),qp=f(),Jp=f(),Yp=P({code:j([g(-32700),g(-32600),g(-32601),g(-32602),g(-32603),g(-32800),g(-32e3),g(-32002),C().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:A(),data:W(f().optional(),()=>void 0)});j([P({id:cf,result:j([sp,cp,fp,pp,mp,hp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Gp,Kp,qp,Jp])}),P({id:cf,error:Yp})]);const Xp=P({content:Sf,messageId:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Zp=P({toolCallId:ff,title:A(),kind:W(pf.optional(),()=>void 0),status:W(mf.optional(),()=>void 0),content:W(sf(Ef).optional(),()=>[]),locations:W(sf(Df).optional(),()=>[]),rawInput:W(f().optional(),()=>void 0),rawOutput:W(f().optional(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Qp=j([g(`high`),g(`medium`),g(`low`)]),$p=j([g(`pending`),g(`in_progress`),g(`completed`)]),em=P({content:A(),priority:Qp,status:$p,_meta:W(m(A(),f()).nullish(),()=>void 0)}),tm=P({entries:nf(sf(em),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),nm=A(),rm=P({planId:nm,entries:nf(sf(em),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),im=P({planId:nm,uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),am=P({planId:nm,content:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),om=P({plan:j([rm.and(P({type:g(`items`)})),im.and(P({type:g(`file`)})),am.and(P({type:g(`markdown`)}))]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),sm=P({planId:nm,_meta:W(m(A(),f()).nullish(),()=>void 0)}),cm=P({hint:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),lm=P({availableCommands:nf(sf(P({name:A(),description:A(),input:W(cm.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)})),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),um=P({currentModeId:gp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),dm=P({configOptions:nf(sf(Tp),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),fm=P({title:W(A().nullish(),()=>void 0),updatedAt:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),pm=P({amount:O(),currency:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),mm=P({used:O(),size:O(),cost:W(pm.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),hm=P({sessionId:lf,update:j([Xp.and(P({sessionUpdate:g(`user_message_chunk`)})),Xp.and(P({sessionUpdate:g(`agent_message_chunk`)})),Xp.and(P({sessionUpdate:g(`agent_thought_chunk`)})),Zp.and(P({sessionUpdate:g(`tool_call`)})),Of.and(P({sessionUpdate:g(`tool_call_update`)})),tm.and(P({sessionUpdate:g(`plan`)})),om.and(P({sessionUpdate:g(`plan_update`)})),sm.and(P({sessionUpdate:g(`plan_removed`)})),lm.and(P({sessionUpdate:g(`available_commands_update`)})),um.and(P({sessionUpdate:g(`current_mode_update`)})),dm.and(P({sessionUpdate:g(`config_option_update`)})),fm.and(P({sessionUpdate:g(`session_info_update`)})),mm.and(P({sessionUpdate:g(`usage_update`)}))]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),gm=P({elicitationId:qf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),_m=P({connectionId:Zf,method:A(),params:W(m(A(),f()).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),vm=f();P({method:A(),params:j([hm,gm,_m,vm]).nullish()});const bre=P({readTextFile:W(a().optional().default(!1),()=>!1),writeTextFile:W(a().optional().default(!1),()=>!1),_meta:W(m(A(),f()).nullish(),()=>void 0)}),xre=P({configOptions:W(P({boolean:W(P({_meta:W(m(A(),f()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Sre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Cre=P({terminal:W(a().optional().default(!1),()=>!1),_meta:W(m(A(),f()).nullish(),()=>void 0)}),wre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Tre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ere=P({form:W(wre.nullish(),()=>void 0),url:W(Tre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Dre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ore=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),kre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Are=P({jump:W(Dre.nullish(),()=>void 0),rename:W(Ore.nullish(),()=>void 0),searchAndReplace:W(kre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),ym=P({protocolVersion:ep,clientCapabilities:W(P({fs:W(bre.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(a().optional().default(!1),()=>!1),session:W(xre.nullish(),()=>void 0),plan:W(Sre.nullish(),()=>void 0),auth:W(Cre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(Ere.nullish(),()=>void 0),nes:W(Are.nullish(),()=>void 0),positionEncodings:W(sf(tp).optional(),()=>[]),_meta:W(m(A(),f()).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(op.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),bm=P({methodId:np,_meta:W(m(A(),f()).nullish(),()=>void 0)}),xm=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Sm=P({providerId:lp,apiType:up,baseUrl:A(),headers:m(A(),A()).optional(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Cm=P({providerId:lp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),wm=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Tm=P({name:A(),value:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),jre=P({name:A(),url:A(),headers:N(Tm),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Mre=P({name:A(),url:A(),headers:N(Tm),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Nre=P({name:A(),serverId:Xf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Pre=P({name:A(),command:A(),args:N(A()),env:N(jf),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Em=j([jre.and(P({type:g(`http`)})),Mre.and(P({type:g(`sse`)})),Nre.and(P({type:g(`acp`)})),Pre]),Dm=P({cwd:A(),additionalDirectories:W(sf(A()).optional(),()=>[]),mcpServers:nf(sf(Em),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Om=P({mcpServers:nf(sf(Em),()=>[]),cwd:A(),additionalDirectories:W(sf(A()).optional(),()=>[]),sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),km=P({cwd:A().nullish(),cursor:A().nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Am=P({sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),jm=P({sessionId:lf,cwd:A(),additionalDirectories:W(sf(A()).optional(),()=>[]),mcpServers:W(sf(Em).optional(),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Mm=P({sessionId:lf,cwd:A(),additionalDirectories:W(sf(A()).optional(),()=>[]),mcpServers:W(sf(Em).optional(),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Nm=P({sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Pm=P({sessionId:lf,modeId:gp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Fm=T(j([P({value:a(),type:g(`boolean`)}),P({value:bp})]),P({sessionId:lf,configId:vp,_meta:W(m(A(),f()).nullish(),()=>void 0)})),Im=P({sessionId:lf,prompt:N(Sf),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Fre=P({uri:A(),name:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ire=P({name:A(),owner:A(),remoteUrl:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Lm=P({workspaceUri:W(A().nullish(),()=>void 0),workspaceFolders:N(Fre).nullish(),repository:W(Ire.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Lre=j([g(`automatic`),g(`diagnostic`),g(`manual`)]),Rre=P({uri:A(),languageId:A(),text:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),zre=P({startLine:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Bre=P({uri:A(),excerpts:N(zre),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Vre=P({uri:A(),diff:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Hre=P({action:A(),uri:A(),position:Rp,timestampMs:O(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Ure=P({uri:A(),languageId:A(),visibleRange:W(zp.nullish(),()=>void 0),lastFocusedMs:W(O().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Wre=j([g(`error`),g(`warning`),g(`information`),g(`hint`)]),Gre=P({uri:A(),range:zp,severity:Wre,message:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Kre=P({recentFiles:N(Rre).nullish(),relatedSnippets:N(Bre).nullish(),editHistory:N(Vre).nullish(),userActions:N(Hre).nullish(),openFiles:N(Ure).nullish(),diagnostics:N(Gre).nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Rm=P({sessionId:lf,uri:A(),version:O(),position:Rp,selection:zp.nullish(),triggerKind:Lre,context:Kre.nullish(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),zm=P({sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)});P({id:cf,method:A(),params:j([ym,bm,xm,Sm,Cm,wm,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Qf,$f]).nullish()});const qre=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Jre=P({content:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Yre=P({optionId:kf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Xre=P({outcome:j([P({outcome:g(`cancelled`)}),Yre.and(P({outcome:g(`selected`)}))]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Zre=P({terminalId:Tf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Qre=P({exitCode:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),$re=P({output:A(),truncated:a(),exitStatus:W(Qre.nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),eie=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),tie=P({exitCode:W(C().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(A().nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)}),nie=P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),rie=j([A(),O(),O(),a(),N(A())]),Bm=P({content:m(A(),rie).nullish()});j([P({id:cf,result:j([qre,Jre,Xre,Zre,$re,eie,tie,nie,of(T(j([Bm.and(P({action:g(`accept`)})),P({action:g(`decline`)}),P({action:g(`cancel`)}),af(P({action:A()}),`action`,[`accept`,`cancel`,`decline`])]),P({_meta:W(m(A(),f()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),P({connectionId:Zf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),P({_meta:W(m(A(),f()).nullish(),()=>void 0)}),Jp,qp])}),P({id:cf,error:Yp})]);const Vm=P({sessionId:lf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Hm=P({sessionId:lf,uri:A(),languageId:A(),version:O(),text:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),iie=P({range:zp.nullish(),text:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Um=P({sessionId:lf,uri:A(),version:O(),contentChanges:nf(sf(iie),()=>[]),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Wm=P({sessionId:lf,uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Gm=P({sessionId:lf,uri:A(),_meta:W(m(A(),f()).nullish(),()=>void 0)}),Km=P({sessionId:lf,uri:A(),version:O(),position:Rp,visibleRange:zp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),qm=P({sessionId:lf,id:Lp,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Jm=P({sessionId:lf,id:Lp,reason:W(j([g(`rejected`),g(`ignored`),g(`replaced`),g(`cancelled`)]).nullish(),()=>void 0),_meta:W(m(A(),f()).nullish(),()=>void 0)});P({method:A(),params:j([Vm,Hm,Um,Wm,Gm,Km,qm,Jm,_m,vm]).nullish()}),P({requestId:cf,_meta:W(m(A(),f()).nullish(),()=>void 0)}),Kf.and(P({mode:g(`form`)})).and(P({message:A()})),Jf.and(P({mode:g(`url`)})).and(P({message:A()})),j([Lf,Rf]).and(P({message:A()})),Bf.and(P({type:g(`string`)})),Vf.and(P({type:g(`number`)})),Hf.and(P({type:g(`integer`)})),Uf.and(P({type:g(`boolean`)})),Gf.and(P({type:g(`array`)})),Wf.and(P({type:g(`string`)})),Bm.and(P({action:g(`accept`)})),P({action:g(`decline`)}),P({action:g(`cancel`)});const Ym=`$/cancel_request`;function Xm(e){return typeof e==`object`&&!!e}function aie(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function oie(e){if(!(!Xm(e)||!aie(e.requestId)))return e.requestId}const Zm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Qm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function sie(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function cie(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 $m(e){if(e instanceof nh)return e.toResult();if(cie(e))return nh.invalidParams(e.format()).toResult();let t=sie(e);try{return nh.internalError(t?JSON.parse(t):{}).toResult()}catch{return nh.internalError({details:t}).toResult()}}function lie(e){return e instanceof nh&&e.code===-32800?e:nh.requestCancelled(e)}function uie(e,t){let n=die(e,t);return n?n.toResult():$m(e)}function die(e,t){if(!(!t.aborted||!fie(e)))return lie(t.reason)}function fie(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var pie=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 nh?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Qm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},eh=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},mie=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}},th=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new mie(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 hie}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 eh(()=>{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 Qm(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(Ym,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Qm(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 Zm.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(!Xm(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(nh.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(uie(n,t.responder.signal));else{let t=$m(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 pie(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&&Xm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new nh(n,r,i))}else t.reject(nh.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==Ym)return;let t=oie(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(nh.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Qm(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)}},hie=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)??Zm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Zm.no(r):await n(t(r.params),r.responder,i)??Zm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Zm.no(r):await n(t(r.params),i)??Zm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new th(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},nh=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}}},gie=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 _ie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new gie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Xm(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)+`
@@ -1184,7 +1184,7 @@ tags: [lore, history]
1184
1184
  `);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(),Me.release(Yr))}),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()),Me.release(Yr))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Me.release(Yr))})}let Fi=`local-op-auth-signout`,Ii=q(_s,async(e,t,n)=>{let r=n.host??di();if(!Me.tryAcquire($r)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Fi,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ae,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=lu(e,i,Dw({...Ir,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,Ni,{},{handler:Fi})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Fi,cause:e})}finally{Me.release($r)}},{handler:Fi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Fi})}),Li=`/api/local-op/auth/set-identity`,Ri=`local-op-auth-set-identity`,zi=q(cte,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!M){K(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:Ri});return}if(!Me.tryAcquire(Li)){K(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:Ri,extraHeaders:{"Retry-After":`5`}});return}try{dB(M,r,i),j?.()?.refreshIdentity().catch(()=>{}),J(t,200,Ni,{},{handler:Ri})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:Ri,cause:e})}finally{Me.release(Li)}},{handler:Ri,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ri})});async function Bi(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=j?.();if(!e){J(t,200,Ct,{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,Ct,e.getStatus(),{handler:`sync-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}function Vi(e){let t=L(M??c,e),n=rN(R(c,t));if(!n||n.startsWith(`..`))return;let r=Xx(n);if(f().has(r))return{kind:`doc`,docName:r};if(he&&!he.isExcluded(n,{bypassFilters:!0,showOk:!0})&&V(t))return{kind:`asset`,path:n}}async function Ui(e,t){if(r(e,t,{handler:`git-worktree-status`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`git-worktree-status`,extraHeaders:{Allow:`GET`}});return}try{let e=j?.();J(t,200,Wt,await gB(M??c,e?t=>e.isSyncScopedPath(t):()=>!1,Vi),{handler:`git-worktree-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`git-worktree-status`,cause:e})}}}let Wi=q(see,async(e,t,n)=>{let r=j?.();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,Ba,{op:i},{handler:`sync-trigger`}),r.trigger(i).catch(e=>{X.error({err:e,op:i},`[sync] fire-and-forget trigger failed`)})},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?j?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1}),Ki=q(ht,async(e,t,n)=>{let r=j?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-blocking`});return}if(r.getBlockingPaths().length===0){K(t,409,`urn:ok:error:no-blocking-changes`,`No local changes are blocking a merge.`,{handler:`sync-resolve-blocking`});return}try{let e=r.getBlockingPaths(),n=await r.commitBlockingPaths();J(t,200,lte,{action:`commit`,paths:e,...n===null?{}:{commitSha:n}},{handler:`sync-resolve-blocking`}),r.trigger(`sync`).catch(e=>{X.error({err:e},`[sync] resolve-blocking follow-up sync failed`)})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-resolve-blocking`,cause:e})}},{handler:`sync-resolve-blocking`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-blocking`})});async function Yi(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=j?.();J(t,200,hee,{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 Xi=q(Tr,async(e,t,n)=>{let r=j?.();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,jt,{},{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`})?j?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Zi(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(!M){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 a=Xx(i),s=o.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=j?.(),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=Oc({baseDir:M,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),a=Xx(i),s=o.documents.get(a),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=be?be(a):null;t!==null&&(c=t,l=!0)}else{SL(L(M,i),M,{allowShareableOkArtifact:rP});try{c=H(L(M,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;J(t,200,ys,{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)]),a=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=Xx(i),t=o.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=be?be(e):null;t!==null&&!Bbe(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,ys,{file:i,base:a,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 Qi(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=QJ(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,Tee,{plan:await aY({projectDir:c,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof zJ){K(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof BJ){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 $i=q(zee,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=QJ(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,Iee,{result:await rY(i,{projectDir:c,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`})}),ea=q(Cee,async(e,t,n)=>{let r=QJ(n.packId);if(r===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${n.packId}" is not registered.`});return}try{J(t,200,ste,await Pve(c,r),{handler:`seed-install-pack-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-install-pack-skill`})});async function ta(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,pte,{packs:$J()},{handler:`seed-packs`})}}let na=q(Kee,async(e,t,n)=>{if(n.out!==void 0&&!SK(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,io,await RI({...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`})});function ra(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=z(c),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${B}`)?(K(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function aa(e,t,n=`template`){return!e||!sr.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 sa(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:z(e,i);if(a!==e&&!a.startsWith(`${e}${B}`))continue;let o=z(a,`.ok`,`templates`,`${n}.md`);if(V(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function ca(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 la=fK({GET:q(Gr,async(e,t)=>{try{let n=ra(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await KA(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(V(i))try{let e=(0,ZD.parse)(await Yu(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,Nee,{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(tte,async(e,t,n)=>{try{if(De){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=pO(n,ce);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=ra(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=QA({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`&&(An(e,kn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),Vn(`folder-config-put`))}J(t,200,Hee,{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 da(e,t,n){let r=o.documents.get(e);return r&&DS(r)?(AS(n,new kS({file:`${e}.md`}),t),!0):!1}function pa(e,t,n){let r=o.documents.get(e);return r&&DS(r)?(AS(n,new kS({file:`${e}.md`}),t),!0):!1}let ha=e=>{let{body:t}=ns(e);return{frontmatter:Hi(e)??{},body:t}},ga=q(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!aa(r,t,`template-get`))return;let i=ra(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=sa(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=Et(await Yu(c,`utf-8`)),f=d.identity,p=d.starterContent;J(t,200,Uee,{template:{name:r,folder:l,scope:u,path:R(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}),va=q(ete,async(e,t,n)=>{try{if(De){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=pO(n,ce);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(!aa(r,t,`template-put`))return;let i=ra(n.folder,t,`folder`,`template-put`);if(!i||da(oo(i.folderRel,r),`template-put`,t))return;let a=kj({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ca(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 o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!V(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=oo(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=xn(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Bb(h.dc.document,a.content,`agent`)},h.origin);let g=await ut(u);if(g?.kind===`failure`){dt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){mt(t,`template-put`);return}Nt(u,a.content),An(e,kn(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),Vn(`template-put`),J(t,200,kee,{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`}),ya=q(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!aa(r,t,`template-delete`))return;let i=ra(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=Aa(n,ce);if(a.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(da(oo(i.folderRel,r),`template-delete`,t))return;await Vt([oo(i.folderRel,r)],`deleted-upstream`);let o=jj({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&&(An(a,kn(`template`,i.folderRel,r),`template-delete: ${o.path}`),Vn(`template-delete`),ye?.setDeleted(oo(i.folderRel,r))),J(t,200,nte,{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}),ba=fK({GET:ga,PUT:va,POST:q(wee,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!aa(n.fromName,t,`template-move`)||!aa(n.toName,t,`template-move`))return;let r=ra(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=ra(n.toFolder,t,`folder`,`template-move`);if(!i||da(oo(r.folderRel,n.fromName),`template-move`,t))return;await Vt([oo(r.folderRel,n.fromName)],`renamed`);let a=await Nj({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await oZ(M,e,t);return n||aZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=sa(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}ye?.setDeleted(oo(r.folderRel,n.fromName));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=br(H(z(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=Aj({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ca(n.frontmatter)});t.ok||(o=t.error)}}try{Nt(oo(i.folderRel,n.toName),H(z(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(An(e,kn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),Vn(`template-move`),je?.(`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,Wee,{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:ya},{handler:`template`}),xa=q(Qee,async(e,t,n)=>{try{if(De){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=pO(n,ce);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(!cZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=nt(r);if(cS(i)||lS(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=GX(c,`file`,i);if(!V(a)){K(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let l=o.documents.get(i);if(n.deleteSource){let e=j?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=l!==void 0&&DS(l),a=n.has(r);if(i||a){AS(t,new kS({file:r}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await o.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}=KX(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!aa(d,t,`template-import`))return;let f=ra(n.targetFolder,t,`folder`,`template-import`);if(!f||da(oo(f.folderRel,d),`template-import`,t))return;let{frontmatter:p,body:m}=ns(u),g=Ji(p),_={};try{g.trim()&&(_=(0,ZD.parse)(g))}catch{}let v=n.title||_?.title||Gk(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,ZD.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=kj({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=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!V(w),E=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),D=oo(f.folderRel,d),{agentId:O,agentName:ee,colorSeed:te,clientName:k}=xn(n),A=await s.getSession(D,O,{displayName:ee,colorSeed:te,clientName:k});A.dc.document.transact(()=>{Bb(A.dc.document,C.content,`agent`)},A.origin);let ne=await ut(D);if(ne?.kind===`failure`){dt(t,ne.failure,`template-import`);return}if(ne?.kind===`divergence`){mt(t,`template-import`);return}Nt(D,C.content),An(e,kn(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await Vt([i],`deleted-upstream`),ye&&ye.setDeleted(i),nc(a),h?.({kind:`delete`,path:a,docName:i})),Vn(`template-import`),je?.(`files`),J(t,200,Bee,{path:E,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 Sa(e){return!!e&&e.length<=64&&Ta.test(e)}function Ca(e,t,n){return Sa(e)?!0:(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)}function wa(e,t,n){let r=mte.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 Ea=le??Hu(),Da=kbe({contentDir:c,skillsHome:Ea,effectiveInstallMode:za});function Oa(e){return z(e===`global`?Ea:c,`.ok`,`skills`)}function ka(e,t,n){let r=z(Oa(e),t);if(e===`global`){if(n!==void 0){let e=yL(Ea).find(e=>e.name===t&&e.hosts.includes(n));return e?z(Ea,e.dir):null}let e=bL(Ea,t);return e===null?V(L(r,`SKILL.md`))?r:null:e}let i=vL(c).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?z(c,i.dir):n===void 0&&V(L(r,`SKILL.md`))?r:null}function Aa(e,t){let n=e.searchParams;return pO({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 ja(e,t){let n=e===`project`?M:Ea;if(!n)return`symlink`;try{return Bo(L(n,...sD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function Ma(e){let t=e===`project`?M:Ea;return t?L(t,...sD):null}function Na(e,t,n,r={}){let i=Ma(e);return i?HK(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 Pa(e,t,n){let r=Ma(e),i=Ma(t);if(!r||!i)return!1;let a=BK(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await HK(i,e=>({...e,skills:{...e.skills,[n]:o}})),await HK(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function Fa(e,t,n){let r=Ma(e);return r?HK(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Ia(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 za(e,t,n){let r=e===`project`?M:Ea;return(r?R_e(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Va(e){let t=ka(`project`,e);return t?R(c,t).split(B).join(`/`):`${wi}/${e}`}let Ha=tO.project;function Ua(e,t,n){let r=[],i=null,a=[...Pr.map(e=>({id:e,root:st[e]??``})),{id:`agents`,root:ma}];for(let{id:o,root:s}of a){if(!s)continue;let a=z(e,...s.split(`/`),t);V(z(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=z(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:R(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function Wa(e){let t=vde(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 Ga(e,t){if(!rO(t))return null;let n=Ua(e,t);if(!n)return null;let r=_D(n.dir)?.contentHash??``,i;try{i=Ru(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:bi,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}let Ja=null;function Ya(e){let t=Date.now();if(Ja&&Ja.identity===e&&t-Ja.at<3e4)return Ja.byName;let n=new Map;try{n=tt(In(le===void 0?{}:{home:le}).skills,e=>_D(e)?.contentHash)}catch(e){X.warn({err:e},`plugin upstream index failed; origins will be omitted`)}return Ja={at:t,identity:e,byName:n},n}function Za(e,t){return Ya(t).get(e)?.contentHash??null}function Qa(e,t,n){let r=Ya(t).get(e);if(!r)return null;try{if(U(n)!==U(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function $a(e,t,n){let r=Ya(t).get(e);if(!r)return null;if(n!==void 0)try{if(U(n)===U(r.home))return null}catch{}let i;try{i=Ru(L(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){X.warn({err:e,home:r.home},`plugin bundle unreadable; origin dated epoch`),i=new Date(0).toISOString()}return{source:r.home,skill:e,contentHash:r.contentHash,autoUpdate:!1,importedAt:i}}function eo(e,t){let n=iO.find(t=>tO[t]===e);if(n===void 0||t!==void 0&&aO[n]!==(t===`global`?`user`:`project`))return null;try{let e=z(lO(n,{checkDesktop:!0}),`SKILL.md`);return V(e)?e:null}catch(t){return X.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function ro(e,t,n){let r=Ua(e,t),i=r?.skillMd??eo(t);if(i===null)return null;let a;try{let{frontmatter:e}=ha(H(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=Ga(e,t),s=_D(I(i));return{name:t,...a===void 0?{}:{description:a},scope:n,path:r?.relPath??i,absolutePath:i,installed:(r?.hosts.length??0)>0,hosts:r?.hosts??[],managed:!0,...s?{size:qi(s)}:{},...o?{origin:Wa(o)}:{}}}function ao(e,t,n){return rO(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 oo(e,t){return dte(e,t)}function so(e,t){return R(t===`global`?Ea:c,e).split(/[\\/]/).filter(Boolean).join(`/`)}function co(e){return e===`global`?Ea:M}async function lo(e,t,n,r={}){let i=await LN(e,t),a=n===`project`?c:Ea;if(r.purge!==void 0){rL(t,e,Pr,WI(n));for(let e of Sge(a,n,t,r.purge.contentHash))dc(e,{recursive:!0,force:!0});return i!==null}if(!V(z(Oa(n),t,`SKILL.md`))){let r=(n===`project`?vL(c):yL(Ea)).find(e=>e.name===t);if(r){let a=n===`project`?c:Ea,o=z(a,r.dir),s=z(a,`.agents`,`skills`),l=L(s,t);if(V(s)&&!V(L(l,`SKILL.md`))){let e=!1;try{e=U(o)===U(l)}catch{e=!1}e||uc(o,l,{recursive:!0,dereference:!0})}return nL({canonicalAbs:V(L(l,`SKILL.md`))?l:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...Pr],roots:WI(n)}),i!==null}}return rL(t,e,Pr,WI(n)),i!==null}function uo(e,t){let n=[];if(!V(e))return{skills:n,truncated:!1};let r;try{r=Nu(e,{withFileTypes:!0})}catch(r){return F(`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()||!Ta.test(a.name))continue;if(n.length>=500){i=!0;break}let r=z(e,a.name,`SKILL.md`);if(!V(r))continue;let o;try{let{frontmatter:e}=ha(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:so(r,t),absolutePath:r})}return{skills:n,truncated:i}}function fo(e){return`!/${I(e).split(B).join(`/`)}/`}let po=q(jr,JB(async(e,t,n)=>{if(!Ca(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){K(t,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=vL(c).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=FX(z(c,r,`SKILL.md`),c)??`${r}/SKILL.md`,a=I(i),o=i,s=fo(a),l=`.gitignore`,u=z(c,l);if(he&&!he.isPathIgnored(o)){J(t,200,Ur,{line:s,gitignorePath:l,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){J(t,200,Ur,{line:s,gitignorePath:l,applied:!1},{handler:`skill-track-in-git`});return}let d=V(u)?H(u,`utf-8`):null;if((d??``).split(`
1185
1185
  `).some(e=>e.trim()===s)){K(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${l}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(Bu(u,`${d===null||d.endsWith(`
1186
1186
  `)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),Fn(),await he?.rebuildIgnorePatterns(),he?.isPathIgnored(o)){d===null?Iu(u,{force:!0}):Bu(u,d,`utf-8`),Fn(),await he.rebuildIgnorePatterns(),K(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${l} was left unchanged.`,{handler:`skill-track-in-git`});return}je?.(`files`),J(t,200,Ur,{line:s,gitignorePath:l,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),mo={lastKey:null},ho=q(Gr,JB(async(e,t)=>{let n=(he?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(M?LI(M).join(`,`):``)+``+II(Ea).map(e=>e.editorId).join(`,`)+``+yL(Ea).map(e=>e.dir).sort().join(`,`);if(Mn!==null&&Mn.fp!==n&&Fn(),Mn!==null&&Mn.gen===jn&&Mn.fp===n&&Date.now()-Mn.at<5e3){J(t,200,ii,Mn.body,{handler:`skills-list`});return}let r=Oa(`project`),i=uo(r,`project`),a=uo(Oa(`global`),`global`),o=M?LI(M):[],s=II(Ea).map(e=>e.editorId),l=M?PN(M).skills:{},u=PN(Ea).skills,d=M?lD(V(L(M,...sD))?H(L(M,...sD),`utf-8`):``)??null:null,f=Wa,p=(e,t,n)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=n?d?.skills[e.name]:void 0,o=a?f(a):void 0,s=a?.localHash!==void 0&&Vo(r,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}:{}}}),m=M?Bq(M):{},h=(e,t,n)=>{let r=[];for(let i of t??[]){let t=z(e,i.path);if(n!==void 0&&t===z(n))continue;let a=!1;try{a=Du(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}},g=M?lL(c,`project`):{},_=mL(g,`project`),v=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),y=zd(M??c),b=kve(c),x=fL(`project`),S=fL(`global`),C=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),w=new Set,T=Lde(c),E=e=>{let t=zde(T,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},D=M?vL(c).map(e=>{let t=!w.has(e.name);w.add(e.name);let n=z(c,e.dir),r=t?Qa(e.name,y,n)??E(n):null,i=t&&r===null?d?.skills[e.name]??Ga(c,e.name)??$a(e.name,y,n):void 0,a=i?f(i):void 0,s=i?.localHash===void 0?(()=>{if(!i||!t)return!1;let n=Za(e.name,y);return n!==null&&b.isModified(`project`,e.name,e.contentHash,n)})():e.contentHash!==i.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:z(c,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:o,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(g).length>0?{hostAliases:g}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...r===null?{}:{plugin:r},...(()=>{let n=C(t?m[e.name]:void 0,_).filter(e=>!v(e.path,x));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=h(M,C(t?m[e.name]:void 0,_),z(c,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...za(`project`,e.name,e)===`link`?{linkMode:!0}:{},...a?{origin:a}:{},...s?{modified:!0}:{},...i?.baselineRef===void 0?{}:{revertable:!0},...rO(e.name)?{managed:!0}:{}}}):[],O=Bq(Ea),ee=Bo(L(Ea,...sD)),te=lL(Ea,`global`),k=mL(te,`global`),A=new Set(yL(Ea).map(e=>e.name));a.skills=a.skills.filter(e=>!A.has(e.name));let ne=new Set,re=yL(Ea).map(e=>{let t=!ne.has(e.name);ne.add(e.name);let n=t?O[e.name]:void 0,r=bL(Ea,e.name),i=r!==null&&z(Ea,e.dir)!==z(r)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:z(Ea,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],...i===void 0?{}:{hostQualifier:i},size:e.size,installableEditors:s,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(te).length>0?{hostAliases:te}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=h(Ea,C(n,k),z(Ea,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=C(n,k).filter(e=>!v(e.path,S));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...za(`global`,e.name,e)===`link`?{linkMode:!0}:{},...rO(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=z(Ea,e.dir),r=Qa(e.name,y,n);if(r!==null)return{plugin:r};let i=ee.skills[e.name]??Ga(Ea,e.name)??$a(e.name,y,n);if(!i)return{};let a=i.localHash===void 0?(()=>{let t=Za(e.name,y);return t!==null&&b.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==i.localHash;return{origin:f(i),...a?{modified:!0}:{}}})()}}),ie=new Set(D.map(e=>e.name)),j=M&&!i.skills.some(e=>e.name===Ha)&&!ie.has(Ha)?ro(M,Ha,`project`):null,ae=new Set(re.map(e=>e.name)),oe=oO.map(e=>tO[e]).filter(e=>!a.skills.some(t=>t.name===e)&&!ae.has(e)).map(e=>ro(Ea,e,`global`)).filter(e=>e!==null),se=new Set(D.map(e=>e.name)),ce=[...p(i,l,!0).filter(e=>!se.has(e.name)),...D,...p(a,u,!1),...re,...j?[j]:[],...oe];b.flush();let le={skills:ce.map(e=>{let t=e.scope===`project`&&e.absolutePath?FX(e.absolutePath,c):null,n=e.absolutePath?bge(I(e.absolutePath)):[],r=n.length>0?{...e,filePaths:n}:e,i=t===null||t===e.path?r:{...r,canonicalPath:t},a=t??e.path;return e.scope===`project`&&he?.isPathIgnored(a)===!0?{...i,ignored:!0}:i}),truncated:i.truncated||a.truncated},ue=await Hbe(D.map(e=>e.path),he??null,mo)?{...le,skills:le.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=he?.isPathIgnored(t)===!0;if(n===(e.ignored===!0))return e;if(n)return{...e,ignored:!0};let{ignored:r,...i}=e;return i})}:le;Mn={at:Date.now(),gen:jn,fp:n,body:ue},J(t,200,ii,ue,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),go=q(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ca(r,t,`skill-get`))return;let i=wa(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(rO(r)){let e=i===`global`?Ea:M,a=e?Ua(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=ha(await Yu(a.skillMd,`utf-8`));J(t,200,Pi,{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:aL(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=ka(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=z(o,`SKILL.md`),{frontmatter:c,body:l}=ha(await Yu(s,`utf-8`));J(t,200,Pi,{skill:{name:r,scope:i,path:so(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:aL(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 vo(e,t){!k||hS(e)||(he&&(Fn(),he.refreshInPlaceSkillDirs(),Rn()),St(e,t,`skill-put`))}let yo=q(Vee,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Ca(n.name,t,`skill-put`)||ao(n.name,t,`skill-put`))return;let r=aj({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`?c:Ea,a=ka(n.scope,n.name);if(a===null){let a=hL(i,n.scope);if(a===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let o=oj({skillsRoot:z(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`&&(An(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),Vn(`skill-put`)),await vo(n.scope===`project`?`${a}/${n.name}/SKILL`:os(`global`,n.name),r.content),je?.(`files`),J(t,200,Nn,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=R(i,a).split(B).join(`/`),l=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:os(n.scope,n.name);if(pa(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=xn(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Bb(h.dc.document,r.content,`agent`)},h.origin);let g=await ut(u);if(g?.kind===`failure`){dt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){mt(t,`skill-put`);return}n.scope===`project`&&(An(e,kn(`skill`,``,n.name),`skill-edit: ${l}`),Vn(`skill-put`)),await vo(u,r.content),je?.(`files`),J(t,200,Nn,{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 bo(e,t,n){let r=e===`project`?c:Ea,i=ka(e,t,n);return{root:i===null?Oa(e):I(i),dirRel:i===null?`.ok/skills/${t}`:R(r,i).split(B).join(`/`),realDir:i}}function xo(e,t){let n=e===`project`?c:Ea,r=(e===`project`?vL(c):yL(Ea)).find(e=>e.name===t);r&&nL({canonicalAbs:z(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>oa(e)),roots:WI(e)})}let So=q(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ca(r,t,`skill-delete`))return;let i=wa(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=n.searchParams.get(`host`)??void 0,{root:o,dirRel:s,realDir:c}=bo(i,r,a);if(a!==void 0&&c===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${r}" (${i}) in ${a}.`});return}let l=Aa(n,ce);if(l.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Vt(i===`project`?[...new Set([`${s}/SKILL`,os(i,r)])]:[os(i,r,a)],`deleted-upstream`),a===void 0&&xo(i,r);let u=fj({skillsRoot:o,name:r}),d=Oa(i);if(a===void 0&&u.ok&&d!==o&&V(z(d,r,`SKILL.md`))){let e=fj({skillsRoot:d,name:r});e.ok||X.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!u.ok){let e=u.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:u.error.code,cause:Error(u.error.message)});return}u.existed&&(i===`project`&&(An(l,s,`skill-delete: ${s}`),Fn(),Un(`skill-delete`)),je?.(`files`));let f=co(i);a===void 0&&f&&await lo(f,r,i),J(t,200,Oee,{existed:u.existed,path:u.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}),Co=q(xt,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Ca(n.fromName,t,`skill-move`)||!Ca(n.toName,t,`skill-move`)||ao(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=bo(n.scope,n.fromName);if(ka(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=co(n.scope),o=a?PN(a).skills[n.fromName]:void 0,s=n.scope===`project`?c:Ea,l=(n.scope===`project`?vL(c):yL(Ea)).find(e=>e.name===n.fromName),u=l?I(l.dir):null,d=u===null?[]:Object.entries(lL(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?BI(o.hosts):[],...l?BI(l.hosts):[],...BI(d)])];await Vt(n.scope===`project`?[...new Set([`${i}/SKILL`,os(n.scope,n.fromName)])]:[os(n.scope,n.fromName)],`renamed`),xo(n.scope,n.fromName);let p=await pj({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await oZ(M,e,t);return n||aZ(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=z(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=ha(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=oj({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=kge({base:n.scope===`project`?c:Ea,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){F(`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`)}n.scope===`project`&&!m&&(Fn(),he?.refreshInPlaceSkillDirs(),Po(r,n.fromName,n.toName).then(()=>Fo(x,n.toName)).catch(()=>{}),Rn());let S=so(z(r,n.fromName),n.scope),C=so(z(r,n.toName),n.scope),w=Vo(r,n.toName);if(await Na(n.scope,n.fromName,n.toName,{localHash:w}),n.scope===`project`&&(An(e,kn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),(async()=>{try{await Un(`skill-move`);let t=await Ho(Uo(e),C);t!==void 0&&await Fa(`project`,n.toName,{baselineRef:t})}catch(e){F(`skill-move`).warn({err:e,toName:n.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),a){await LN(a,n.fromName),rL(n.fromName,a,f,WI(n.scope));let e=z(r,n.toName);if(f.length>0){let t=YI(e,n.toName,a,f,ja(n.scope,n.toName),WI(n.scope));await IN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??HI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(je?.(`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,Xe,{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`}),wo=q(jee,async(e,t,n)=>{let{name:r,home:i}=n;if(!Ca(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(!Ru(a).isDirectory()||!V(z(a,`SKILL.md`))){K(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}tz(r,a),J(t,200,ia,{docName:rte(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),Eo=q(oee,async(e,t,n)=>{try{let e=pO(n,ce);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(!Ca(r,t,`skill-move-scope`))return;if(rO(r)){K(t,400,`urn:ok:error:invalid-request`,`"${r}" is a built-in skill and always lives at its own scope.`,{handler:`skill-move-scope`,detail:`BUILTIN_SCOPE_FIXED`});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`&&!M){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:s,realDir:l}=bo(i,r),u=z(o,r),d=(()=>{try{return U(u)}catch{return u}})(),f=a===`project`?c:Ea,p=hL(f,a);if(p===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{handler:`skill-move-scope`,detail:`NO_USABLE_SKILL_HOME`});return}let m=z(f,p),h=z(m,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(z(l)===z(h)||V(h)&&U(l)===U(h)){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(ka(a,r)!==null||V(h)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let g=co(i),_=co(a),v=g?PN(g).skills[r]:void 0,y=i===`project`?c:Ea,b=(i===`project`?vL(c):yL(Ea)).find(e=>e.name===r),x=b?I(b.dir):null,S=x===null?[]:Object.entries(lL(y,i)).filter(([,e])=>e===x).map(([e])=>e),C=[...new Set([...v?BI(v.hosts):[],...b?BI(b.hosts):[],...BI(S)])];await Vt([...new Set([...i===`project`?[`${s}/SKILL`]:[],os(i,r),os(a,r)])],`renamed`),sc(m,{recursive:!0}),uc(d,h,{recursive:!0,dereference:!0}),xo(i,r);let w=fj({skillsRoot:o,name:r});if(w.ok&&d!==u){let e=R((()=>{try{return U(y)}catch{return y}})(),d);e!==``&&!e.startsWith(`..`)&&!hu(e)&&dc(d,{recursive:!0,force:!0})}if(!w.ok){fj({skillsRoot:m,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:w.error.code,cause:Error(w.error.message)});return}let T=await Pa(i,a,r);if(g&&await lo(g,r,i,b?{purge:{contentHash:b.contentHash}}:{}),g&&await z_e(g,r),_&&C.length>0){let e=YI(h,r,_,C,ja(a,n.name),WI(a));await IN(_,r,{...v,scope:a,hosts:e,scripts:v?.scripts??HI(h,r).hasScripts,installedAt:v?.installedAt??new Date().toISOString()})}if(T&&await Fa(a,r,{localHash:Vo(m,r)}),i===`project`||a===`project`){An(e,i===`project`?s:R(c,h).split(B).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`);let t=R(c,h).split(B).join(`/`),n=!!T&&a===`project`;(async()=>{try{if(await Un(`skill-move-scope`),n){let n=await Ho(Uo(e),t);n!==void 0&&await Fa(a,r,{baselineRef:n})}}catch(e){F(`skill-move-scope`).warn({err:e,name:r},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()}if(!V(L(h,`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:R(f,h).split(B).join(`/`)});return}Fn(),he?.refreshInPlaceSkillDirs(),Rn(),je?.(`files`),J(t,200,Ra,{scope:a,path:R(f,h).split(B).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`}),Do=q(qa,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!Ca(n.name,t,`skill-duplicate`)||!Ca(n.toName,t,`skill-duplicate`)||ao(n.toName,t,`skill-duplicate`))return;let r=ka(n.scope,n.name);if(r===null||!V(L(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`?c:Ea,a=hL(i,n.scope);if(a===null){K(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let o=z(i,a),s=z(o,n.toName);if(ka(n.scope,n.toName)!==null||V(s)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let l=_D(r);if(!l){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}sc(o,{recursive:!0}),uc(r,s,{recursive:!0,dereference:!0});let{fenced:u,body:d}=to(l.skillMd),f=To(u,{name:n.toName});if(!f.ok){fj({skillsRoot:o,name:n.toName}),K(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:f.error.kind});return}try{gc(L(s,`SKILL.md`),`${f.nextFenced}${d}`)}catch(e){throw fj({skillsRoot:o,name:n.toName}),e}if(n.scope===`project`){let t=R(c,s).split(B).join(`/`);An(e,kn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),Un(`skill-duplicate`)}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,ate,{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`}),Oo=fK({GET:go,PUT:yo,POST:Co,DELETE:So},{handler:`skill`});function ko(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 Ao(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function jo(e,t){let n=z(e,t),r=R(c,e).split(B).join(`/`),i;try{i=Nu(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(B).join(`/`).replace(/\.md$/i,``)}`)}function Mo(e,t){let n=t.replace(/\.md$/i,``);return`${ua(e).replace(/\/SKILL$/,``)}/${n}`}function No(e,t){let n=z(e,t,`references`);if(!V(n))return[];let r=[],i=(e,t)=>{for(let n of Nu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(z(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function Po(e,t,n){if(!k){F(`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){F(`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=R(c,e).split(B).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),z(e,n,`SKILL.md`));for(let r of No(e,n))i(o(t,r),o(n,r),z(e,n,r));await k.recordDirectMutations(r)}async function Fo(e,t){if(!k||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 k.recordDirectMutations(n)}let Io=fK({GET:q(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ca(r,t,`skill-file-get`))return;let i=wa(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=rO(r)?i===`global`?Ea:M:void 0,s=n.searchParams.get(`host`)??void 0,c=o?Ua(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`:ko(a))??`reference`,u=s,d=o?c?.dir??null:ka(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??z(Oa(i),r),p=z(f,a);if(p!==f&&!p.startsWith(`${f}${B}`)){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?lr.map(t=>`${e[1]}${t}`).find(e=>e!==a&&V(z(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=z(f,n)}let g=await Yu(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,no,{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(Ree,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Ca(n.name,t,`skill-file-put`)||ao(n.name,t,`skill-file-put`))return;let r=ko(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=ka(n.scope,n.name);if(i===null||!V(L(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=R(n.scope===`project`?c:Ea,i).split(B).join(`/`),o=n.path.replace(/\\/g,`/`),l=Ao(n.scope,r,o),u;if(l){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(pa(e,`skill-file-put`,t))return;if(u=!V(z(i,o)),u&&cj(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:c,colorSeed:l,clientName:d}=xn(n),f=await s.getSession(e,r,{displayName:c,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Bb(f.dc.document,n.content,`agent`)},f.origin);let p=await ut(e);if(p?.kind===`failure`){dt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){mt(t,`skill-file-put`);return}}else{let e=lj({skillsRoot:I(i),name:n.name,relPath:o,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`&&(An(e,kn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),Un(`skill-file-put`)),je?.(`files`),J(t,200,fa,{path:o,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(Gr,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!Ca(i,t,`skill-file-delete`)||ao(i,t,`skill-file-delete`))return;let a=wa(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=ko(o);if(s===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=Aa(n,ce);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=ka(a,i),d=u===null?Oa(a):I(u),f=z(u??L(d,i),o);if(V(f)&&Ao(a,s,o)){let e=o.replace(/\.md$/i,``);await Vt([u===null?Mo(i,o):`${R(c,u).split(B).join(`/`)}/${e}`],`deleted-upstream`)}else if(a===`project`&&u!==null&&V(f)&&Ru(f).isDirectory()){let e=jo(u,o);e.length>0&&await Vt(e,`deleted-upstream`)}let p=dj({skillsRoot:d,name:i,relPath:o});if(!p.ok){let e=p.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:p.error.code,cause:Error(p.error.message)});return}p.existed&&a===`project`&&(An(l,kn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${R(c,u).split(B).join(`/`)}/${o}`}`),Un(`skill-file-delete`)),p.existed&&je?.(`files`),J(t,200,Gee,{path:o,existed:p.existed,kind:s},{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`}),Ro=q(See,async(e,t,n)=>{try{if(!Ca(n.name,t,`skill-file-rename`)||ao(n.name,t,`skill-file-rename`))return;let e=pO(n,ce);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=ko(r),o=ko(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 s=ka(n.scope,n.name);if(s===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let l=I(s),u=Ao(n.scope,a,r),d=Ao(n.scope,o,i),f=R(c,s).split(B).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&pa(p,`skill-file-rename`,t))return;if(p!==null)await Vt([p],`deleted-upstream`);else if(n.scope===`project`){let e=z(s,r);if(V(e)&&Ru(e).isDirectory()){let e=jo(s,r);e.length>0&&await Vt(e,`deleted-upstream`)}}let h=uj({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(k){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:H(z(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(z(l,n.name,i),`utf-8`)})}catch{}await yt(e,`skill-file-rename`)}n.scope===`project`&&(An(e,kn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),Un(`skill-file-rename`)),je?.(`files`),J(t,200,ote,{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 zo(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let Bo=BK;function Vo(e,t){return _D(z(e,t))?.contentHash}async function Ho(e,t){let n=w?.current;if(!(!n||!e))try{let r=wx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1187
- `).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 Un(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Uo=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Wo(e){try{let t=co(e.scope);if(!t)return;let n=UI(t);if(n.length===0)return;let r=YI(z(e.skillsRoot,e.name),e.name,t,n,`copy`,WI(e.scope));if(r.length===0)return;await IN(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 Go(e,t){if(t.ok){J(e,200,mee,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 Ko=Obe({contentDir:c,skillsHome:Ea,...M===void 0?{}:{projectDir:M},resolveSkillDirForRead:ka,parseFrontmatterDoc:ha,attributeOkArtifactWrite:An,commitOkArtifactWrite:Un,shadowHeadSha:Ho,artifactWriterId:Uo,effectiveInstallMode:za,signalFiles:()=>je?.(`files`)}),Jo=Nbe({contentDir:c,skillsHome:Ea,...M===void 0?{}:{projectDir:M},legacyStoreRoot:wi,effectiveSkillRoot:bo,parseFrontmatterDoc:ha,attributeOkArtifactWrite:An,commitOkArtifactWrite:Un,shadowHeadSha:Ho,artifactWriterId:Uo,skillArtifactKey:e=>kn(`skill`,``,e),captureAndCloseDocuments:Vt,projectImportedSkillCopy:Wo,signalFiles:()=>je?.(`files`)});function Yo(e,t){if(t.ok){J(e,200,tr,t.body,{handler:`skill-reimport`});return}K(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function Xo(e,t,n){let r=e===`project`?c:Ea,i=(e===`project`?vL(c):yL(Ea)).find(e=>e.name===t);return i?z(r,i.dir):z(n,t)}function Zo(e,t,n,r){let i=r.skills[t];if(i)return i;let a=Xo(e,t,n);return Bue(t,_D(a)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:Ibe(a)})??Ga(e===`global`?Ea:c,t)??$a(t,zd(M??c),a)}let Qo=q(ute,async(e,t,n)=>{let r=()=>{};try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);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 SD(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(kK(t,p,`skill-import`))return;let m=await oD(p);r=m.cleanup,s=m.ref;let h=vD(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=>hD(e.dir)?.name===f)??h.find(e=>e.name===Es[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??zo(d)}catch(e){if(e instanceof XE){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 Ko.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||bs(u))&&NI({source:u,skills:[d.body.name]},fI()),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),je?.(`files`),Go(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`}),$o=q(Jee,async(e,t,n)=>{let r=()=>{};try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);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 SD(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(kK(t,f,`skills-import-bulk`))return;if(l=e?.publisher??zo(d),f.kind===`well-known`)a=f,o=await nD(f.origin);else{let e=await oD(f);r=e.cleanup,c=e.ref,s=vD(e.dir)}}catch(e){if(e instanceof XE){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 oD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof XE?`not-found`:`failed`,warnings:[],...e instanceof XE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>_D(e.dir)?.name===t)??s.find(e=>e.name===Es[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Ko.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`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){F(`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||bs(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&NI({source:u,skills:e},fI())}Fn(),he?.refreshInPlaceSkillDirs(),Rn(),je?.(`files`),J(t,200,eee,{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`}),es=8*1024*1024,ts=32*1024*1024;function rs(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+B)?null:r}function is(e){return new Promise((t,n)=>{let r;try{r=DJ(e,{files:200,fields:10,fieldSize:2*1024,fileSize:es})}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>ts){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 as(e,t){return new Promise((n,r)=>{(0,qde.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=rs(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){sc(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>es){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>ts){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{sc(I(n),{recursive:!0}),gc(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 ss(e,t){let n=ku(L(Gu(),`ok-skill-upload-`)),r=()=>{try{dc(n,{recursive:!0,force:!0})}catch{}};try{if(!M){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=wa(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=pO({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},ce);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 is(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 as(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=rs(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}sc(I(r),{recursive:!0}),gc(r,e.data)}let u=vD(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];Go(t,await Ko.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 cs=q(pt,async(e,t,n)=>{try{let e=Oa(n.scope);if(!Ca(n.name,t,`skill-install`))return;if(n.scope===`project`&&!M){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=co(n.scope),i=z(e,n.name),a=n.scope===`project`?c:Ea,o=(n.scope===`project`?vL(c):yL(Ea)).find(e=>e.name===n.name),s=rO(n.name)?eo(n.name,n.scope):null,l=o?z(a,o.dir):V(i)||s===null?i:I(s);if(!V(l)){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 ut(n.scope===`project`?`${R(a,l).split(B).join(`/`)}/SKILL`:os(n.scope,n.name));let u=HI(l,n.name,{allowReservedName:rO(n.name)});if(!u.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${u.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=Da.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)}`)}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o.hosts.filter(oa),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let d=n.setSource??n.source,f=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),p=n.targets,m=[],h=[];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 Da.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}p=e.targets.filter(oa),m.push(...e.rootAdds),h.push(...e.rootRemoves)}if(d&&!o){let e=await Da.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:l,newSource:d});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}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?M:Ea;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 ir.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:l,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||je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?M:Ea;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 ir.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:l});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)}`)}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.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`?M:Ea,s=await ir.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:l,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)}`)}je?.(`files`),J(t,200,Cr,{name:n.name,hosts:[...o.hosts],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let g=n.scope===`global`?p===void 0?II(Ea).map(e=>e.editorId):Zee.filter(e=>p?.some(t=>t===e)):p===void 0?UI(r):Pr.filter(e=>p?.some(t=>t===e)),_=[],v=[];if(g.length===0&&p===void 0&&(_.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`."),v.push(`no-targets`)),u.hasScripts&&(_.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."),v.push(`scripts-present`)),u.warnings.length>0&&(_.push(u.warnings[0]),v.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(p===void 0?n.scope===`global`&&V(L(Ea,`.agents`)):p.includes(`agents`))?[...g,`agents`]:[...g],a=n.scope===`project`?M:Ea,s=f===void 0?za(n.scope,n.name,o):f?`link`:`copy`;if(d){let e=await Da.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:l,inPlaceEntry:o,newSource:d});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}je?.(`files`),J(t,200,Cr,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let c=await Da.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:l,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:p!==void 0,installMode:s,...f===void 0?{}:{linkModeReq:f},rootAdds:m,rootRemoves:h});if(!c.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:c.reason});return}_.push(...c.warnings),v.push(...c.warningCodes),je?.(`files`),J(t,200,Cr,{name:n.name,hosts:c.hosts,scripts:u.hasScripts,warnings:_,warningCodes:v,...c.sourceMovedTo===void 0?{}:{sourceMovedTo:c.sourceMovedTo}},{handler:`skill-install`});return}let y=BI(PN(r).skills[n.name]?.hosts??[]).filter(e=>!g.includes(e));y.length>0&&rL(n.name,r,y,WI(n.scope));let b=L(r,...sD),x=V(b)?H(b,`utf-8`):null,S=x===null?null:lD(x);x!==null&&S===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let C=S?.skills[n.name]!==void 0,w=f===void 0?C?`copy`:`symlink`:f?`symlink`:`copy`,T=YI(l,n.name,r,g,w,WI(n.scope));T.length===0?await LN(r,n.name):await IN(r,n.name,{hosts:T,scope:n.scope,scripts:u.hasScripts,installedAt:new Date().toISOString(),projection:w}),je?.(`files`),J(t,200,Cr,{name:n.name,hosts:T,scripts:u.hasScripts,warnings:_,warningCodes:v},{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`}),ls=q(Gt,async(e,t,n)=>{try{if(!Ca(n.name,t,`skill-uninstall`))return;let e=co(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 lo(e,n.name,n.scope);je?.(`files`),J(t,200,nee,{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`}),us=q(Lt,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Ca(n.name,t,`skill-restore`)||ao(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=w?.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 _X({shadow:r,contentDir:c,contentRoot:te??`.`,name:n.name,version:n.version,skillDirRel:Va(n.name)});if(!i.ok){Ia(t,i,`skill-restore`);return}let a=[],o=HI(z(c,Va(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),An(e,kn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Un(`skill-restore`),je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,on,{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`}),ds=q(Hn,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Ca(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Ea:c,{root:a,dirRel:o,realDir:s}=bo(n.scope,n.name);if(s===null||!V(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let l=L(n.scope===`global`?Ea:M,...sD),u=Zo(n.scope,n.name,a,Bo(l));if(!u){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 HK(l,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,tr,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null;try{let e=u.skill??n.name,i=Es[e],a=await SD(u.source,e).catch(async e=>{if(i===void 0)throw e;return SD(u.source,i)}),o=a?.source??WD(u.source,u.pluginProvider),s=a?.skill??u.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:u.source});return}if(kK(t,c,`skill-reimport`))return;let l=await oD(c);r=l.cleanup,d=l.ref;let p=vD(l.dir),m=mX(p,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>_D(e)?.name});if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:p.map(e=>e.name).join(`, `)});return}f=m.dir}catch(e){if(e instanceof XE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let p=await Jo.runSkillReimport({acquiredDir:f,name:n.name,scope:n.scope,entry:u,lockPath:l,ref:d,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});Fn(),he?.refreshInPlaceSkillDirs(),Rn(),Yo(t,p)}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`}),fs=q(Xr,async(e,t,n)=>{try{if(n.scope===`project`&&!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let r=pO(n,ce);if(r.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let i=L(n.scope===`global`?Ea:M,...sD),a=Bo(i),o=[],{bySource:s,unrecorded:c}=Mbe([...new Set(n.names)].filter(e=>Sa(e)?!0:(o.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`}),!1)),e=>Zo(n.scope,e,bo(n.scope,e).root,a));for(let e of c)o.push({requested:e,status:`not-found`,warnings:[]});for(let t of s){let s=()=>{};try{let c,l=[];try{let e=t.names[0],n=await SD(t.source,e).catch(async n=>{let r=Es[e];if(r===void 0)throw n;return SD(t.source,r)}),r=n?.source??WD(t.source,a.skills[t.names[0]]?.pluginProvider),i=n?.spec??iD(r);if(!i||OK(i)){for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:`INVALID_SOURCE`});continue}let u=await oD(i);s=u.cleanup,c=u.ref,l=vD(u.dir)}catch(n){F(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:xS(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)});continue}for(let s of t.names){let t=Zo(n.scope,s,bo(n.scope,s).root,a);if(!t){o.push({requested:s,status:`not-found`,warnings:[]});continue}let u=mX(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:s,frontmatterNameOf:e=>_D(e)?.name});if(!u){o.push({requested:s,status:`not-found`,source:t.source,warnings:[]});continue}try{let a=await Jo.runSkillReimport({acquiredDir:u.dir,name:s,scope:n.scope,entry:t,lockPath:i,ref:c,actor:r});if(!a.ok){F(`skills-reimport-bulk`).warn({skill:s,err:a.cause,detail:a.detail,requestId:xS(e)},`bulk update: one skill failed (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:a.detail??a.title});continue}o.push({requested:s,status:a.body.updated?`updated`:`up-to-date`,source:a.body.source,warnings:a.body.warnings})}catch(n){F(`skills-reimport-bulk`).warn({skill:s,err:n,requestId:xS(e)},`bulk update: one skill threw (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)})}}}finally{s()}}J(t,200,bee,{results:o,updated:o.filter(e=>e.status===`updated`).length,upToDate:o.filter(e=>e.status===`up-to-date`).length,failed:o.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{Fn(),he?.refreshInPlaceSkillDirs(),Fn(),await he?.rebuildIgnorePatterns()}catch(e){F(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),ps=q(iee,async(e,t,n)=>{try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Ca(n.name,t,`skill-revert`)||ao(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=L(M,...sD),i=Bo(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=w?.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 _X({shadow:a,contentDir:c,contentRoot:te??`.`,name:n.name,version:i.baselineRef,skillDirRel:Va(n.name)});if(!o.ok){Ia(t,o,`skill-revert`);return}An(e,kn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Un(`skill-revert`);let s=z(c,Va(n.name),`..`),l=Vo(s,n.name);await HK(r,e=>uD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),s===Oa(`project`)&&await Wo({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),je?.(`files`),J(t,200,lee,{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`}),ms=Ebe({contentDir:c,projectDir:M,getAllFilesIndex:m,getFileIndexGeneration:g,getSearchMaxEntries:Wbe,semanticSearch:N,getSemanticSimilarityFloor:Se,ready:ve,getProjectSkillsRoot:()=>Oa(`project`),parseFrontmatterDoc:ha});ms.prewarm();async function vs(e,t){if(r(e,t,{handler:`handoff`}))try{await Kpe(e,t,{contentDir:c,platform:process.platform,isSchemeRegistered:P.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:xS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function xs(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await gN(e,t,{contentDir:c,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:xS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Cs=q(en,async(e,t,n)=>{try{if(!M){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!She(e,n.kind)){BF(`invalid-path`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`invalid-path`},{handler:RF});return}let r=Ehe(M);if(r===null){if(XF(M).kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}BF(`detached-head`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`detached-head`},{handler:RF});return}let i=XF(M);if(i.kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}if(i.kind===`non-github`){BF(`non-github-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`non-github-remote`},{handler:RF});return}if(!Fhe(M,r)){BF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,Mr,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:RF});return}let a=eZ(M,c);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=a===``?e:e===``?a:`${a}/${e}`,s;s=n.kind===`doc`?Che(i.host,i.owner,i.repo,r,o):zF(i.host,i.owner,i.repo,r,o);let l;try{let e=a===``?0:li(zF(i.host,i.owner,i.repo,r,a)).targetSegments.length;l=`https://openknowledge.ai/d/${yee(s,e)}`}catch(e){if(!(e instanceof ti))throw e;BF(`unsupported-share-url`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`unsupported-share-url`},{handler:RF});return}let u=await whe(M,r,o,n.kind);BF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,Mr,{ok:!0,shareUrl:l,sharedUrl:s,branch:r,freshness:u},{handler:RF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:RF,cause:e})}},{handler:RF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:RF})}),ws=q(Gr,async(e,t)=>{try{if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Qz});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(!Fee(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Qz});return}if(!Xz(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Qz});return}J(t,200,uee,await Zz(M,r,i,a),{handler:Qz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Qz,cause:e})}},{handler:Qz,method:`GET`,skipBodyParse:!0});function Ts(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let Ds=q(ai,async(e,t,n)=>{try{if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lI});return}if(!Xz(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:lI});return}let e=await Uhe(M,n.branch,n.path,n.kind,{credentialConfig:Dc(ae,{resetAmbient:QF(M)})});J(t,200,Zr,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:Ts(n.path,e.renamedTo,n.contentRootDepth),{handler:lI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lI,cause:e})}},{handler:lI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:lI})}),Os=q(hte,async(e,t,n)=>{if(pO(n,ce).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:rB});return}if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:rB});return}try{J(t,200,at,await Tc(()=>aB(M,n.branch,{fastForward:n.fastForward===!0,credentialConfig:Dc(ae,{resetAmbient:QF(M)})})),{handler:rB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:rB,cause:e})}},{handler:rB,method:`POST`});async function ks(e){let[t,...n]=ae,r=[...n,...e];return await new Promise((e,n)=>{let i=lu(t,r,Dw({...Fr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},nI),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 ${nI}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=cI(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 As=q(Gr,async(e,t)=>{if(!Me.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:$F,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ks([`share`,`owners`,`--json`]),n=Ihe(aI(e));sI(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,ree,n,{handler:$F})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:$F,cause:e})}finally{Me.release(`/api/share/publish/owners`)}},{handler:$F,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:$F})}),Ms=q(Gr,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!iI(r)||!rI(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:eI});return}if(!Me.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:eI,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ks([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Lhe(aI(e));sI(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Kt,n,{handler:eI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:eI,cause:e})}finally{Me.release(`/api/share/publish/name-check`)}},{handler:eI,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:eI})}),Ns=q(Yee,async(e,t,n)=>{if(!M){sI(`publish-create`,`no-project`),J(t,200,pn,{ok:!1,error:`no-project`},{handler:tI});return}if(!iI(n.owner)||!rI(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:tI});return}if(!Me.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:tI,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,M,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await ks(e),i=Bhe(aI(r));sI(`publish-create`,i.ok?`ok`:i.error),i.ok&&j?.()?.refreshRemote().catch(()=>{}),J(t,200,pn,i,{handler:tI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:tI,cause:e})}finally{Me.release(`/api/share/publish`)}},{handler:tI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:tI})}),Ps=q($ee,async(e,t,n)=>{try{let e=F(`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,Eee,{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`})}),Fs=`local-op-embeddings-set-key`,Is=`local-op-embeddings-clear-key`,Ls=`/api/local-op/embeddings`;function Rs(){let e=we?.();return{projectDir:M??c,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let zs=q(bt,async(e,t,n)=>{if(!Me.tryAcquire(Ls)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Fs,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Rs();await new pM(Ce).setForProject(e,r,n.key),N?.reloadCredential(),J(t,200,Ot,{keyPresent:!0},{handler:Fs,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Fs,cause:e})}finally{Me.release(Ls)}},{handler:Fs,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Fs})}),Bs=q(Gr,async(e,t)=>{if(!Me.tryAcquire(Ls)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Is,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Rs();await new pM(Ce).clearForProject(e,n),N?.reloadCredential(),J(t,200,Ot,{keyPresent:!1},{handler:Is,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Is,cause:e})}finally{Me.release(Ls)}},{handler:Is,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Is})}),Vs=`local-op-embeddings-test`,Hs=`/api/local-op/embeddings/test`,Ws=q(Gr,async(e,t)=>{if(!Me.tryAcquire(Hs)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Vs,extraHeaders:{"Retry-After":`5`}});return}try{let e=we?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await oM(new pM(Ce),M??c,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Ufe({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,aee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Vs,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Vs,cause:e})}finally{Me.release(Hs)}},{handler:Vs,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Vs})}),Gs=0;function Ks(){Gs+=1,je?.(`lint-config`)}let qs=()=>`${Gs} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function Js(e,t){let n=Te?.()??Lo;try{let r=await _a(e,iF(c,n,{docName:t,projectDir:M??c,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ee?.()??`warning`;if(k&&a!==`off`&&!hS(t)){await wt(t,e,`lint-validation`);let r=PF({projectDir:M??c,contentDir:c,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:vt,docFilePathFor:e=>ZX(c,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:ZX(c,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}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Xs(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=sF({projectDir:M??c,contentDir:c});return DP(t.schemas,n)}let Zs=q(Sn,async(e,t,n)=>{let r;try{r=_F(z(c),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}Ks();try{let e=Te?.()??Lo,n=[],r=tF(c,void 0,e=>n.push(e)),i=rF(M??c,nF(e,r),e=>n.push(e));n.push(...Xs(i)),J(t,200,zn,{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`}),Qs=q(Je,async(e,t,n)=>{let r;try{let e=z(M??c),t=n.parentPath??[];r=n.delete?Gme(e,n.file):n.field!==void 0&&n.removeField?Ume(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Wme(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Vme(e,n.file,n.field,n.constraint,t):Hme(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`)&&je?.(`files`),Ks();try{let e=Te?.()??Lo,n=[],r=tF(c,void 0,e=>n.push(e)),i=rF(M??c,nF(e,r),e=>n.push(e));n.push(...Xs(i)),J(t,200,zn,{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`}),$s=q(Ft,async(t,n,r)=>{try{let t=WX(r.docName,n,`lint-fix`);if(t===null)return;let i=nt(t),a=pO(r,ce);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(cS(i)||lS(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=ZX(c,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}sN(z(c,f),c);let p=Te?.()??Lo,{stored:m}=wn(a.summary),h=await s.getSession(i,o,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),_=[],{cfg:v,before:y,fixed:b,ran:x,failures:S}=await Rme({projectDir:M??c,contentDir:c,baseConfig:p,docRelPath:f,source:g,onConfigProblem:e=>_.push(e)}),C=y,w,T=[];if(b!==g){try{let t=hs(d),n=hi[t]??Ss(u??o);re?.setPresence(o,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{gw(h.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,mw(h))},h.origin),a.kind!==`anonymous`&&Hj(i,o,l,u,void 0,a.kind===`agent`?Cn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{re?.touchMode(o,`idle`)}let t=await ut(i);if(t?.kind===`failure`){dt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){mt(n,`lint-fix`);return}lt(i,`lint-fix`);try{C=await _a(h.dc.document.getText(`source`).toString(),v,f,e=>T.push(e))}catch(e){w=`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`),C=y}}let E=C.filter(e=>e.severity===`error`).length,D=C.length-E,O=Math.max(0,y.length-C.length),ee=[..._,...gs([...S,...T]),...w?[w]:[]];J(n,200,rn,{file:f,fixedCount:O,diagnostics:C,errorCount:E,warningCount:D,ran:x,...ee.length>0?{warnings:ee}:{},...w?{warning:w}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof QM){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof kS){AS(n,e,`lint-fix`);return}if(e instanceof PS){LS(n,e,`lint-fix`);return}if(e instanceof Cw){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`}),ec=bfe({service:Ue,getPrincipal:ce,onChanged:()=>je?.(`comments`)}),tc={"/api/comments":fK({GET:ec.list,POST:ec.create},{handler:`comments`}),"/api/comment":fK({GET:ec.read,POST:ec.mutate,DELETE:ec.remove},{handler:`comment`}),"/api/asset":dr,"/api/asset-text":pr,"/api/folder-config":la,"/api/template":ba,"/api/template/import":xa,"/api/skill":Oo,"/api/skill-file":Io,"/api/skill-file/rename":Ro,"/api/skills":ho,"/api/skill/import":Qo,"/api/skills/import-bulk":$o,"/api/skill/edit-external":wo,"/api/skill/duplicate":Do,"/api/skill/move-scope":Eo,"/api/skill-upload":ss,"/api/skill/install":cs,"/api/skill/uninstall":ls,"/api/skill/restore":us,"/api/skill/reimport":ds,"/api/skills/reimport-bulk":fs,"/api/skill/revert":ps,"/api/skill/track-in-git":po,"/api/lint/markdownlint-config":Zs,"/api/lint/frontmatter-schema":Qs,"/api/lint/fix":$s,"/api/create-page":mr,"/api/create-folder":gr,"/api/duplicate-path":_r,"/api/rename-path":vr,"/api/delete-path":yr,"/api/trash/cleanup":xr,"/api/upload":wr,"/api/agent-write":Wn,"/api/agent-write-md":Gn,"/api/agent-write-batch":Kn,"/api/frontmatter-patch":qn,"/api/agent-patch":Jn,"/api/agent-undo":Yn,"/api/agent-activity":Xn,"/api/agent-burst-diff":Zn,"/api/save-version":ar,"/api/rollback":or,"/api/share/construct-url":Cs,"/api/share/target-status":Ds,"/api/git/branch-info":ws,"/api/git/worktree-status":Ui,"/api/git/checkout":Os,"/api/share/publish/owners":As,"/api/share/publish/name-check":Ms,"/api/share/publish":Ns,"/api/sync/status":Bi,"/api/sync/trigger":Wi,"/api/sync/conflicts":Yi,"/api/sync/conflict-content":Zi,"/api/sync/resolve-conflict":Xi,"/api/sync/resolve-blocking":Ki,"/api/local-op/clone":Rr,"/api/local-op/ok-init":Wr,"/api/local-op/auth/login":_i,"/api/local-op/auth/status":Ei,"/api/local-op/auth/pat":Oi,"/api/local-op/auth/gh-login":xi,"/api/local-op/auth/cancel":Ci,"/api/local-op/auth/repos":Ai,"/api/local-op/auth/signout":Ii,"/api/local-op/auth/set-identity":zi,"/api/local-op/embeddings/set-key":zs,"/api/local-op/embeddings/clear-key":Bs,"/api/local-op/embeddings/test":Ws,"/api/spawn-cursor":xs,"/api/handoff":vs,"/api/install-skill":na,"/api/seed/plan":Qi,"/api/seed/apply":$i,"/api/seed/install-pack-skill":ea,"/api/seed/packs":ta,"/api/client-logs":Ps};C&&(tc[`/api/test-reset`]=$n,tc[`/api/test-flush-git`]=Qn,tc[`/api/test-rescan-backlinks`]=er,tc[`/api/test-rescan-files`]=nr);let rc=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/sync/resolve-blocking./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/skills/reimport-bulk./api/skill/revert./api/skill/track-in-git./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),ic=[`/api/local-op/`],ac=qB({log:X,policy:n,ephemeral:De,table:{resolve(e){let t=tc[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>rc.has(e)||ic.some(t=>e.startsWith(t))}}),oc=[sK({hocuspocus:o,derivedDocumentIndex:k,getFileIndex:f,isSafeDocName:cZ,readPageTitleForDocName:We,readPageTitleForLinkedDocName:Ke,readFrontmatterMetadataForLinkedDocName:$e,collectAdmittedDocNames:vt,resolveAlias:nt,respondToDerivedIndexQueryFailure:Dt}),pK({hocuspocus:o,agentPresenceBroadcaster:re,isAllowedWorkspaceHostHeader:i,log:X}),Ne,rV({contentDir:c,projectDir:M,ephemeral:De,log:X,ready:ve,durabilityState:t,serverInstanceId:d,getDiskAckSVs:O,getCollabClientCount:ee,getConfigDiagnostics:Ae,acpRegistry:fe,loadAcpCustomAgents:pe,acpHarnessAvailability:me,isRoutePeerAdmitted:a,isAllowedWorkspaceHostHeader:i,checkLocalOpSecurity:r,getPrincipal:ce,semanticSearch:N,readSemanticProviderConfig:we,embeddingsSecretsFile:Ce,getFileIndex:f,shadowRef:w,getCurrentBranch:D,installedAgentsCache:P}),cK({hocuspocus:o,contentDir:c,projectDir:M,contentFilter:he,isSafeDocName:cZ,resolveDocFilePath:ZX,isValidRelativeContentPath:HX,streamShowAllEntries:VX,getLinterBaseConfig:Te,getLinksValidationSetting:Ee,derivedDocumentIndex:k,collectAdmittedDocNames:vt,unmatchedGlobProblems:Xs,readAuditGeneration:qs}),$H({contentRoot:te,log:X,shadowRef:w,flushGitCommit:T,commitOkArtifactWrite:Un,getCurrentBranch:D,validateFolderRel:ra,safeDocPath:MX,docTreePathCandidates:NX}),mK({contentDir:c,projectDir:M,homeDirOverride:le,skillsHome:Ea,isSafeDocName:cZ,commentService:Ue,enumerateInstalledSkillsCached:In,checkLocalOpSecurity:r}),WK({log:X,skillsHome:Ea,projectDir:M,contentDir:c,resolveSkillDirForRead:ka}),V_e({contentDir:c,projectDir:M,skillsHome:Ea,homeDirOverride:le,savedThemeLockTimeoutMs:ue,ephemeral:De,log:X,signalChannel:je,searchService:ms,linkPreviewFetch:Oe,getLinkPreviewsEnabled:ke,getGeneratedIndexSettingsStatus:l,setGeneratedIndexEnabled:u})],cc=oc.flatMap(e=>[...e.paths]);PG(cc,tc);let fc=oc.map(e=>qB({log:X,policy:n,ephemeral:De,table:e.table})),pc={paths:cc,dispatch:async(e,t)=>{for(let n of fc)if(await n(e,t))return!0;return!1}},hc=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]),_c=oc.map(e=>e.table),vc=e=>{for(let t of _c){let n=t.resolve(e)?.dispatch;if(n!==void 0)return n}};for(let e of hc)if(tc[e]===void 0&&vc(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await ac(e,t)},nativeApi:pc,localApi:dK({resolve:e=>{if(!hc.has(e))return;let t=tc[e];return t===void 0?vc(e):t}})}}function uZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=mu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!IB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!RB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:jB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=nX(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=De.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function dZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function axe(e){let t;try{t=Nu(e.contentDir,{withFileTypes:!0})}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Yx(n.name,ve)&&e.basenameIndex.add(n.name)}async function fZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Xu(i,{withFileTypes:!0})}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=rN(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Ju(a)}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Zu(a)}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!iN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Qu(i)}catch(t){let n=dZ(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()&&Yx(a,de)&&!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()&&Yx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const pZ=P({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:O().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),mZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function hZ(e){return mZ.includes(e)}function gZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function oxe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!hZ(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 _Z=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=gZ(e,this.payload)}};function vZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=pZ.safeParse(t);return n.success?n.data:void 0}var yZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function bZ(e,t,n=``){e=ene(`.`,e);let r=Qte(e),i=0,a,o;for(;i<r.length;i++)a=ad(e,r[i]),o=$te(a),o.isDirectory()?bZ(a,t,ad(n,r[i])):t(ad(n,r[i]),a,o)}function sxe(e){let t=e.url;if(t==null)return;let n=e._parsedUrl;if(n&&n.raw===t)return n;let r=t,i=``,a,o;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(o=t.substring(e),r=t.substring(0,e)),e=r.indexOf(`?`,1),e!==-1&&(i=r.substring(e),r=r.substring(0,e),i.length>1&&(a=fne.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const cxe=()=>{};function lxe(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function xZ(e,t){let n=0,r,i=e.length-1;e.charCodeAt(i)===47&&(e=e.substring(0,i));let a=[],o=`${e}/index`;for(;n<t.length;n++)r=t[n]?`.${t[n]}`:``,e&&a.push(e+r),a.push(o+r);return a}function uxe(e,t,n){let r=0,i,a=xZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function dxe(e,t,n,r){let i=0,a=xZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=gu(L(e,c=a[i])),o.startsWith(e)&&xu.existsSync(o)){if(s=xu.statSync(o),s.isDirectory())continue;return l=SZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function fxe(e,t){return t.statusCode=404,t.end()}function pxe(e,t,n,r,i){let a=200,o,s={};i={...i};for(let e in i)o=t.getHeader(e),o&&(i[e]=o);if((o=t.getHeader(`content-type`))&&(i[`Content-Type`]=o),e.headers.range){a=206;let[n,o]=e.headers.range.replace(`bytes=`,``).split(`-`),c=s.end=parseInt(o,10)||r.size-1,l=s.start=parseInt(n,10)||0;if(c>=r.size&&(c=r.size-1),l>=r.size)return t.setHeader(`Content-Range`,`bytes */${r.size}`),t.statusCode=416,t.end();i[`Content-Range`]=`bytes ${l}-${c}/${r.size}`,i[`Content-Length`]=c-l+1,i[`Accept-Ranges`]=`bytes`}t.writeHead(a,i),xu.createReadStream(n,s).pipe(t)}const mxe={".br":`br`,".gz":`gzip`};function SZ(e,t,n){let r=mxe[e.slice(-3)],i=pbe(e.slice(0,r&&-3))||``;i===`text/html`&&(i+=`;charset=utf-8`);let a={"Content-Length":t.size,"Content-Type":i,"Last-Modified":t.mtime.toUTCString()};return r&&(a[`Content-Encoding`]=r),n&&(a.ETag=`W/"${t.size}-${t.mtime.getTime()}"`),a}function CZ(e,t={}){e=z(e||`.`);let n=t.onNoMatch||fxe,r=t.setHeaders||cxe,i=t.extensions||[`html`,`htm`],a=t.gzip&&i.map(e=>`${e}.gz`).concat(`gz`),o=t.brotli&&i.map(e=>`${e}.br`).concat(`br`),s={},c=`/`,l=!!t.etag,u=!!t.single;if(typeof t.single==`string`){let e=t.single.lastIndexOf(`.`);c+=~e?t.single.substring(0,e):t.single}let d=[];t.ignores!==!1&&(d.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),t.dotfiles?d.push(/\/\.\w/):d.push(/\/\.well-known/),[].concat(t.ignores||[]).forEach(e=>{d.push(new RegExp(e,`i`))}));let f=t.maxAge!=null&&`public,max-age=${t.maxAge}`;f&&t.immutable?f+=`,immutable`:f&&t.maxAge===0&&(f+=`,must-revalidate`),t.dev||bZ(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=SZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?dxe.bind(0,e+B,l):uxe.bind(0,s);return function(e,t,s){let f=[``],m=sxe(e).pathname,h=e.headers[`accept-encoding`]||``;if(a&&h.includes(`gzip`)&&f.unshift(...a),o&&/(br|brotli)/i.test(h)&&f.unshift(...o),f.push(...i),m.indexOf(`%`)!==-1)try{m=decodeURI(m)}catch{}let g=p(m,f)||u&&!lxe(m,d)&&p(c,f);if(!g)return s?s():n(e,t);if(l&&e.headers[`if-none-match`]===g.headers.ETag)return t.writeHead(304),t.end();(a||o)&&t.setHeader(`Vary`,`Accept-Encoding`),r(t,m,g.stats),pxe(e,t,g.abs,g.stats,g.headers)}}const wZ=F(`conflict-storage`);var TZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(KO(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){wZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){wZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);V(e)||Ou(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Bu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return wZ.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){let r=this.conflicts.find(t=>t.file===e);if(!r)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-DfQBBy3_.mjs`),a=i(this.projectDir,{credentialConfig:[]});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!iN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);SL(r,t,{allowShareableOkArtifact:rP}),gc(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),wZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Xb(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){wZ.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}),wZ.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){let r=z(this.projectDir),i=z(r,e.file);if(!iN(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(SL(i,r,{allowShareableOkArtifact:rP}),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-DfQBBy3_.mjs`),n=await t(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,e.theirsSha]);SL(i,r,{allowShareableOkArtifact:rP}),gc(i,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);gc(i,n,`utf-8`);break;case`delete`:V(i)&&nc(i);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function hxe(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 gxe(e,t){let n=KO(e);try{Ou(n,{recursive:!0}),Bu(L(n,Ce),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=vte(e);Ou(I(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`};Bu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const EZ=new Map;let DZ=!1;function _xe(e,t){try{let n=hxe(e,t);for(let e of EZ.keys())gxe(e,n)}catch{}}function vxe(e){EZ.set(e,(EZ.get(e)??0)+1),DZ||(DZ=!0,process.on(`uncaughtExceptionMonitor`,_xe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=EZ.get(e)??0;n<=1?EZ.delete(e):EZ.set(e,n-1)}}}function OZ(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function kZ(e){let t=e.scheduler??ba,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!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 l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??OZ(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function AZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jZ(e){if(!V(e))return{};let t;try{t=(0,ZD.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(!AZ(t))return{};let n=t.telemetry;if(!AZ(n))return{};let r=n.localSink;return AZ(r)?r:{}}function MZ(e){return typeof e==`boolean`?e:void 0}function yxe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function NZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function PZ(e){if(AZ(e))return yxe(e.maxBytes)}function bxe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=jZ(Vs(`project`,e.projectDir)),n=jZ(Vs(`project-local`,e.projectDir));if((MZ(n.enabled)??MZ(t.enabled)??!0)===!1)return null;let r=PZ(n.spans)??PZ(t.spans)??52428800,i=PZ(n.logs)??PZ(t.logs)??26214400,a=NZ(n.attributeDenylist)??NZ(t.attributeDenylist)??h;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var FZ;(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})(FZ||={});var xxe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xxe||={});const IZ=FZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),LZ=e=>{switch(typeof e){case`undefined`:return IZ.undefined;case`string`:return IZ.string;case`number`:return Number.isNaN(e)?IZ.nan:IZ.number;case`boolean`:return IZ.boolean;case`function`:return IZ.function;case`bigint`:return IZ.bigint;case`symbol`:return IZ.symbol;case`object`:return Array.isArray(e)?IZ.array:e===null?IZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?IZ.promise:typeof Map<`u`&&e instanceof Map?IZ.map:typeof Set<`u`&&e instanceof Set?IZ.set:typeof Date<`u`&&e instanceof Date?IZ.date:IZ.object;default:return IZ.unknown}},Z=FZ.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 RZ=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,FZ.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()}};RZ.create=e=>new RZ(e);const zZ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===IZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,FZ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${FZ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${FZ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${FZ.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}"`:FZ.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,FZ.assertNever(e)}return{message:n}};let Sxe=zZ;function BZ(){return Sxe}const VZ=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 HZ(e,t){let n=BZ(),r=VZ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===zZ?void 0:zZ].filter(e=>!!e)});e.common.issues.push(r)}var UZ=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 WZ;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 WZ;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 WZ=Object.freeze({status:`aborted`}),GZ=e=>({status:`dirty`,value:e}),KZ=e=>({status:`valid`,value:e}),qZ=e=>e.status===`aborted`,JZ=e=>e.status===`dirty`,YZ=e=>e.status===`valid`,XZ=e=>typeof Promise<`u`&&e instanceof Promise;var ZZ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(ZZ||={});var QZ=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 $Z=(e,t)=>{if(YZ(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 RZ(e.common.issues);return this._error=t,this._error}}};function eQ(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 tQ=class{get description(){return this._def.description}_getType(e){return LZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:LZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new UZ,ctx:{common:e.parent.common,data:e.data,parsedType:LZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(XZ(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:LZ(e)};return $Z(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:LZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return YZ(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=>YZ(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:LZ(e)},r=this._parse({data:e,path:n.path,parent:n});return $Z(n,await(XZ(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 NQ({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 PQ.create(this,this._def)}nullable(){return FQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _Q.create(this)}promise(){return MQ.create(this,this._def)}or(e){return bQ.create([this,e],this._def)}and(e){return CQ.create(this,e,this._def)}transform(e){return new NQ({...eQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new IQ({...eQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new zQ({typeName:Q.ZodBranded,type:this,...eQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new LQ({...eQ(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 BQ.create(this,e)}readonly(){return VQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Cxe=/^c[^\s-]{8,}$/i,wxe=/^[0-9a-z]+$/,Txe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Exe=/^[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,Dxe=/^[a-z0-9_-]{21}$/i,Oxe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kxe=/^[-+]?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)?)??$/,Axe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let nQ;const jxe=/^(?:(?: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])$/,Mxe=/^(?:(?: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])$/,Nxe=/^(([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]))$/,Pxe=/^(([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])$/,Fxe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ixe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rQ=`((\\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])))`,Lxe=RegExp(`^${rQ}$`);function iQ(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 Rxe(e){return RegExp(`^${iQ(e)}$`)}function zxe(e){let t=`${rQ}T${iQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Bxe(e,t){return!!((t===`v4`||!t)&&jxe.test(e)||(t===`v6`||!t)&&Nxe.test(e))}function Vxe(e,t){if(!Oxe.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 Hxe(e,t){return!!((t===`v4`||!t)&&Mxe.test(e)||(t===`v6`||!t)&&Pxe.test(e))}var aQ=class e extends tQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==IZ.string){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.string,received:t.parsedType}),WZ}let t=new UZ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),HZ(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),HZ(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?HZ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&HZ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Axe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)nQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),nQ.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Exe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Dxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Cxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)wxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Txe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(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),HZ(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),HZ(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),HZ(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),HZ(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),HZ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?zxe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Lxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Rxe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?kxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Bxe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Vxe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Hxe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Fxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ixe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):FZ.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,...ZZ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...ZZ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...ZZ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...ZZ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...ZZ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...ZZ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...ZZ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...ZZ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...ZZ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...ZZ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...ZZ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...ZZ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...ZZ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...ZZ.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,...ZZ.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,...ZZ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...ZZ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...ZZ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...ZZ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...ZZ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...ZZ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...ZZ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...ZZ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...ZZ.errToObj(t)})}nonempty(e){return this.min(1,ZZ.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}};aQ.create=e=>new aQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...eQ(e)});function Uxe(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 oQ=class e extends tQ{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)!==IZ.number){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.number,received:t.parsedType}),WZ}let t,n=new UZ;for(let r of this._def.checks)r.kind===`int`?FZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),HZ(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),HZ(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),HZ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Uxe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),HZ(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),HZ(t,{code:Z.not_finite,message:r.message}),n.dirty()):FZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,ZZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,ZZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,ZZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,ZZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ZZ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:ZZ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:ZZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:ZZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:ZZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:ZZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:ZZ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:ZZ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:ZZ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:ZZ.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`&&FZ.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)}};oQ.create=e=>new oQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...eQ(e)});var sQ=class e extends tQ{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)!==IZ.bigint)return this._getInvalidInput(e);let t,n=new UZ;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),HZ(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),HZ(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),HZ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):FZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.bigint,received:t.parsedType}),WZ}gte(e,t){return this.setLimit(`min`,e,!0,ZZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,ZZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,ZZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,ZZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ZZ.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:ZZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:ZZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:ZZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:ZZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:ZZ.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}};sQ.create=e=>new sQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...eQ(e)});var cQ=class extends tQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==IZ.boolean){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.boolean,received:t.parsedType}),WZ}return KZ(e.data)}};cQ.create=e=>new cQ({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...eQ(e)});var lQ=class e extends tQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==IZ.date){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.date,received:t.parsedType}),WZ}if(Number.isNaN(e.data.getTime()))return HZ(this._getOrReturnCtx(e),{code:Z.invalid_date}),WZ;let t=new UZ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),HZ(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),HZ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):FZ.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:ZZ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:ZZ.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)}};lQ.create=e=>new lQ({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...eQ(e)});var uQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.symbol){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.symbol,received:t.parsedType}),WZ}return KZ(e.data)}};uQ.create=e=>new uQ({typeName:Q.ZodSymbol,...eQ(e)});var dQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.undefined){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.undefined,received:t.parsedType}),WZ}return KZ(e.data)}};dQ.create=e=>new dQ({typeName:Q.ZodUndefined,...eQ(e)});var fQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.null){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.null,received:t.parsedType}),WZ}return KZ(e.data)}};fQ.create=e=>new fQ({typeName:Q.ZodNull,...eQ(e)});var pQ=class extends tQ{constructor(){super(...arguments),this._any=!0}_parse(e){return KZ(e.data)}};pQ.create=e=>new pQ({typeName:Q.ZodAny,...eQ(e)});var mQ=class extends tQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return KZ(e.data)}};mQ.create=e=>new mQ({typeName:Q.ZodUnknown,...eQ(e)});var hQ=class extends tQ{_parse(e){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.never,received:t.parsedType}),WZ}};hQ.create=e=>new hQ({typeName:Q.ZodNever,...eQ(e)});var gQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.undefined){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.void,received:t.parsedType}),WZ}return KZ(e.data)}};gQ.create=e=>new gQ({typeName:Q.ZodVoid,...eQ(e)});var _Q=class e extends tQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==IZ.array)return HZ(t,{code:Z.invalid_type,expected:IZ.array,received:t.parsedType}),WZ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(HZ(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&&(HZ(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&&(HZ(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 QZ(t,e,t.path,n)))).then(e=>UZ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new QZ(t,e,t.path,n)));return UZ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:ZZ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:ZZ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:ZZ.toString(n)}})}nonempty(e){return this.min(1,e)}};_Q.create=(e,t)=>new _Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...eQ(t)});function vQ(e){if(e instanceof yQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=PQ.create(vQ(r))}return new yQ({...e._def,shape:()=>t})}else if(e instanceof _Q)return new _Q({...e._def,type:vQ(e.element)});else if(e instanceof PQ)return PQ.create(vQ(e.unwrap()));else if(e instanceof FQ)return FQ.create(vQ(e.unwrap()));else if(e instanceof wQ)return wQ.create(e.items.map(e=>vQ(e)));else return e}var yQ=class e extends tQ{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=FZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==IZ.object){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.object,received:t.parsedType}),WZ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hQ&&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 QZ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof hQ){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&&(HZ(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 QZ(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=>UZ.mergeObjectSync(t,e)):UZ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return ZZ.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:ZZ.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 FZ.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 FZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return vQ(this)}partial(t){let n={};for(let e of FZ.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 FZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof PQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return kQ(FZ.objectKeys(this.shape))}};yQ.create=(e,t)=>new yQ({shape:()=>e,unknownKeys:`strip`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)}),yQ.strictCreate=(e,t)=>new yQ({shape:()=>e,unknownKeys:`strict`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)}),yQ.lazycreate=(e,t)=>new yQ({shape:e,unknownKeys:`strip`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)});var bQ=class extends tQ{_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 RZ(e.ctx.common.issues));return HZ(t,{code:Z.invalid_union,unionErrors:n}),WZ}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 RZ(e));return HZ(t,{code:Z.invalid_union,unionErrors:i}),WZ}}get options(){return this._def.options}};bQ.create=(e,t)=>new bQ({options:e,typeName:Q.ZodUnion,...eQ(t)});const xQ=e=>e instanceof DQ?xQ(e.schema):e instanceof NQ?xQ(e.innerType()):e instanceof OQ?[e.value]:e instanceof AQ?e.options:e instanceof jQ?FZ.objectValues(e.enum):e instanceof IQ?xQ(e._def.innerType):e instanceof dQ?[void 0]:e instanceof fQ?[null]:e instanceof PQ?[void 0,...xQ(e.unwrap())]:e instanceof FQ?[null,...xQ(e.unwrap())]:e instanceof zQ||e instanceof VQ?xQ(e.unwrap()):e instanceof LQ?xQ(e._def.innerType):[];var Wxe=class e extends tQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==IZ.object)return HZ(t,{code:Z.invalid_type,expected:IZ.object,received:t.parsedType}),WZ;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}):(HZ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),WZ)}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=xQ(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,...eQ(r)})}};function SQ(e,t){let n=LZ(e),r=LZ(t);if(e===t)return{valid:!0,data:e};if(n===IZ.object&&r===IZ.object){let n=FZ.objectKeys(t),r=FZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=SQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===IZ.array&&r===IZ.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=SQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===IZ.date&&r===IZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var CQ=class extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(qZ(e)||qZ(r))return WZ;let i=SQ(e.value,r.value);return i.valid?((JZ(e)||JZ(r))&&t.dirty(),{status:t.value,value:i.data}):(HZ(n,{code:Z.invalid_intersection_types}),WZ)};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}))}};CQ.create=(e,t,n)=>new CQ({left:e,right:t,typeName:Q.ZodIntersection,...eQ(n)});var wQ=class e extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==IZ.array)return HZ(n,{code:Z.invalid_type,expected:IZ.array,received:n.parsedType}),WZ;if(n.data.length<this._def.items.length)return HZ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),WZ;!this._def.rest&&n.data.length>this._def.items.length&&(HZ(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 QZ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>UZ.mergeArray(t,e)):UZ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new wQ({items:e,typeName:Q.ZodTuple,rest:null,...eQ(t)})};var Gxe=class e extends tQ{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!==IZ.object)return HZ(n,{code:Z.invalid_type,expected:IZ.object,received:n.parsedType}),WZ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new QZ(n,e,n.path,e)),value:a._parse(new QZ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?UZ.mergeObjectAsync(t,r):UZ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof tQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...eQ(r)}):new e({keyType:aQ.create(),valueType:t,typeName:Q.ZodRecord,...eQ(n)})}},TQ=class extends tQ{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!==IZ.map)return HZ(n,{code:Z.invalid_type,expected:IZ.map,received:n.parsedType}),WZ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new QZ(n,e,n.path,[a,`key`])),value:i._parse(new QZ(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 WZ;(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 WZ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};TQ.create=(e,t,n)=>new TQ({valueType:t,keyType:e,typeName:Q.ZodMap,...eQ(n)});var EQ=class e extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==IZ.set)return HZ(n,{code:Z.invalid_type,expected:IZ.set,received:n.parsedType}),WZ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(HZ(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&&(HZ(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 WZ;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 QZ(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:ZZ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:ZZ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};EQ.create=(e,t)=>new EQ({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...eQ(t)});var Kxe=class e extends tQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==IZ.function)return HZ(t,{code:Z.invalid_type,expected:IZ.function,received:t.parsedType}),WZ;function n(e,n){return VZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,BZ(),zZ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return VZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,BZ(),zZ].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 MQ){let e=this;return KZ(async function(...t){let o=new RZ([]),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 KZ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new RZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new RZ([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:wQ.create(t).rest(mQ.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||wQ.create([]).rest(mQ.create()),returns:n||mQ.create(),typeName:Q.ZodFunction,...eQ(r)})}},DQ=class extends tQ{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})}};DQ.create=(e,t)=>new DQ({getter:e,typeName:Q.ZodLazy,...eQ(t)});var OQ=class extends tQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return HZ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),WZ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};OQ.create=(e,t)=>new OQ({value:e,typeName:Q.ZodLiteral,...eQ(t)});function kQ(e,t){return new AQ({values:e,typeName:Q.ZodEnum,...eQ(t)})}var AQ=class e extends tQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return HZ(t,{expected:FZ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),WZ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return HZ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),WZ}return KZ(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})}};AQ.create=kQ;var jQ=class extends tQ{_parse(e){let t=FZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==IZ.string&&n.parsedType!==IZ.number){let e=FZ.objectValues(t);return HZ(n,{expected:FZ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),WZ}if(this._cache||=new Set(FZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=FZ.objectValues(t);return HZ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),WZ}return KZ(e.data)}get enum(){return this._def.values}};jQ.create=(e,t)=>new jQ({values:e,typeName:Q.ZodNativeEnum,...eQ(t)});var MQ=class extends tQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==IZ.promise&&t.common.async===!1?(HZ(t,{code:Z.invalid_type,expected:IZ.promise,received:t.parsedType}),WZ):KZ((t.parsedType===IZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};MQ.create=(e,t)=>new MQ({type:e,typeName:Q.ZodPromise,...eQ(t)});var NQ=class extends tQ{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=>{HZ(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 WZ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?WZ:r.status===`dirty`||t.value===`dirty`?GZ(r.value):r});{if(t.value===`aborted`)return WZ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?WZ:r.status===`dirty`||t.value===`dirty`?GZ(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`?WZ:(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`?WZ:(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(!YZ(e))return WZ;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=>YZ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):WZ);FZ.assertNever(r)}};NQ.create=(e,t,n)=>new NQ({schema:e,typeName:Q.ZodEffects,effect:t,...eQ(n)}),NQ.createWithPreprocess=(e,t,n)=>new NQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...eQ(n)});var PQ=class extends tQ{_parse(e){return this._getType(e)===IZ.undefined?KZ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};PQ.create=(e,t)=>new PQ({innerType:e,typeName:Q.ZodOptional,...eQ(t)});var FQ=class extends tQ{_parse(e){return this._getType(e)===IZ.null?KZ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};FQ.create=(e,t)=>new FQ({innerType:e,typeName:Q.ZodNullable,...eQ(t)});var IQ=class extends tQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===IZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};IQ.create=(e,t)=>new IQ({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...eQ(t)});var LQ=class extends tQ{_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 XZ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new RZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new RZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};LQ.create=(e,t)=>new LQ({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...eQ(t)});var RQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.nan){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.nan,received:t.parsedType}),WZ}return{status:`valid`,value:e.data}}};RQ.create=e=>new RQ({typeName:Q.ZodNaN,...eQ(e)});var zQ=class extends tQ{_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}},BQ=class e extends tQ{_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`?WZ:e.status===`dirty`?(t.dirty(),GZ(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`?WZ: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})}},VQ=class extends tQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(YZ(e)&&(e.value=Object.freeze(e.value)),e);return XZ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};VQ.create=(e,t)=>new VQ({innerType:e,typeName:Q.ZodReadonly,...eQ(t)}),yQ.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||={}),aQ.create,oQ.create,RQ.create,sQ.create,cQ.create,lQ.create,uQ.create,dQ.create,fQ.create,pQ.create,mQ.create,hQ.create,gQ.create,_Q.create;const qxe=yQ.create;yQ.strictCreate,bQ.create,Wxe.create,CQ.create,wQ.create,Gxe.create,TQ.create,EQ.create,Kxe.create,DQ.create,OQ.create,AQ.create,jQ.create,MQ.create,NQ.create,PQ.create,FQ.create,NQ.createWithPreprocess,BQ.create;const Jxe=le(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);r.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>fe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>we(e,t,n),e.parseAsync=async(t,n)=>Ne(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ke(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)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Yxe=le(`ZodMiniObject`,(e,t)=>{E.init(e,t),Jxe.init(e,t),Te(e,`shape`,()=>t.shape)});function HQ(e,t){return new Yxe({type:`object`,shape:e??{},...Ae(t)})}function UQ(e){return!!e._zod}function WQ(e){let t=Object.values(e);if(t.length===0)return HQ({});let n=t.every(UQ),r=t.every(e=>!UQ(e));if(n)return HQ(e);if(r)return qxe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function GQ(e,t){return UQ(e)?we(e,t):e.safeParse(t)}async function KQ(e,t){return UQ(e)?await ke(e,t):await e.safeParseAsync(t)}function qQ(e){if(!e)return;let t;if(t=UQ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function JQ(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 WQ(e)}}if(UQ(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 YQ(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 Xxe(e){return e.description}function Zxe(e){if(UQ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function XQ(e){if(UQ(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 ZQ=`2025-11-25`,QQ=[ZQ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],$Q=`io.modelcontextprotocol/related-task`,e$=be(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),t$=j([A(),O().int()]),n$=A();x({ttl:O().optional(),pollInterval:O().optional()});const Qxe=P({ttl:O().optional()}),$xe=P({taskId:A()}),r$=x({progressToken:t$.optional(),[$Q]:$xe.optional()}),i$=P({_meta:r$.optional()}),a$=i$.extend({task:Qxe.optional()}),eSe=e=>a$.safeParse(e).success,o$=P({method:A(),params:i$.loose().optional()}),s$=P({_meta:r$.optional()}),c$=P({method:A(),params:s$.loose().optional()}),l$=x({_meta:r$.optional()}),u$=j([A(),O().int()]),d$=P({jsonrpc:g(`2.0`),id:u$,...o$.shape}).strict(),f$=e=>d$.safeParse(e).success,p$=P({jsonrpc:g(`2.0`),...c$.shape}).strict(),tSe=e=>p$.safeParse(e).success,m$=P({jsonrpc:g(`2.0`),id:u$,result:l$}).strict(),h$=e=>m$.safeParse(e).success;var g$;(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`})(g$||={});const _$=P({jsonrpc:g(`2.0`),id:u$.optional(),error:P({code:O().int(),message:A(),data:f().optional()})}).strict(),v$=e=>_$.safeParse(e).success,y$=j([d$,p$,m$,_$]);j([m$,_$]);const b$=l$.strict(),nSe=s$.extend({requestId:u$.optional(),reason:A().optional()}),x$=c$.extend({method:g(`notifications/cancelled`),params:nSe}),S$=P({icons:N(P({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:d([`light`,`dark`]).optional()})).optional()}),C$=P({name:A(),title:A().optional()}),w$=C$.extend({...C$.shape,...S$.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),rSe=re(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,T(P({form:T(P({applyDefaults:a().optional()}),m(A(),f())).optional(),url:e$.optional()}),m(A(),f()).optional())),iSe=x({list:e$.optional(),cancel:e$.optional(),requests:x({sampling:x({createMessage:e$.optional()}).optional(),elicitation:x({create:e$.optional()}).optional()}).optional()}),aSe=x({list:e$.optional(),cancel:e$.optional(),requests:x({tools:x({call:e$.optional()}).optional()}).optional()}),oSe=P({experimental:m(A(),e$).optional(),sampling:P({context:e$.optional(),tools:e$.optional()}).optional(),elicitation:rSe.optional(),roots:P({listChanged:a().optional()}).optional(),tasks:iSe.optional(),extensions:m(A(),e$).optional()}),sSe=i$.extend({protocolVersion:A(),capabilities:oSe,clientInfo:w$}),T$=o$.extend({method:g(`initialize`),params:sSe}),E$=e=>T$.safeParse(e).success,cSe=P({experimental:m(A(),e$).optional(),logging:e$.optional(),completions:e$.optional(),prompts:P({listChanged:a().optional()}).optional(),resources:P({subscribe:a().optional(),listChanged:a().optional()}).optional(),tools:P({listChanged:a().optional()}).optional(),tasks:aSe.optional(),extensions:m(A(),e$).optional()}),lSe=l$.extend({protocolVersion:A(),capabilities:cSe,serverInfo:w$,instructions:A().optional()}),D$=c$.extend({method:g(`notifications/initialized`),params:s$.optional()}),uSe=e=>D$.safeParse(e).success,O$=o$.extend({method:g(`ping`),params:i$.optional()}),dSe=P({progress:O(),total:s(O()),message:s(A())}),fSe=P({...s$.shape,...dSe.shape,progressToken:t$}),k$=c$.extend({method:g(`notifications/progress`),params:fSe}),pSe=i$.extend({cursor:n$.optional()}),A$=o$.extend({params:pSe.optional()}),j$=l$.extend({nextCursor:n$.optional()}),mSe=d([`working`,`input_required`,`completed`,`failed`,`cancelled`]),M$=P({taskId:A(),status:mSe,ttl:j([O(),u()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:s(O()),statusMessage:s(A())}),N$=l$.extend({task:M$}),hSe=s$.merge(M$),P$=c$.extend({method:g(`notifications/tasks/status`),params:hSe}),F$=o$.extend({method:g(`tasks/get`),params:i$.extend({taskId:A()})}),I$=l$.merge(M$),L$=o$.extend({method:g(`tasks/result`),params:i$.extend({taskId:A()})});l$.loose();const R$=A$.extend({method:g(`tasks/list`)}),z$=j$.extend({tasks:N(M$)}),B$=o$.extend({method:g(`tasks/cancel`),params:i$.extend({taskId:A()})}),gSe=l$.merge(M$),V$=P({uri:A(),mimeType:s(A()),_meta:m(A(),f()).optional()}),H$=V$.extend({text:A()}),U$=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),W$=V$.extend({blob:U$}),G$=d([`user`,`assistant`]),K$=P({audience:N(G$).optional(),priority:O().min(0).max(1).optional(),lastModified:v({offset:!0}).optional()}),q$=P({...C$.shape,...S$.shape,uri:A(),description:s(A()),mimeType:s(A()),size:s(O()),annotations:K$.optional(),_meta:s(x({}))}),_Se=P({...C$.shape,...S$.shape,uriTemplate:A(),description:s(A()),mimeType:s(A()),annotations:K$.optional(),_meta:s(x({}))}),J$=A$.extend({method:g(`resources/list`)}),vSe=j$.extend({resources:N(q$)}),Y$=A$.extend({method:g(`resources/templates/list`)}),ySe=j$.extend({resourceTemplates:N(_Se)}),X$=i$.extend({uri:A()}),bSe=X$,Z$=o$.extend({method:g(`resources/read`),params:bSe}),xSe=l$.extend({contents:N(j([H$,W$]))}),SSe=c$.extend({method:g(`notifications/resources/list_changed`),params:s$.optional()}),CSe=X$,wSe=o$.extend({method:g(`resources/subscribe`),params:CSe}),TSe=X$,ESe=o$.extend({method:g(`resources/unsubscribe`),params:TSe}),DSe=s$.extend({uri:A()}),OSe=c$.extend({method:g(`notifications/resources/updated`),params:DSe}),kSe=P({name:A(),description:s(A()),required:s(a())}),ASe=P({...C$.shape,...S$.shape,description:s(A()),arguments:s(N(kSe)),_meta:s(x({}))}),Q$=A$.extend({method:g(`prompts/list`)}),jSe=j$.extend({prompts:N(ASe)}),MSe=i$.extend({name:A(),arguments:m(A(),A()).optional()}),$$=o$.extend({method:g(`prompts/get`),params:MSe}),e1=P({type:g(`text`),text:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),t1=P({type:g(`image`),data:U$,mimeType:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),n1=P({type:g(`audio`),data:U$,mimeType:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),NSe=P({type:g(`tool_use`),name:A(),id:A(),input:m(A(),f()),_meta:m(A(),f()).optional()}),PSe=P({type:g(`resource`),resource:j([H$,W$]),annotations:K$.optional(),_meta:m(A(),f()).optional()}),r1=j([e1,t1,n1,q$.extend({type:g(`resource_link`)}),PSe]),FSe=P({role:G$,content:r1}),ISe=l$.extend({description:A().optional(),messages:N(FSe)}),LSe=c$.extend({method:g(`notifications/prompts/list_changed`),params:s$.optional()}),RSe=P({title:A().optional(),readOnlyHint:a().optional(),destructiveHint:a().optional(),idempotentHint:a().optional(),openWorldHint:a().optional()}),zSe=P({taskSupport:d([`required`,`optional`,`forbidden`]).optional()}),i1=P({...C$.shape,...S$.shape,description:A().optional(),inputSchema:P({type:g(`object`),properties:m(A(),e$).optional(),required:N(A()).optional()}).catchall(f()),outputSchema:P({type:g(`object`),properties:m(A(),e$).optional(),required:N(A()).optional()}).catchall(f()).optional(),annotations:RSe.optional(),execution:zSe.optional(),_meta:m(A(),f()).optional()}),a1=A$.extend({method:g(`tools/list`)}),BSe=j$.extend({tools:N(i1)}),o1=l$.extend({content:N(r1).default([]),structuredContent:m(A(),f()).optional(),isError:a().optional()});o1.or(l$.extend({toolResult:f()}));const VSe=a$.extend({name:A(),arguments:m(A(),f()).optional()}),s1=o$.extend({method:g(`tools/call`),params:VSe}),HSe=c$.extend({method:g(`notifications/tools/list_changed`),params:s$.optional()});P({autoRefresh:a().default(!0),debounceMs:O().int().nonnegative().default(300)});const c1=d([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),USe=i$.extend({level:c1}),l1=o$.extend({method:g(`logging/setLevel`),params:USe}),WSe=s$.extend({level:c1,logger:A().optional(),data:f()}),GSe=c$.extend({method:g(`notifications/message`),params:WSe}),KSe=P({hints:N(P({name:A().optional()})).optional(),costPriority:O().min(0).max(1).optional(),speedPriority:O().min(0).max(1).optional(),intelligencePriority:O().min(0).max(1).optional()}),qSe=P({mode:d([`auto`,`required`,`none`]).optional()}),JSe=P({type:g(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(r1).default([]),structuredContent:P({}).loose().optional(),isError:a().optional(),_meta:m(A(),f()).optional()}),YSe=S(`type`,[e1,t1,n1]),u1=S(`type`,[e1,t1,n1,NSe,JSe]),XSe=P({role:G$,content:j([u1,N(u1)]),_meta:m(A(),f()).optional()}),ZSe=a$.extend({messages:N(XSe),modelPreferences:KSe.optional(),systemPrompt:A().optional(),includeContext:d([`none`,`thisServer`,`allServers`]).optional(),temperature:O().optional(),maxTokens:O().int(),stopSequences:N(A()).optional(),metadata:e$.optional(),tools:N(i1).optional(),toolChoice:qSe.optional()}),QSe=o$.extend({method:g(`sampling/createMessage`),params:ZSe}),d1=l$.extend({model:A(),stopReason:s(d([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:G$,content:YSe}),f1=l$.extend({model:A(),stopReason:s(d([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:G$,content:j([u1,N(u1)])}),$Se=P({type:g(`boolean`),title:A().optional(),description:A().optional(),default:a().optional()}),eCe=P({type:g(`string`),title:A().optional(),description:A().optional(),minLength:O().optional(),maxLength:O().optional(),format:d([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),tCe=P({type:d([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),nCe=P({type:g(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),rCe=P({type:g(`string`),title:A().optional(),description:A().optional(),oneOf:N(P({const:A(),title:A()})),default:A().optional()}),iCe=j([j([P({type:g(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),j([nCe,rCe]),j([P({type:g(`array`),title:A().optional(),description:A().optional(),minItems:O().optional(),maxItems:O().optional(),items:P({type:g(`string`),enum:N(A())}),default:N(A()).optional()}),P({type:g(`array`),title:A().optional(),description:A().optional(),minItems:O().optional(),maxItems:O().optional(),items:P({anyOf:N(P({const:A(),title:A()}))}),default:N(A()).optional()})])]),$Se,eCe,tCe]),aCe=j([a$.extend({mode:g(`form`).optional(),message:A(),requestedSchema:P({type:g(`object`),properties:m(A(),iCe),required:N(A()).optional()})}),a$.extend({mode:g(`url`),message:A(),elicitationId:A(),url:A().url()})]),oCe=o$.extend({method:g(`elicitation/create`),params:aCe}),sCe=s$.extend({elicitationId:A()}),cCe=c$.extend({method:g(`notifications/elicitation/complete`),params:sCe}),p1=l$.extend({action:d([`accept`,`decline`,`cancel`]),content:re(e=>e===null?void 0:e,m(A(),j([A(),O(),a(),N(A())])).optional())}),lCe=P({type:g(`ref/resource`),uri:A()}),uCe=P({type:g(`ref/prompt`),name:A()}),dCe=i$.extend({ref:j([uCe,lCe]),argument:P({name:A(),value:A()}),context:P({arguments:m(A(),A()).optional()}).optional()}),m1=o$.extend({method:g(`completion/complete`),params:dCe});function fCe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pCe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const mCe=l$.extend({completion:x({values:N(A()).max(100),total:s(O().int()),hasMore:s(a())})}),hCe=P({uri:A().startsWith(`file://`),name:A().optional(),_meta:m(A(),f()).optional()}),gCe=o$.extend({method:g(`roots/list`),params:i$.optional()}),h1=l$.extend({roots:N(hCe)}),_Ce=c$.extend({method:g(`notifications/roots/list_changed`),params:s$.optional()});j([O$,T$,m1,l1,$$,Q$,J$,Y$,Z$,wSe,ESe,s1,a1,F$,L$,R$,B$]),j([x$,k$,D$,_Ce,P$]),j([b$,d1,f1,p1,h1,I$,z$,N$]),j([O$,QSe,oCe,gCe,F$,L$,R$,B$]),j([x$,k$,GSe,OSe,SSe,HSe,LSe,P$,cCe]),j([b$,lSe,mCe,ISe,jSe,vSe,ySe,xSe,o1,BSe,I$,z$,N$]);var g1=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===g$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new vCe(e.elicitations,n)}return new e(t,n,r)}},vCe=class extends g1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(g$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function _1(e){return e===`completed`||e===`failed`||e===`cancelled`}const yCe=Symbol(`Let zodToJsonSchema decide on which parser to use`),v1={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`},bCe=e=>typeof e==`string`?{...v1,name:e}:{...v1,...e},xCe=e=>{let t=bCe(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 y1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function b1(e,t,n,r,i){e[t]=n,y1(e,t,r,i)}const x1=(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 S1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?x1(t,e.currentPath):t.join(`/`)}}function SCe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=F1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&b1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&b1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(b1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),b1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function CCe(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?b1(n,`minimum`,r.value,r.message,t):b1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),b1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?b1(n,`maximum`,r.value,r.message,t):b1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),b1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:b1(n,`multipleOf`,r.value,r.message,t);break}return n}function wCe(){return{type:`boolean`}}function C1(e,t){return F1(e.type._def,t)}const TCe=(e,t)=>F1(e.innerType._def,t);function w1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>w1(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 ECe(e,t)}}const ECe=(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`:b1(n,`minimum`,r.value,r.message,t);break;case`max`:b1(n,`maximum`,r.value,r.message,t);break}return n};function DCe(e,t){return{...F1(e.innerType._def,t),default:e.defaultValue()}}function OCe(e,t){return t.effectStrategy===`input`?F1(e.schema._def,t):S1(t)}function kCe(e){return{type:`string`,enum:Array.from(e.values)}}const ACe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function jCe(e,t){let n=[F1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),F1(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(ACe(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 MCe(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 T1;const E1={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:()=>(T1===void 0&&(T1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),T1),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 D1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:b1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:b1(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`:k1(n,`email`,r.message,t);break;case`format:idn-email`:k1(n,`idn-email`,r.message,t);break;case`pattern:zod`:A1(n,E1.email,r.message,t);break}break;case`url`:k1(n,`uri`,r.message,t);break;case`uuid`:k1(n,`uuid`,r.message,t);break;case`regex`:A1(n,r.regex,r.message,t);break;case`cuid`:A1(n,E1.cuid,r.message,t);break;case`cuid2`:A1(n,E1.cuid2,r.message,t);break;case`startsWith`:A1(n,RegExp(`^${O1(r.value,t)}`),r.message,t);break;case`endsWith`:A1(n,RegExp(`${O1(r.value,t)}$`),r.message,t);break;case`datetime`:k1(n,`date-time`,r.message,t);break;case`date`:k1(n,`date`,r.message,t);break;case`time`:k1(n,`time`,r.message,t);break;case`duration`:k1(n,`duration`,r.message,t);break;case`length`:b1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),b1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:A1(n,RegExp(O1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&k1(n,`ipv4`,r.message,t),r.version!==`v4`&&k1(n,`ipv6`,r.message,t);break;case`base64url`:A1(n,E1.base64url,r.message,t);break;case`jwt`:A1(n,E1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&A1(n,E1.ipv4Cidr,r.message,t),r.version!==`v4`&&A1(n,E1.ipv6Cidr,r.message,t);break;case`emoji`:A1(n,E1.emoji(),r.message,t);break;case`ulid`:A1(n,E1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:k1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:b1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:A1(n,E1.base64,r.message,t);break}break;case`nanoid`:A1(n,E1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function O1(e,t){return t.patternStrategy===`escape`?PCe(e):e}const NCe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function PCe(e){let t=``;for(let n=0;n<e.length;n++)NCe.has(e[n])||(t+=`\\`),t+=e[n];return t}function k1(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}}})):b1(e,`format`,t,n,r)}function A1(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:j1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):b1(e,`pattern`,j1(t,r),n,r)}function j1(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
1187
+ `).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 Un(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Uo=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Wo(e){try{let t=co(e.scope);if(!t)return;let n=UI(t);if(n.length===0)return;let r=YI(z(e.skillsRoot,e.name),e.name,t,n,`copy`,WI(e.scope));if(r.length===0)return;await IN(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 Go(e,t){if(t.ok){J(e,200,mee,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 Ko=Obe({contentDir:c,skillsHome:Ea,...M===void 0?{}:{projectDir:M},resolveSkillDirForRead:ka,parseFrontmatterDoc:ha,attributeOkArtifactWrite:An,commitOkArtifactWrite:Un,shadowHeadSha:Ho,artifactWriterId:Uo,effectiveInstallMode:za,signalFiles:()=>je?.(`files`)}),Jo=Nbe({contentDir:c,skillsHome:Ea,...M===void 0?{}:{projectDir:M},legacyStoreRoot:wi,effectiveSkillRoot:bo,parseFrontmatterDoc:ha,attributeOkArtifactWrite:An,commitOkArtifactWrite:Un,shadowHeadSha:Ho,artifactWriterId:Uo,skillArtifactKey:e=>kn(`skill`,``,e),captureAndCloseDocuments:Vt,projectImportedSkillCopy:Wo,signalFiles:()=>je?.(`files`)});function Yo(e,t){if(t.ok){J(e,200,tr,t.body,{handler:`skill-reimport`});return}K(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function Xo(e,t,n){let r=e===`project`?c:Ea,i=(e===`project`?vL(c):yL(Ea)).find(e=>e.name===t);return i?z(r,i.dir):z(n,t)}function Zo(e,t,n,r){let i=r.skills[t];if(i)return i;let a=Xo(e,t,n);return Bue(t,_D(a)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:Ibe(a)})??Ga(e===`global`?Ea:c,t)??$a(t,zd(M??c),a)}let Qo=q(ute,async(e,t,n)=>{let r=()=>{};try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);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 SD(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(kK(t,p,`skill-import`))return;let m=await oD(p);r=m.cleanup,s=m.ref;let h=vD(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=>hD(e.dir)?.name===f)??h.find(e=>e.name===Es[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??zo(d)}catch(e){if(e instanceof XE){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 Ko.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||bs(u))&&NI({source:u,skills:[d.body.name]},fI()),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),je?.(`files`),Go(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`}),$o=q(Jee,async(e,t,n)=>{let r=()=>{};try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);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 SD(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(kK(t,f,`skills-import-bulk`))return;if(l=e?.publisher??zo(d),f.kind===`well-known`)a=f,o=await nD(f.origin);else{let e=await oD(f);r=e.cleanup,c=e.ref,s=vD(e.dir)}}catch(e){if(e instanceof XE){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 oD({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof XE?`not-found`:`failed`,warnings:[],...e instanceof XE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>_D(e.dir)?.name===t)??s.find(e=>e.name===Es[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Ko.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`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){F(`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||bs(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&NI({source:u,skills:e},fI())}Fn(),he?.refreshInPlaceSkillDirs(),Rn(),je?.(`files`),J(t,200,eee,{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`}),es=8*1024*1024,ts=32*1024*1024;function rs(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+B)?null:r}function is(e){return new Promise((t,n)=>{let r;try{r=DJ(e,{files:200,fields:10,fieldSize:2*1024,fileSize:es})}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>ts){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 as(e,t){return new Promise((n,r)=>{(0,qde.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=rs(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){sc(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>es){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>ts){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{sc(I(n),{recursive:!0}),gc(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 ss(e,t){let n=ku(L(Gu(),`ok-skill-upload-`)),r=()=>{try{dc(n,{recursive:!0,force:!0})}catch{}};try{if(!M){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=wa(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=pO({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},ce);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 is(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 as(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=rs(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}sc(I(r),{recursive:!0}),gc(r,e.data)}let u=vD(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];Go(t,await Ko.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 cs=q(pt,async(e,t,n)=>{try{let e=Oa(n.scope);if(!Ca(n.name,t,`skill-install`))return;if(n.scope===`project`&&!M){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=co(n.scope),i=z(e,n.name),a=n.scope===`project`?c:Ea,o=(n.scope===`project`?vL(c):yL(Ea)).find(e=>e.name===n.name),s=rO(n.name)?eo(n.name,n.scope):null,l=o?z(a,o.dir):V(i)||s===null?i:I(s);if(!V(l)){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 ut(n.scope===`project`?`${R(a,l).split(B).join(`/`)}/SKILL`:os(n.scope,n.name));let u=HI(l,n.name,{allowReservedName:rO(n.name)});if(!u.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${u.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=Da.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)}`)}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o.hosts.filter(oa),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let d=n.setSource??n.source,f=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),p=n.targets,m=[],h=[];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 Da.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}p=e.targets.filter(oa),m.push(...e.rootAdds),h.push(...e.rootRemoves)}if(d&&!o){let e=await Da.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:l,newSource:d});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}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?M:Ea;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 ir.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:l,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||je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?M:Ea;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 ir.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:l});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)}`)}je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,Cr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.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`?M:Ea,s=await ir.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:l,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)}`)}je?.(`files`),J(t,200,Cr,{name:n.name,hosts:[...o.hosts],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let g=n.scope===`global`?p===void 0?II(Ea).map(e=>e.editorId):Zee.filter(e=>p?.some(t=>t===e)):p===void 0?UI(r):Pr.filter(e=>p?.some(t=>t===e)),_=[],v=[];if(g.length===0&&p===void 0&&(_.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`."),v.push(`no-targets`)),u.hasScripts&&(_.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."),v.push(`scripts-present`)),u.warnings.length>0&&(_.push(u.warnings[0]),v.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(p===void 0?n.scope===`global`&&V(L(Ea,`.agents`)):p.includes(`agents`))?[...g,`agents`]:[...g],a=n.scope===`project`?M:Ea,s=f===void 0?za(n.scope,n.name,o):f?`link`:`copy`;if(d){let e=await Da.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:l,inPlaceEntry:o,newSource:d});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}je?.(`files`),J(t,200,Cr,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let c=await Da.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:l,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:p!==void 0,installMode:s,...f===void 0?{}:{linkModeReq:f},rootAdds:m,rootRemoves:h});if(!c.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:c.reason});return}_.push(...c.warnings),v.push(...c.warningCodes),je?.(`files`),J(t,200,Cr,{name:n.name,hosts:c.hosts,scripts:u.hasScripts,warnings:_,warningCodes:v,...c.sourceMovedTo===void 0?{}:{sourceMovedTo:c.sourceMovedTo}},{handler:`skill-install`});return}let y=BI(PN(r).skills[n.name]?.hosts??[]).filter(e=>!g.includes(e));y.length>0&&rL(n.name,r,y,WI(n.scope));let b=L(r,...sD),x=V(b)?H(b,`utf-8`):null,S=x===null?null:lD(x);x!==null&&S===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let C=S?.skills[n.name]!==void 0,w=f===void 0?C?`copy`:`symlink`:f?`symlink`:`copy`,T=YI(l,n.name,r,g,w,WI(n.scope));T.length===0?await LN(r,n.name):await IN(r,n.name,{hosts:T,scope:n.scope,scripts:u.hasScripts,installedAt:new Date().toISOString(),projection:w}),je?.(`files`),J(t,200,Cr,{name:n.name,hosts:T,scripts:u.hasScripts,warnings:_,warningCodes:v},{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`}),ls=q(Gt,async(e,t,n)=>{try{if(!Ca(n.name,t,`skill-uninstall`))return;let e=co(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 lo(e,n.name,n.scope);je?.(`files`),J(t,200,nee,{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`}),us=q(Lt,async(e,t,n)=>{try{let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Ca(n.name,t,`skill-restore`)||ao(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=w?.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 _X({shadow:r,contentDir:c,contentRoot:te??`.`,name:n.name,version:n.version,skillDirRel:Va(n.name)});if(!i.ok){Ia(t,i,`skill-restore`);return}let a=[],o=HI(z(c,Va(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),An(e,kn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Un(`skill-restore`),je?.(`files`),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,on,{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`}),ds=q(Hn,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Ca(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Ea:c,{root:a,dirRel:o,realDir:s}=bo(n.scope,n.name);if(s===null||!V(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let l=L(n.scope===`global`?Ea:M,...sD),u=Zo(n.scope,n.name,a,Bo(l));if(!u){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 HK(l,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),Fn(),he?.refreshInPlaceSkillDirs(),Rn(),J(t,200,tr,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null;try{let e=u.skill??n.name,i=Es[e],a=await SD(u.source,e).catch(async e=>{if(i===void 0)throw e;return SD(u.source,i)}),o=a?.source??WD(u.source,u.pluginProvider),s=a?.skill??u.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:u.source});return}if(kK(t,c,`skill-reimport`))return;let l=await oD(c);r=l.cleanup,d=l.ref;let p=vD(l.dir),m=mX(p,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>_D(e)?.name});if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:p.map(e=>e.name).join(`, `)});return}f=m.dir}catch(e){if(e instanceof XE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let p=await Jo.runSkillReimport({acquiredDir:f,name:n.name,scope:n.scope,entry:u,lockPath:l,ref:d,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});Fn(),he?.refreshInPlaceSkillDirs(),Rn(),Yo(t,p)}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`}),fs=q(Xr,async(e,t,n)=>{try{if(n.scope===`project`&&!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let r=pO(n,ce);if(r.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let i=L(n.scope===`global`?Ea:M,...sD),a=Bo(i),o=[],{bySource:s,unrecorded:c}=Mbe([...new Set(n.names)].filter(e=>Sa(e)?!0:(o.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`}),!1)),e=>Zo(n.scope,e,bo(n.scope,e).root,a));for(let e of c)o.push({requested:e,status:`not-found`,warnings:[]});for(let t of s){let s=()=>{};try{let c,l=[];try{let e=t.names[0],n=await SD(t.source,e).catch(async n=>{let r=Es[e];if(r===void 0)throw n;return SD(t.source,r)}),r=n?.source??WD(t.source,a.skills[t.names[0]]?.pluginProvider),i=n?.spec??iD(r);if(!i||OK(i)){for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:`INVALID_SOURCE`});continue}let u=await oD(i);s=u.cleanup,c=u.ref,l=vD(u.dir)}catch(n){F(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:xS(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)});continue}for(let s of t.names){let t=Zo(n.scope,s,bo(n.scope,s).root,a);if(!t){o.push({requested:s,status:`not-found`,warnings:[]});continue}let u=mX(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:s,frontmatterNameOf:e=>_D(e)?.name});if(!u){o.push({requested:s,status:`not-found`,source:t.source,warnings:[]});continue}try{let a=await Jo.runSkillReimport({acquiredDir:u.dir,name:s,scope:n.scope,entry:t,lockPath:i,ref:c,actor:r});if(!a.ok){F(`skills-reimport-bulk`).warn({skill:s,err:a.cause,detail:a.detail,requestId:xS(e)},`bulk update: one skill failed (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:a.detail??a.title});continue}o.push({requested:s,status:a.body.updated?`updated`:`up-to-date`,source:a.body.source,warnings:a.body.warnings})}catch(n){F(`skills-reimport-bulk`).warn({skill:s,err:n,requestId:xS(e)},`bulk update: one skill threw (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)})}}}finally{s()}}J(t,200,bee,{results:o,updated:o.filter(e=>e.status===`updated`).length,upToDate:o.filter(e=>e.status===`up-to-date`).length,failed:o.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{Fn(),he?.refreshInPlaceSkillDirs(),Fn(),await he?.rebuildIgnorePatterns()}catch(e){F(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),ps=q(iee,async(e,t,n)=>{try{if(!M){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=pO(n,ce);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Ca(n.name,t,`skill-revert`)||ao(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=L(M,...sD),i=Bo(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=w?.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 _X({shadow:a,contentDir:c,contentRoot:te??`.`,name:n.name,version:i.baselineRef,skillDirRel:Va(n.name)});if(!o.ok){Ia(t,o,`skill-revert`);return}An(e,kn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Un(`skill-revert`);let s=z(c,Va(n.name),`..`),l=Vo(s,n.name);await HK(r,e=>uD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),s===Oa(`project`)&&await Wo({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),je?.(`files`),J(t,200,lee,{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`}),ms=Ebe({contentDir:c,projectDir:M,getAllFilesIndex:m,getFileIndexGeneration:g,getSearchMaxEntries:Wbe,semanticSearch:N,getSemanticSimilarityFloor:Se,ready:ve,getProjectSkillsRoot:()=>Oa(`project`),parseFrontmatterDoc:ha});ms.prewarm();async function vs(e,t){if(r(e,t,{handler:`handoff`}))try{await Kpe(e,t,{contentDir:c,platform:process.platform,isSchemeRegistered:P.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:xS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function xs(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await gN(e,t,{contentDir:c,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:xS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Cs=q(en,async(e,t,n)=>{try{if(!M){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!She(e,n.kind)){BF(`invalid-path`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`invalid-path`},{handler:RF});return}let r=Ehe(M);if(r===null){if(XF(M).kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}BF(`detached-head`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`detached-head`},{handler:RF});return}let i=XF(M);if(i.kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`no-remote`},{handler:RF});return}if(i.kind===`non-github`){BF(`non-github-remote`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`non-github-remote`},{handler:RF});return}if(!Fhe(M,r)){BF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,Mr,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:RF});return}let a=eZ(M,c);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=a===``?e:e===``?a:`${a}/${e}`,s;s=n.kind===`doc`?Che(i.host,i.owner,i.repo,r,o):zF(i.host,i.owner,i.repo,r,o);let l;try{let e=a===``?0:li(zF(i.host,i.owner,i.repo,r,a)).targetSegments.length;l=`https://openknowledge.ai/d/${yee(s,e)}`}catch(e){if(!(e instanceof ti))throw e;BF(`unsupported-share-url`,{kind:n.kind}),J(t,200,Mr,{ok:!1,error:`unsupported-share-url`},{handler:RF});return}let u=await whe(M,r,o,n.kind);BF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,Mr,{ok:!0,shareUrl:l,sharedUrl:s,branch:r,freshness:u},{handler:RF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:RF,cause:e})}},{handler:RF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:RF})}),ws=q(Gr,async(e,t)=>{try{if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:Qz});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(!Fee(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:Qz});return}if(!Xz(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:Qz});return}J(t,200,uee,await Zz(M,r,i,a),{handler:Qz})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Qz,cause:e})}},{handler:Qz,method:`GET`,skipBodyParse:!0});function Ts(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let Ds=q(ai,async(e,t,n)=>{try{if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:lI});return}if(!Xz(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:lI});return}let e=await Uhe(M,n.branch,n.path,n.kind,{credentialConfig:Dc(ae,{resetAmbient:QF(M)})});J(t,200,Zr,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:Ts(n.path,e.renamedTo,n.contentRootDepth),{handler:lI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:lI,cause:e})}},{handler:lI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:lI})}),Os=q(hte,async(e,t,n)=>{if(pO(n,ce).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:rB});return}if(!M){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:rB});return}try{J(t,200,at,await Tc(()=>aB(M,n.branch,{fastForward:n.fastForward===!0,credentialConfig:Dc(ae,{resetAmbient:QF(M)})})),{handler:rB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:rB,cause:e})}},{handler:rB,method:`POST`});async function ks(e){let[t,...n]=ae,r=[...n,...e];return await new Promise((e,n)=>{let i=lu(t,r,Dw({...Fr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},nI),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 ${nI}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=cI(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 As=q(Gr,async(e,t)=>{if(!Me.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:$F,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ks([`share`,`owners`,`--json`]),n=Ihe(aI(e));sI(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,ree,n,{handler:$F})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:$F,cause:e})}finally{Me.release(`/api/share/publish/owners`)}},{handler:$F,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:$F})}),Ms=q(Gr,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!iI(r)||!rI(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:eI});return}if(!Me.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:eI,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ks([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Lhe(aI(e));sI(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Kt,n,{handler:eI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:eI,cause:e})}finally{Me.release(`/api/share/publish/name-check`)}},{handler:eI,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:eI})}),Ns=q(Yee,async(e,t,n)=>{if(!M){sI(`publish-create`,`no-project`),J(t,200,pn,{ok:!1,error:`no-project`},{handler:tI});return}if(!iI(n.owner)||!rI(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:tI});return}if(!Me.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:tI,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,M,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await ks(e),i=Bhe(aI(r));sI(`publish-create`,i.ok?`ok`:i.error),i.ok&&j?.()?.refreshRemote().catch(()=>{}),J(t,200,pn,i,{handler:tI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:tI,cause:e})}finally{Me.release(`/api/share/publish`)}},{handler:tI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:tI})}),Ps=q($ee,async(e,t,n)=>{try{let e=F(`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,Eee,{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`})}),Fs=`local-op-embeddings-set-key`,Is=`local-op-embeddings-clear-key`,Ls=`/api/local-op/embeddings`;function Rs(){let e=we?.();return{projectDir:M??c,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let zs=q(bt,async(e,t,n)=>{if(!Me.tryAcquire(Ls)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Fs,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Rs();await new pM(Ce).setForProject(e,r,n.key),N?.reloadCredential(),J(t,200,Ot,{keyPresent:!0},{handler:Fs,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Fs,cause:e})}finally{Me.release(Ls)}},{handler:Fs,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Fs})}),Bs=q(Gr,async(e,t)=>{if(!Me.tryAcquire(Ls)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Is,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Rs();await new pM(Ce).clearForProject(e,n),N?.reloadCredential(),J(t,200,Ot,{keyPresent:!1},{handler:Is,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Is,cause:e})}finally{Me.release(Ls)}},{handler:Is,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Is})}),Vs=`local-op-embeddings-test`,Hs=`/api/local-op/embeddings/test`,Ws=q(Gr,async(e,t)=>{if(!Me.tryAcquire(Hs)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Vs,extraHeaders:{"Retry-After":`5`}});return}try{let e=we?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await oM(new pM(Ce),M??c,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Ufe({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,aee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Vs,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Vs,cause:e})}finally{Me.release(Hs)}},{handler:Vs,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Vs})}),Gs=0;function Ks(){Gs+=1,je?.(`lint-config`)}let qs=()=>`${Gs} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function Js(e,t){let n=Te?.()??Lo;try{let r=await _a(e,iF(c,n,{docName:t,projectDir:M??c,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ee?.()??`warning`;if(k&&a!==`off`&&!hS(t)){await wt(t,e,`lint-validation`);let r=PF({projectDir:M??c,contentDir:c,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:vt,docFilePathFor:e=>ZX(c,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:ZX(c,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}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Xs(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=sF({projectDir:M??c,contentDir:c});return DP(t.schemas,n)}let Zs=q(Sn,async(e,t,n)=>{let r;try{r=_F(z(c),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}Ks();try{let e=Te?.()??Lo,n=[],r=tF(c,void 0,e=>n.push(e)),i=rF(M??c,nF(e,r),e=>n.push(e));n.push(...Xs(i)),J(t,200,zn,{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`}),Qs=q(Je,async(e,t,n)=>{let r;try{let e=z(M??c),t=n.parentPath??[];r=n.delete?Gme(e,n.file):n.field!==void 0&&n.removeField?Ume(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Wme(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Vme(e,n.file,n.field,n.constraint,t):Hme(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`)&&je?.(`files`),Ks();try{let e=Te?.()??Lo,n=[],r=tF(c,void 0,e=>n.push(e)),i=rF(M??c,nF(e,r),e=>n.push(e));n.push(...Xs(i)),J(t,200,zn,{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`}),$s=q(Ft,async(t,n,r)=>{try{let t=WX(r.docName,n,`lint-fix`);if(t===null)return;let i=nt(t),a=pO(r,ce);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(cS(i)||lS(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=ZX(c,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}sN(z(c,f),c);let p=Te?.()??Lo,{stored:m}=wn(a.summary),h=await s.getSession(i,o,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),_=[],{cfg:v,before:y,fixed:b,ran:x,failures:S}=await Rme({projectDir:M??c,contentDir:c,baseConfig:p,docRelPath:f,source:g,onConfigProblem:e=>_.push(e)}),C=y,w,T=[];if(b!==g){try{let t=hs(d),n=hi[t]??Ss(u??o);re?.setPresence(o,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{gw(h.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,mw(h))},h.origin),a.kind!==`anonymous`&&Hj(i,o,l,u,void 0,a.kind===`agent`?Cn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{re?.touchMode(o,`idle`)}let t=await ut(i);if(t?.kind===`failure`){dt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){mt(n,`lint-fix`);return}lt(i,`lint-fix`);try{C=await _a(h.dc.document.getText(`source`).toString(),v,f,e=>T.push(e))}catch(e){w=`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`),C=y}}let E=C.filter(e=>e.severity===`error`).length,D=C.length-E,O=Math.max(0,y.length-C.length),ee=[..._,...gs([...S,...T]),...w?[w]:[]];J(n,200,rn,{file:f,fixedCount:O,diagnostics:C,errorCount:E,warningCount:D,ran:x,...ee.length>0?{warnings:ee}:{},...w?{warning:w}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof QM){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof kS){AS(n,e,`lint-fix`);return}if(e instanceof PS){LS(n,e,`lint-fix`);return}if(e instanceof Cw){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`}),ec=bfe({service:Ue,getPrincipal:ce,onChanged:()=>je?.(`comments`)}),tc={"/api/comments":fK({GET:ec.list,POST:ec.create},{handler:`comments`}),"/api/comment":fK({GET:ec.read,POST:ec.mutate,DELETE:ec.remove},{handler:`comment`}),"/api/asset":dr,"/api/asset-text":pr,"/api/folder-config":la,"/api/template":ba,"/api/template/import":xa,"/api/skill":Oo,"/api/skill-file":Io,"/api/skill-file/rename":Ro,"/api/skills":ho,"/api/skill/import":Qo,"/api/skills/import-bulk":$o,"/api/skill/edit-external":wo,"/api/skill/duplicate":Do,"/api/skill/move-scope":Eo,"/api/skill-upload":ss,"/api/skill/install":cs,"/api/skill/uninstall":ls,"/api/skill/restore":us,"/api/skill/reimport":ds,"/api/skills/reimport-bulk":fs,"/api/skill/revert":ps,"/api/skill/track-in-git":po,"/api/lint/markdownlint-config":Zs,"/api/lint/frontmatter-schema":Qs,"/api/lint/fix":$s,"/api/create-page":mr,"/api/create-folder":gr,"/api/duplicate-path":_r,"/api/rename-path":vr,"/api/delete-path":yr,"/api/trash/cleanup":xr,"/api/upload":wr,"/api/agent-write":Wn,"/api/agent-write-md":Gn,"/api/agent-write-batch":Kn,"/api/frontmatter-patch":qn,"/api/agent-patch":Jn,"/api/agent-undo":Yn,"/api/agent-activity":Xn,"/api/agent-burst-diff":Zn,"/api/save-version":ar,"/api/rollback":or,"/api/share/construct-url":Cs,"/api/share/target-status":Ds,"/api/git/branch-info":ws,"/api/git/worktree-status":Ui,"/api/git/checkout":Os,"/api/share/publish/owners":As,"/api/share/publish/name-check":Ms,"/api/share/publish":Ns,"/api/sync/status":Bi,"/api/sync/trigger":Wi,"/api/sync/conflicts":Yi,"/api/sync/conflict-content":Zi,"/api/sync/resolve-conflict":Xi,"/api/sync/resolve-blocking":Ki,"/api/local-op/clone":Rr,"/api/local-op/ok-init":Wr,"/api/local-op/auth/login":_i,"/api/local-op/auth/status":Ei,"/api/local-op/auth/pat":Oi,"/api/local-op/auth/gh-login":xi,"/api/local-op/auth/cancel":Ci,"/api/local-op/auth/repos":Ai,"/api/local-op/auth/signout":Ii,"/api/local-op/auth/set-identity":zi,"/api/local-op/embeddings/set-key":zs,"/api/local-op/embeddings/clear-key":Bs,"/api/local-op/embeddings/test":Ws,"/api/spawn-cursor":xs,"/api/handoff":vs,"/api/install-skill":na,"/api/seed/plan":Qi,"/api/seed/apply":$i,"/api/seed/install-pack-skill":ea,"/api/seed/packs":ta,"/api/client-logs":Ps};C&&(tc[`/api/test-reset`]=$n,tc[`/api/test-flush-git`]=Qn,tc[`/api/test-rescan-backlinks`]=er,tc[`/api/test-rescan-files`]=nr);let rc=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/sync/resolve-blocking./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/skills/reimport-bulk./api/skill/revert./api/skill/track-in-git./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),ic=[`/api/local-op/`],ac=qB({log:X,policy:n,ephemeral:De,table:{resolve(e){let t=tc[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>rc.has(e)||ic.some(t=>e.startsWith(t))}}),oc=[sK({hocuspocus:o,derivedDocumentIndex:k,getFileIndex:f,isSafeDocName:cZ,readPageTitleForDocName:We,readPageTitleForLinkedDocName:Ke,readFrontmatterMetadataForLinkedDocName:$e,collectAdmittedDocNames:vt,resolveAlias:nt,respondToDerivedIndexQueryFailure:Dt}),pK({hocuspocus:o,agentPresenceBroadcaster:re,isAllowedWorkspaceHostHeader:i,log:X}),Ne,rV({contentDir:c,projectDir:M,ephemeral:De,log:X,ready:ve,durabilityState:t,serverInstanceId:d,getDiskAckSVs:O,getCollabClientCount:ee,getConfigDiagnostics:Ae,acpRegistry:fe,loadAcpCustomAgents:pe,acpHarnessAvailability:me,isRoutePeerAdmitted:a,isAllowedWorkspaceHostHeader:i,checkLocalOpSecurity:r,getPrincipal:ce,semanticSearch:N,readSemanticProviderConfig:we,embeddingsSecretsFile:Ce,getFileIndex:f,shadowRef:w,getCurrentBranch:D,installedAgentsCache:P}),cK({hocuspocus:o,contentDir:c,projectDir:M,contentFilter:he,isSafeDocName:cZ,resolveDocFilePath:ZX,isValidRelativeContentPath:HX,streamShowAllEntries:VX,getLinterBaseConfig:Te,getLinksValidationSetting:Ee,derivedDocumentIndex:k,collectAdmittedDocNames:vt,unmatchedGlobProblems:Xs,readAuditGeneration:qs}),$H({contentRoot:te,log:X,shadowRef:w,flushGitCommit:T,commitOkArtifactWrite:Un,getCurrentBranch:D,validateFolderRel:ra,safeDocPath:MX,docTreePathCandidates:NX}),mK({contentDir:c,projectDir:M,homeDirOverride:le,skillsHome:Ea,isSafeDocName:cZ,commentService:Ue,enumerateInstalledSkillsCached:In,checkLocalOpSecurity:r}),WK({log:X,skillsHome:Ea,projectDir:M,contentDir:c,resolveSkillDirForRead:ka}),V_e({contentDir:c,projectDir:M,skillsHome:Ea,homeDirOverride:le,savedThemeLockTimeoutMs:ue,ephemeral:De,log:X,signalChannel:je,searchService:ms,linkPreviewFetch:Oe,getLinkPreviewsEnabled:ke,getGeneratedIndexSettingsStatus:l,setGeneratedIndexEnabled:u})],cc=oc.flatMap(e=>[...e.paths]);PG(cc,tc);let fc=oc.map(e=>qB({log:X,policy:n,ephemeral:De,table:e.table})),pc={paths:cc,dispatch:async(e,t)=>{for(let n of fc)if(await n(e,t))return!0;return!1}},hc=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]),_c=oc.map(e=>e.table),vc=e=>{for(let t of _c){let n=t.resolve(e)?.dispatch;if(n!==void 0)return n}};for(let e of hc)if(tc[e]===void 0&&vc(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await ac(e,t)},nativeApi:pc,localApi:dK({resolve:e=>{if(!hc.has(e))return;let t=tc[e];return t===void 0?vc(e):t}})}}function uZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=mu(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!IB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!RB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:jB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=nX(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=De.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function dZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function axe(e){let t;try{t=Nu(e.contentDir,{withFileTypes:!0})}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Yx(n.name,ve)&&e.basenameIndex.add(n.name)}async function fZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Xu(i,{withFileTypes:!0})}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=rN(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await Ju(a)}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Zu(a)}catch(t){let n=dZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!iN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Qu(i)}catch(t){let n=dZ(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()&&Yx(a,de)&&!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()&&Yx(a,de)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const pZ=P({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:O().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),mZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function hZ(e){return mZ.includes(e)}function gZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function oxe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!hZ(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 _Z=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=gZ(e,this.payload)}};function vZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=pZ.safeParse(t);return n.success?n.data:void 0}var yZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function bZ(e,t,n=``){e=ene(`.`,e);let r=Qte(e),i=0,a,o;for(;i<r.length;i++)a=ad(e,r[i]),o=$te(a),o.isDirectory()?bZ(a,t,ad(n,r[i])):t(ad(n,r[i]),a,o)}function sxe(e){let t=e.url;if(t==null)return;let n=e._parsedUrl;if(n&&n.raw===t)return n;let r=t,i=``,a,o;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(o=t.substring(e),r=t.substring(0,e)),e=r.indexOf(`?`,1),e!==-1&&(i=r.substring(e),r=r.substring(0,e),i.length>1&&(a=fne.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const cxe=()=>{};function lxe(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function xZ(e,t){let n=0,r,i=e.length-1;e.charCodeAt(i)===47&&(e=e.substring(0,i));let a=[],o=`${e}/index`;for(;n<t.length;n++)r=t[n]?`.${t[n]}`:``,e&&a.push(e+r),a.push(o+r);return a}function uxe(e,t,n){let r=0,i,a=xZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function dxe(e,t,n,r){let i=0,a=xZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=gu(L(e,c=a[i])),o.startsWith(e)&&xu.existsSync(o)){if(s=xu.statSync(o),s.isDirectory())continue;return l=SZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function fxe(e,t){return t.statusCode=404,t.end()}function pxe(e,t,n,r,i){let a=200,o,s={};i={...i};for(let e in i)o=t.getHeader(e),o&&(i[e]=o);if((o=t.getHeader(`content-type`))&&(i[`Content-Type`]=o),e.headers.range){a=206;let[n,o]=e.headers.range.replace(`bytes=`,``).split(`-`),c=s.end=parseInt(o,10)||r.size-1,l=s.start=parseInt(n,10)||0;if(c>=r.size&&(c=r.size-1),l>=r.size)return t.setHeader(`Content-Range`,`bytes */${r.size}`),t.statusCode=416,t.end();i[`Content-Range`]=`bytes ${l}-${c}/${r.size}`,i[`Content-Length`]=c-l+1,i[`Accept-Ranges`]=`bytes`}t.writeHead(a,i),xu.createReadStream(n,s).pipe(t)}const mxe={".br":`br`,".gz":`gzip`};function SZ(e,t,n){let r=mxe[e.slice(-3)],i=pbe(e.slice(0,r&&-3))||``;i===`text/html`&&(i+=`;charset=utf-8`);let a={"Content-Length":t.size,"Content-Type":i,"Last-Modified":t.mtime.toUTCString()};return r&&(a[`Content-Encoding`]=r),n&&(a.ETag=`W/"${t.size}-${t.mtime.getTime()}"`),a}function CZ(e,t={}){e=z(e||`.`);let n=t.onNoMatch||fxe,r=t.setHeaders||cxe,i=t.extensions||[`html`,`htm`],a=t.gzip&&i.map(e=>`${e}.gz`).concat(`gz`),o=t.brotli&&i.map(e=>`${e}.br`).concat(`br`),s={},c=`/`,l=!!t.etag,u=!!t.single;if(typeof t.single==`string`){let e=t.single.lastIndexOf(`.`);c+=~e?t.single.substring(0,e):t.single}let d=[];t.ignores!==!1&&(d.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),t.dotfiles?d.push(/\/\.\w/):d.push(/\/\.well-known/),[].concat(t.ignores||[]).forEach(e=>{d.push(new RegExp(e,`i`))}));let f=t.maxAge!=null&&`public,max-age=${t.maxAge}`;f&&t.immutable?f+=`,immutable`:f&&t.maxAge===0&&(f+=`,must-revalidate`),t.dev||bZ(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=SZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?dxe.bind(0,e+B,l):uxe.bind(0,s);return function(e,t,s){let f=[``],m=sxe(e).pathname,h=e.headers[`accept-encoding`]||``;if(a&&h.includes(`gzip`)&&f.unshift(...a),o&&/(br|brotli)/i.test(h)&&f.unshift(...o),f.push(...i),m.indexOf(`%`)!==-1)try{m=decodeURI(m)}catch{}let g=p(m,f)||u&&!lxe(m,d)&&p(c,f);if(!g)return s?s():n(e,t);if(l&&e.headers[`if-none-match`]===g.headers.ETag)return t.writeHead(304),t.end();(a||o)&&t.setHeader(`Vary`,`Accept-Encoding`),r(t,m,g.stats),pxe(e,t,g.abs,g.stats,g.headers)}}const wZ=F(`conflict-storage`);var TZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(KO(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){wZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){wZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);V(e)||Ou(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Bu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return wZ.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){let r=this.conflicts.find(t=>t.file===e);if(!r)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-Bh1alj7a.mjs`),a=i(this.projectDir,{credentialConfig:[]});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!iN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);SL(r,t,{allowShareableOkArtifact:rP}),gc(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),wZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Xb(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){wZ.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}),wZ.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){let r=z(this.projectDir),i=z(r,e.file);if(!iN(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(SL(i,r,{allowShareableOkArtifact:rP}),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-Bh1alj7a.mjs`),n=await t(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,e.theirsSha]);SL(i,r,{allowShareableOkArtifact:rP}),gc(i,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);gc(i,n,`utf-8`);break;case`delete`:V(i)&&nc(i);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function hxe(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 gxe(e,t){let n=KO(e);try{Ou(n,{recursive:!0}),Bu(L(n,Ce),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=vte(e);Ou(I(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`};Bu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const EZ=new Map;let DZ=!1;function _xe(e,t){try{let n=hxe(e,t);for(let e of EZ.keys())gxe(e,n)}catch{}}function vxe(e){EZ.set(e,(EZ.get(e)??0)+1),DZ||(DZ=!0,process.on(`uncaughtExceptionMonitor`,_xe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=EZ.get(e)??0;n<=1?EZ.delete(e):EZ.set(e,n-1)}}}function OZ(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function kZ(e){let t=e.scheduler??ba,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!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 l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??OZ(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function AZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function jZ(e){if(!V(e))return{};let t;try{t=(0,ZD.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(!AZ(t))return{};let n=t.telemetry;if(!AZ(n))return{};let r=n.localSink;return AZ(r)?r:{}}function MZ(e){return typeof e==`boolean`?e:void 0}function yxe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function NZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function PZ(e){if(AZ(e))return yxe(e.maxBytes)}function bxe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=jZ(Vs(`project`,e.projectDir)),n=jZ(Vs(`project-local`,e.projectDir));if((MZ(n.enabled)??MZ(t.enabled)??!0)===!1)return null;let r=PZ(n.spans)??PZ(t.spans)??52428800,i=PZ(n.logs)??PZ(t.logs)??26214400,a=NZ(n.attributeDenylist)??NZ(t.attributeDenylist)??h;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var FZ;(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})(FZ||={});var xxe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(xxe||={});const IZ=FZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),LZ=e=>{switch(typeof e){case`undefined`:return IZ.undefined;case`string`:return IZ.string;case`number`:return Number.isNaN(e)?IZ.nan:IZ.number;case`boolean`:return IZ.boolean;case`function`:return IZ.function;case`bigint`:return IZ.bigint;case`symbol`:return IZ.symbol;case`object`:return Array.isArray(e)?IZ.array:e===null?IZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?IZ.promise:typeof Map<`u`&&e instanceof Map?IZ.map:typeof Set<`u`&&e instanceof Set?IZ.set:typeof Date<`u`&&e instanceof Date?IZ.date:IZ.object;default:return IZ.unknown}},Z=FZ.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 RZ=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,FZ.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()}};RZ.create=e=>new RZ(e);const zZ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===IZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,FZ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${FZ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${FZ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${FZ.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}"`:FZ.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,FZ.assertNever(e)}return{message:n}};let Sxe=zZ;function BZ(){return Sxe}const VZ=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 HZ(e,t){let n=BZ(),r=VZ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===zZ?void 0:zZ].filter(e=>!!e)});e.common.issues.push(r)}var UZ=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 WZ;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 WZ;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 WZ=Object.freeze({status:`aborted`}),GZ=e=>({status:`dirty`,value:e}),KZ=e=>({status:`valid`,value:e}),qZ=e=>e.status===`aborted`,JZ=e=>e.status===`dirty`,YZ=e=>e.status===`valid`,XZ=e=>typeof Promise<`u`&&e instanceof Promise;var ZZ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(ZZ||={});var QZ=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 $Z=(e,t)=>{if(YZ(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 RZ(e.common.issues);return this._error=t,this._error}}};function eQ(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 tQ=class{get description(){return this._def.description}_getType(e){return LZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:LZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new UZ,ctx:{common:e.parent.common,data:e.data,parsedType:LZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(XZ(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:LZ(e)};return $Z(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:LZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return YZ(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=>YZ(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:LZ(e)},r=this._parse({data:e,path:n.path,parent:n});return $Z(n,await(XZ(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 NQ({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 PQ.create(this,this._def)}nullable(){return FQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return _Q.create(this)}promise(){return MQ.create(this,this._def)}or(e){return bQ.create([this,e],this._def)}and(e){return CQ.create(this,e,this._def)}transform(e){return new NQ({...eQ(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new IQ({...eQ(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new zQ({typeName:Q.ZodBranded,type:this,...eQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new LQ({...eQ(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 BQ.create(this,e)}readonly(){return VQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Cxe=/^c[^\s-]{8,}$/i,wxe=/^[0-9a-z]+$/,Txe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Exe=/^[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,Dxe=/^[a-z0-9_-]{21}$/i,Oxe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,kxe=/^[-+]?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)?)??$/,Axe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let nQ;const jxe=/^(?:(?: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])$/,Mxe=/^(?:(?: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])$/,Nxe=/^(([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]))$/,Pxe=/^(([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])$/,Fxe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ixe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,rQ=`((\\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])))`,Lxe=RegExp(`^${rQ}$`);function iQ(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 Rxe(e){return RegExp(`^${iQ(e)}$`)}function zxe(e){let t=`${rQ}T${iQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Bxe(e,t){return!!((t===`v4`||!t)&&jxe.test(e)||(t===`v6`||!t)&&Nxe.test(e))}function Vxe(e,t){if(!Oxe.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 Hxe(e,t){return!!((t===`v4`||!t)&&Mxe.test(e)||(t===`v6`||!t)&&Pxe.test(e))}var aQ=class e extends tQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==IZ.string){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.string,received:t.parsedType}),WZ}let t=new UZ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),HZ(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),HZ(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?HZ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&HZ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Axe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)nQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),nQ.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Exe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Dxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Cxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)wxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Txe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(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),HZ(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),HZ(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),HZ(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),HZ(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),HZ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?zxe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Lxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Rxe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?kxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Bxe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Vxe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Hxe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Fxe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ixe.test(e.data)||(n=this._getOrReturnCtx(e,n),HZ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):FZ.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,...ZZ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...ZZ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...ZZ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...ZZ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...ZZ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...ZZ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...ZZ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...ZZ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...ZZ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...ZZ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...ZZ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...ZZ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...ZZ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...ZZ.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,...ZZ.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,...ZZ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...ZZ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...ZZ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...ZZ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...ZZ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...ZZ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...ZZ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...ZZ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...ZZ.errToObj(t)})}nonempty(e){return this.min(1,ZZ.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}};aQ.create=e=>new aQ({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...eQ(e)});function Uxe(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 oQ=class e extends tQ{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)!==IZ.number){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.number,received:t.parsedType}),WZ}let t,n=new UZ;for(let r of this._def.checks)r.kind===`int`?FZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),HZ(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),HZ(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),HZ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Uxe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),HZ(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),HZ(t,{code:Z.not_finite,message:r.message}),n.dirty()):FZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,ZZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,ZZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,ZZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,ZZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ZZ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:ZZ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:ZZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:ZZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:ZZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:ZZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:ZZ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:ZZ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:ZZ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:ZZ.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`&&FZ.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)}};oQ.create=e=>new oQ({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...eQ(e)});var sQ=class e extends tQ{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)!==IZ.bigint)return this._getInvalidInput(e);let t,n=new UZ;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),HZ(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),HZ(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),HZ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):FZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.bigint,received:t.parsedType}),WZ}gte(e,t){return this.setLimit(`min`,e,!0,ZZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,ZZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,ZZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,ZZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:ZZ.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:ZZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:ZZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:ZZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:ZZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:ZZ.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}};sQ.create=e=>new sQ({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...eQ(e)});var cQ=class extends tQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==IZ.boolean){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.boolean,received:t.parsedType}),WZ}return KZ(e.data)}};cQ.create=e=>new cQ({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...eQ(e)});var lQ=class e extends tQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==IZ.date){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.date,received:t.parsedType}),WZ}if(Number.isNaN(e.data.getTime()))return HZ(this._getOrReturnCtx(e),{code:Z.invalid_date}),WZ;let t=new UZ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),HZ(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),HZ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):FZ.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:ZZ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:ZZ.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)}};lQ.create=e=>new lQ({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...eQ(e)});var uQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.symbol){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.symbol,received:t.parsedType}),WZ}return KZ(e.data)}};uQ.create=e=>new uQ({typeName:Q.ZodSymbol,...eQ(e)});var dQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.undefined){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.undefined,received:t.parsedType}),WZ}return KZ(e.data)}};dQ.create=e=>new dQ({typeName:Q.ZodUndefined,...eQ(e)});var fQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.null){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.null,received:t.parsedType}),WZ}return KZ(e.data)}};fQ.create=e=>new fQ({typeName:Q.ZodNull,...eQ(e)});var pQ=class extends tQ{constructor(){super(...arguments),this._any=!0}_parse(e){return KZ(e.data)}};pQ.create=e=>new pQ({typeName:Q.ZodAny,...eQ(e)});var mQ=class extends tQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return KZ(e.data)}};mQ.create=e=>new mQ({typeName:Q.ZodUnknown,...eQ(e)});var hQ=class extends tQ{_parse(e){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.never,received:t.parsedType}),WZ}};hQ.create=e=>new hQ({typeName:Q.ZodNever,...eQ(e)});var gQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.undefined){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.void,received:t.parsedType}),WZ}return KZ(e.data)}};gQ.create=e=>new gQ({typeName:Q.ZodVoid,...eQ(e)});var _Q=class e extends tQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==IZ.array)return HZ(t,{code:Z.invalid_type,expected:IZ.array,received:t.parsedType}),WZ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(HZ(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&&(HZ(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&&(HZ(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 QZ(t,e,t.path,n)))).then(e=>UZ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new QZ(t,e,t.path,n)));return UZ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:ZZ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:ZZ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:ZZ.toString(n)}})}nonempty(e){return this.min(1,e)}};_Q.create=(e,t)=>new _Q({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...eQ(t)});function vQ(e){if(e instanceof yQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=PQ.create(vQ(r))}return new yQ({...e._def,shape:()=>t})}else if(e instanceof _Q)return new _Q({...e._def,type:vQ(e.element)});else if(e instanceof PQ)return PQ.create(vQ(e.unwrap()));else if(e instanceof FQ)return FQ.create(vQ(e.unwrap()));else if(e instanceof wQ)return wQ.create(e.items.map(e=>vQ(e)));else return e}var yQ=class e extends tQ{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=FZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==IZ.object){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.object,received:t.parsedType}),WZ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof hQ&&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 QZ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof hQ){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&&(HZ(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 QZ(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=>UZ.mergeObjectSync(t,e)):UZ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return ZZ.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:ZZ.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 FZ.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 FZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return vQ(this)}partial(t){let n={};for(let e of FZ.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 FZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof PQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return kQ(FZ.objectKeys(this.shape))}};yQ.create=(e,t)=>new yQ({shape:()=>e,unknownKeys:`strip`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)}),yQ.strictCreate=(e,t)=>new yQ({shape:()=>e,unknownKeys:`strict`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)}),yQ.lazycreate=(e,t)=>new yQ({shape:e,unknownKeys:`strip`,catchall:hQ.create(),typeName:Q.ZodObject,...eQ(t)});var bQ=class extends tQ{_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 RZ(e.ctx.common.issues));return HZ(t,{code:Z.invalid_union,unionErrors:n}),WZ}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 RZ(e));return HZ(t,{code:Z.invalid_union,unionErrors:i}),WZ}}get options(){return this._def.options}};bQ.create=(e,t)=>new bQ({options:e,typeName:Q.ZodUnion,...eQ(t)});const xQ=e=>e instanceof DQ?xQ(e.schema):e instanceof NQ?xQ(e.innerType()):e instanceof OQ?[e.value]:e instanceof AQ?e.options:e instanceof jQ?FZ.objectValues(e.enum):e instanceof IQ?xQ(e._def.innerType):e instanceof dQ?[void 0]:e instanceof fQ?[null]:e instanceof PQ?[void 0,...xQ(e.unwrap())]:e instanceof FQ?[null,...xQ(e.unwrap())]:e instanceof zQ||e instanceof VQ?xQ(e.unwrap()):e instanceof LQ?xQ(e._def.innerType):[];var Wxe=class e extends tQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==IZ.object)return HZ(t,{code:Z.invalid_type,expected:IZ.object,received:t.parsedType}),WZ;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}):(HZ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),WZ)}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=xQ(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,...eQ(r)})}};function SQ(e,t){let n=LZ(e),r=LZ(t);if(e===t)return{valid:!0,data:e};if(n===IZ.object&&r===IZ.object){let n=FZ.objectKeys(t),r=FZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=SQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===IZ.array&&r===IZ.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=SQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===IZ.date&&r===IZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var CQ=class extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(qZ(e)||qZ(r))return WZ;let i=SQ(e.value,r.value);return i.valid?((JZ(e)||JZ(r))&&t.dirty(),{status:t.value,value:i.data}):(HZ(n,{code:Z.invalid_intersection_types}),WZ)};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}))}};CQ.create=(e,t,n)=>new CQ({left:e,right:t,typeName:Q.ZodIntersection,...eQ(n)});var wQ=class e extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==IZ.array)return HZ(n,{code:Z.invalid_type,expected:IZ.array,received:n.parsedType}),WZ;if(n.data.length<this._def.items.length)return HZ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),WZ;!this._def.rest&&n.data.length>this._def.items.length&&(HZ(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 QZ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>UZ.mergeArray(t,e)):UZ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new wQ({items:e,typeName:Q.ZodTuple,rest:null,...eQ(t)})};var Gxe=class e extends tQ{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!==IZ.object)return HZ(n,{code:Z.invalid_type,expected:IZ.object,received:n.parsedType}),WZ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new QZ(n,e,n.path,e)),value:a._parse(new QZ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?UZ.mergeObjectAsync(t,r):UZ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof tQ?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...eQ(r)}):new e({keyType:aQ.create(),valueType:t,typeName:Q.ZodRecord,...eQ(n)})}},TQ=class extends tQ{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!==IZ.map)return HZ(n,{code:Z.invalid_type,expected:IZ.map,received:n.parsedType}),WZ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new QZ(n,e,n.path,[a,`key`])),value:i._parse(new QZ(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 WZ;(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 WZ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};TQ.create=(e,t,n)=>new TQ({valueType:t,keyType:e,typeName:Q.ZodMap,...eQ(n)});var EQ=class e extends tQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==IZ.set)return HZ(n,{code:Z.invalid_type,expected:IZ.set,received:n.parsedType}),WZ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(HZ(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&&(HZ(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 WZ;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 QZ(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:ZZ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:ZZ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};EQ.create=(e,t)=>new EQ({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...eQ(t)});var Kxe=class e extends tQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==IZ.function)return HZ(t,{code:Z.invalid_type,expected:IZ.function,received:t.parsedType}),WZ;function n(e,n){return VZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,BZ(),zZ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return VZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,BZ(),zZ].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 MQ){let e=this;return KZ(async function(...t){let o=new RZ([]),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 KZ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new RZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new RZ([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:wQ.create(t).rest(mQ.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||wQ.create([]).rest(mQ.create()),returns:n||mQ.create(),typeName:Q.ZodFunction,...eQ(r)})}},DQ=class extends tQ{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})}};DQ.create=(e,t)=>new DQ({getter:e,typeName:Q.ZodLazy,...eQ(t)});var OQ=class extends tQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return HZ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),WZ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};OQ.create=(e,t)=>new OQ({value:e,typeName:Q.ZodLiteral,...eQ(t)});function kQ(e,t){return new AQ({values:e,typeName:Q.ZodEnum,...eQ(t)})}var AQ=class e extends tQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return HZ(t,{expected:FZ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),WZ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return HZ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),WZ}return KZ(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})}};AQ.create=kQ;var jQ=class extends tQ{_parse(e){let t=FZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==IZ.string&&n.parsedType!==IZ.number){let e=FZ.objectValues(t);return HZ(n,{expected:FZ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),WZ}if(this._cache||=new Set(FZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=FZ.objectValues(t);return HZ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),WZ}return KZ(e.data)}get enum(){return this._def.values}};jQ.create=(e,t)=>new jQ({values:e,typeName:Q.ZodNativeEnum,...eQ(t)});var MQ=class extends tQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==IZ.promise&&t.common.async===!1?(HZ(t,{code:Z.invalid_type,expected:IZ.promise,received:t.parsedType}),WZ):KZ((t.parsedType===IZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};MQ.create=(e,t)=>new MQ({type:e,typeName:Q.ZodPromise,...eQ(t)});var NQ=class extends tQ{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=>{HZ(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 WZ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?WZ:r.status===`dirty`||t.value===`dirty`?GZ(r.value):r});{if(t.value===`aborted`)return WZ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?WZ:r.status===`dirty`||t.value===`dirty`?GZ(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`?WZ:(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`?WZ:(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(!YZ(e))return WZ;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=>YZ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):WZ);FZ.assertNever(r)}};NQ.create=(e,t,n)=>new NQ({schema:e,typeName:Q.ZodEffects,effect:t,...eQ(n)}),NQ.createWithPreprocess=(e,t,n)=>new NQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...eQ(n)});var PQ=class extends tQ{_parse(e){return this._getType(e)===IZ.undefined?KZ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};PQ.create=(e,t)=>new PQ({innerType:e,typeName:Q.ZodOptional,...eQ(t)});var FQ=class extends tQ{_parse(e){return this._getType(e)===IZ.null?KZ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};FQ.create=(e,t)=>new FQ({innerType:e,typeName:Q.ZodNullable,...eQ(t)});var IQ=class extends tQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===IZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};IQ.create=(e,t)=>new IQ({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...eQ(t)});var LQ=class extends tQ{_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 XZ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new RZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new RZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};LQ.create=(e,t)=>new LQ({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...eQ(t)});var RQ=class extends tQ{_parse(e){if(this._getType(e)!==IZ.nan){let t=this._getOrReturnCtx(e);return HZ(t,{code:Z.invalid_type,expected:IZ.nan,received:t.parsedType}),WZ}return{status:`valid`,value:e.data}}};RQ.create=e=>new RQ({typeName:Q.ZodNaN,...eQ(e)});var zQ=class extends tQ{_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}},BQ=class e extends tQ{_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`?WZ:e.status===`dirty`?(t.dirty(),GZ(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`?WZ: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})}},VQ=class extends tQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(YZ(e)&&(e.value=Object.freeze(e.value)),e);return XZ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};VQ.create=(e,t)=>new VQ({innerType:e,typeName:Q.ZodReadonly,...eQ(t)}),yQ.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||={}),aQ.create,oQ.create,RQ.create,sQ.create,cQ.create,lQ.create,uQ.create,dQ.create,fQ.create,pQ.create,mQ.create,hQ.create,gQ.create,_Q.create;const qxe=yQ.create;yQ.strictCreate,bQ.create,Wxe.create,CQ.create,wQ.create,Gxe.create,TQ.create,EQ.create,Kxe.create,DQ.create,OQ.create,AQ.create,jQ.create,MQ.create,NQ.create,PQ.create,FQ.create,NQ.createWithPreprocess,BQ.create;const Jxe=le(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);r.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>fe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>we(e,t,n),e.parseAsync=async(t,n)=>Ne(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ke(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)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Yxe=le(`ZodMiniObject`,(e,t)=>{E.init(e,t),Jxe.init(e,t),Te(e,`shape`,()=>t.shape)});function HQ(e,t){return new Yxe({type:`object`,shape:e??{},...Ae(t)})}function UQ(e){return!!e._zod}function WQ(e){let t=Object.values(e);if(t.length===0)return HQ({});let n=t.every(UQ),r=t.every(e=>!UQ(e));if(n)return HQ(e);if(r)return qxe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function GQ(e,t){return UQ(e)?we(e,t):e.safeParse(t)}async function KQ(e,t){return UQ(e)?await ke(e,t):await e.safeParseAsync(t)}function qQ(e){if(!e)return;let t;if(t=UQ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function JQ(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 WQ(e)}}if(UQ(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 YQ(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 Xxe(e){return e.description}function Zxe(e){if(UQ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function XQ(e){if(UQ(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 ZQ=`2025-11-25`,QQ=[ZQ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],$Q=`io.modelcontextprotocol/related-task`,e$=be(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),t$=j([A(),O().int()]),n$=A();x({ttl:O().optional(),pollInterval:O().optional()});const Qxe=P({ttl:O().optional()}),$xe=P({taskId:A()}),r$=x({progressToken:t$.optional(),[$Q]:$xe.optional()}),i$=P({_meta:r$.optional()}),a$=i$.extend({task:Qxe.optional()}),eSe=e=>a$.safeParse(e).success,o$=P({method:A(),params:i$.loose().optional()}),s$=P({_meta:r$.optional()}),c$=P({method:A(),params:s$.loose().optional()}),l$=x({_meta:r$.optional()}),u$=j([A(),O().int()]),d$=P({jsonrpc:g(`2.0`),id:u$,...o$.shape}).strict(),f$=e=>d$.safeParse(e).success,p$=P({jsonrpc:g(`2.0`),...c$.shape}).strict(),tSe=e=>p$.safeParse(e).success,m$=P({jsonrpc:g(`2.0`),id:u$,result:l$}).strict(),h$=e=>m$.safeParse(e).success;var g$;(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`})(g$||={});const _$=P({jsonrpc:g(`2.0`),id:u$.optional(),error:P({code:O().int(),message:A(),data:f().optional()})}).strict(),v$=e=>_$.safeParse(e).success,y$=j([d$,p$,m$,_$]);j([m$,_$]);const b$=l$.strict(),nSe=s$.extend({requestId:u$.optional(),reason:A().optional()}),x$=c$.extend({method:g(`notifications/cancelled`),params:nSe}),S$=P({icons:N(P({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:d([`light`,`dark`]).optional()})).optional()}),C$=P({name:A(),title:A().optional()}),w$=C$.extend({...C$.shape,...S$.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),rSe=re(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,T(P({form:T(P({applyDefaults:a().optional()}),m(A(),f())).optional(),url:e$.optional()}),m(A(),f()).optional())),iSe=x({list:e$.optional(),cancel:e$.optional(),requests:x({sampling:x({createMessage:e$.optional()}).optional(),elicitation:x({create:e$.optional()}).optional()}).optional()}),aSe=x({list:e$.optional(),cancel:e$.optional(),requests:x({tools:x({call:e$.optional()}).optional()}).optional()}),oSe=P({experimental:m(A(),e$).optional(),sampling:P({context:e$.optional(),tools:e$.optional()}).optional(),elicitation:rSe.optional(),roots:P({listChanged:a().optional()}).optional(),tasks:iSe.optional(),extensions:m(A(),e$).optional()}),sSe=i$.extend({protocolVersion:A(),capabilities:oSe,clientInfo:w$}),T$=o$.extend({method:g(`initialize`),params:sSe}),E$=e=>T$.safeParse(e).success,cSe=P({experimental:m(A(),e$).optional(),logging:e$.optional(),completions:e$.optional(),prompts:P({listChanged:a().optional()}).optional(),resources:P({subscribe:a().optional(),listChanged:a().optional()}).optional(),tools:P({listChanged:a().optional()}).optional(),tasks:aSe.optional(),extensions:m(A(),e$).optional()}),lSe=l$.extend({protocolVersion:A(),capabilities:cSe,serverInfo:w$,instructions:A().optional()}),D$=c$.extend({method:g(`notifications/initialized`),params:s$.optional()}),uSe=e=>D$.safeParse(e).success,O$=o$.extend({method:g(`ping`),params:i$.optional()}),dSe=P({progress:O(),total:s(O()),message:s(A())}),fSe=P({...s$.shape,...dSe.shape,progressToken:t$}),k$=c$.extend({method:g(`notifications/progress`),params:fSe}),pSe=i$.extend({cursor:n$.optional()}),A$=o$.extend({params:pSe.optional()}),j$=l$.extend({nextCursor:n$.optional()}),mSe=d([`working`,`input_required`,`completed`,`failed`,`cancelled`]),M$=P({taskId:A(),status:mSe,ttl:j([O(),u()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:s(O()),statusMessage:s(A())}),N$=l$.extend({task:M$}),hSe=s$.merge(M$),P$=c$.extend({method:g(`notifications/tasks/status`),params:hSe}),F$=o$.extend({method:g(`tasks/get`),params:i$.extend({taskId:A()})}),I$=l$.merge(M$),L$=o$.extend({method:g(`tasks/result`),params:i$.extend({taskId:A()})});l$.loose();const R$=A$.extend({method:g(`tasks/list`)}),z$=j$.extend({tasks:N(M$)}),B$=o$.extend({method:g(`tasks/cancel`),params:i$.extend({taskId:A()})}),gSe=l$.merge(M$),V$=P({uri:A(),mimeType:s(A()),_meta:m(A(),f()).optional()}),H$=V$.extend({text:A()}),U$=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),W$=V$.extend({blob:U$}),G$=d([`user`,`assistant`]),K$=P({audience:N(G$).optional(),priority:O().min(0).max(1).optional(),lastModified:v({offset:!0}).optional()}),q$=P({...C$.shape,...S$.shape,uri:A(),description:s(A()),mimeType:s(A()),size:s(O()),annotations:K$.optional(),_meta:s(x({}))}),_Se=P({...C$.shape,...S$.shape,uriTemplate:A(),description:s(A()),mimeType:s(A()),annotations:K$.optional(),_meta:s(x({}))}),J$=A$.extend({method:g(`resources/list`)}),vSe=j$.extend({resources:N(q$)}),Y$=A$.extend({method:g(`resources/templates/list`)}),ySe=j$.extend({resourceTemplates:N(_Se)}),X$=i$.extend({uri:A()}),bSe=X$,Z$=o$.extend({method:g(`resources/read`),params:bSe}),xSe=l$.extend({contents:N(j([H$,W$]))}),SSe=c$.extend({method:g(`notifications/resources/list_changed`),params:s$.optional()}),CSe=X$,wSe=o$.extend({method:g(`resources/subscribe`),params:CSe}),TSe=X$,ESe=o$.extend({method:g(`resources/unsubscribe`),params:TSe}),DSe=s$.extend({uri:A()}),OSe=c$.extend({method:g(`notifications/resources/updated`),params:DSe}),kSe=P({name:A(),description:s(A()),required:s(a())}),ASe=P({...C$.shape,...S$.shape,description:s(A()),arguments:s(N(kSe)),_meta:s(x({}))}),Q$=A$.extend({method:g(`prompts/list`)}),jSe=j$.extend({prompts:N(ASe)}),MSe=i$.extend({name:A(),arguments:m(A(),A()).optional()}),$$=o$.extend({method:g(`prompts/get`),params:MSe}),e1=P({type:g(`text`),text:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),t1=P({type:g(`image`),data:U$,mimeType:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),n1=P({type:g(`audio`),data:U$,mimeType:A(),annotations:K$.optional(),_meta:m(A(),f()).optional()}),NSe=P({type:g(`tool_use`),name:A(),id:A(),input:m(A(),f()),_meta:m(A(),f()).optional()}),PSe=P({type:g(`resource`),resource:j([H$,W$]),annotations:K$.optional(),_meta:m(A(),f()).optional()}),r1=j([e1,t1,n1,q$.extend({type:g(`resource_link`)}),PSe]),FSe=P({role:G$,content:r1}),ISe=l$.extend({description:A().optional(),messages:N(FSe)}),LSe=c$.extend({method:g(`notifications/prompts/list_changed`),params:s$.optional()}),RSe=P({title:A().optional(),readOnlyHint:a().optional(),destructiveHint:a().optional(),idempotentHint:a().optional(),openWorldHint:a().optional()}),zSe=P({taskSupport:d([`required`,`optional`,`forbidden`]).optional()}),i1=P({...C$.shape,...S$.shape,description:A().optional(),inputSchema:P({type:g(`object`),properties:m(A(),e$).optional(),required:N(A()).optional()}).catchall(f()),outputSchema:P({type:g(`object`),properties:m(A(),e$).optional(),required:N(A()).optional()}).catchall(f()).optional(),annotations:RSe.optional(),execution:zSe.optional(),_meta:m(A(),f()).optional()}),a1=A$.extend({method:g(`tools/list`)}),BSe=j$.extend({tools:N(i1)}),o1=l$.extend({content:N(r1).default([]),structuredContent:m(A(),f()).optional(),isError:a().optional()});o1.or(l$.extend({toolResult:f()}));const VSe=a$.extend({name:A(),arguments:m(A(),f()).optional()}),s1=o$.extend({method:g(`tools/call`),params:VSe}),HSe=c$.extend({method:g(`notifications/tools/list_changed`),params:s$.optional()});P({autoRefresh:a().default(!0),debounceMs:O().int().nonnegative().default(300)});const c1=d([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),USe=i$.extend({level:c1}),l1=o$.extend({method:g(`logging/setLevel`),params:USe}),WSe=s$.extend({level:c1,logger:A().optional(),data:f()}),GSe=c$.extend({method:g(`notifications/message`),params:WSe}),KSe=P({hints:N(P({name:A().optional()})).optional(),costPriority:O().min(0).max(1).optional(),speedPriority:O().min(0).max(1).optional(),intelligencePriority:O().min(0).max(1).optional()}),qSe=P({mode:d([`auto`,`required`,`none`]).optional()}),JSe=P({type:g(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(r1).default([]),structuredContent:P({}).loose().optional(),isError:a().optional(),_meta:m(A(),f()).optional()}),YSe=S(`type`,[e1,t1,n1]),u1=S(`type`,[e1,t1,n1,NSe,JSe]),XSe=P({role:G$,content:j([u1,N(u1)]),_meta:m(A(),f()).optional()}),ZSe=a$.extend({messages:N(XSe),modelPreferences:KSe.optional(),systemPrompt:A().optional(),includeContext:d([`none`,`thisServer`,`allServers`]).optional(),temperature:O().optional(),maxTokens:O().int(),stopSequences:N(A()).optional(),metadata:e$.optional(),tools:N(i1).optional(),toolChoice:qSe.optional()}),QSe=o$.extend({method:g(`sampling/createMessage`),params:ZSe}),d1=l$.extend({model:A(),stopReason:s(d([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:G$,content:YSe}),f1=l$.extend({model:A(),stopReason:s(d([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:G$,content:j([u1,N(u1)])}),$Se=P({type:g(`boolean`),title:A().optional(),description:A().optional(),default:a().optional()}),eCe=P({type:g(`string`),title:A().optional(),description:A().optional(),minLength:O().optional(),maxLength:O().optional(),format:d([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),tCe=P({type:d([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:O().optional(),maximum:O().optional(),default:O().optional()}),nCe=P({type:g(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),rCe=P({type:g(`string`),title:A().optional(),description:A().optional(),oneOf:N(P({const:A(),title:A()})),default:A().optional()}),iCe=j([j([P({type:g(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),j([nCe,rCe]),j([P({type:g(`array`),title:A().optional(),description:A().optional(),minItems:O().optional(),maxItems:O().optional(),items:P({type:g(`string`),enum:N(A())}),default:N(A()).optional()}),P({type:g(`array`),title:A().optional(),description:A().optional(),minItems:O().optional(),maxItems:O().optional(),items:P({anyOf:N(P({const:A(),title:A()}))}),default:N(A()).optional()})])]),$Se,eCe,tCe]),aCe=j([a$.extend({mode:g(`form`).optional(),message:A(),requestedSchema:P({type:g(`object`),properties:m(A(),iCe),required:N(A()).optional()})}),a$.extend({mode:g(`url`),message:A(),elicitationId:A(),url:A().url()})]),oCe=o$.extend({method:g(`elicitation/create`),params:aCe}),sCe=s$.extend({elicitationId:A()}),cCe=c$.extend({method:g(`notifications/elicitation/complete`),params:sCe}),p1=l$.extend({action:d([`accept`,`decline`,`cancel`]),content:re(e=>e===null?void 0:e,m(A(),j([A(),O(),a(),N(A())])).optional())}),lCe=P({type:g(`ref/resource`),uri:A()}),uCe=P({type:g(`ref/prompt`),name:A()}),dCe=i$.extend({ref:j([uCe,lCe]),argument:P({name:A(),value:A()}),context:P({arguments:m(A(),A()).optional()}).optional()}),m1=o$.extend({method:g(`completion/complete`),params:dCe});function fCe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function pCe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const mCe=l$.extend({completion:x({values:N(A()).max(100),total:s(O().int()),hasMore:s(a())})}),hCe=P({uri:A().startsWith(`file://`),name:A().optional(),_meta:m(A(),f()).optional()}),gCe=o$.extend({method:g(`roots/list`),params:i$.optional()}),h1=l$.extend({roots:N(hCe)}),_Ce=c$.extend({method:g(`notifications/roots/list_changed`),params:s$.optional()});j([O$,T$,m1,l1,$$,Q$,J$,Y$,Z$,wSe,ESe,s1,a1,F$,L$,R$,B$]),j([x$,k$,D$,_Ce,P$]),j([b$,d1,f1,p1,h1,I$,z$,N$]),j([O$,QSe,oCe,gCe,F$,L$,R$,B$]),j([x$,k$,GSe,OSe,SSe,HSe,LSe,P$,cCe]),j([b$,lSe,mCe,ISe,jSe,vSe,ySe,xSe,o1,BSe,I$,z$,N$]);var g1=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===g$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new vCe(e.elicitations,n)}return new e(t,n,r)}},vCe=class extends g1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(g$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function _1(e){return e===`completed`||e===`failed`||e===`cancelled`}const yCe=Symbol(`Let zodToJsonSchema decide on which parser to use`),v1={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`},bCe=e=>typeof e==`string`?{...v1,name:e}:{...v1,...e},xCe=e=>{let t=bCe(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 y1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function b1(e,t,n,r,i){e[t]=n,y1(e,t,r,i)}const x1=(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 S1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?x1(t,e.currentPath):t.join(`/`)}}function SCe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=F1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&b1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&b1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(b1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),b1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function CCe(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?b1(n,`minimum`,r.value,r.message,t):b1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),b1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?b1(n,`maximum`,r.value,r.message,t):b1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),b1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:b1(n,`multipleOf`,r.value,r.message,t);break}return n}function wCe(){return{type:`boolean`}}function C1(e,t){return F1(e.type._def,t)}const TCe=(e,t)=>F1(e.innerType._def,t);function w1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>w1(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 ECe(e,t)}}const ECe=(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`:b1(n,`minimum`,r.value,r.message,t);break;case`max`:b1(n,`maximum`,r.value,r.message,t);break}return n};function DCe(e,t){return{...F1(e.innerType._def,t),default:e.defaultValue()}}function OCe(e,t){return t.effectStrategy===`input`?F1(e.schema._def,t):S1(t)}function kCe(e){return{type:`string`,enum:Array.from(e.values)}}const ACe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function jCe(e,t){let n=[F1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),F1(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(ACe(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 MCe(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 T1;const E1={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:()=>(T1===void 0&&(T1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),T1),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 D1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:b1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:b1(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`:k1(n,`email`,r.message,t);break;case`format:idn-email`:k1(n,`idn-email`,r.message,t);break;case`pattern:zod`:A1(n,E1.email,r.message,t);break}break;case`url`:k1(n,`uri`,r.message,t);break;case`uuid`:k1(n,`uuid`,r.message,t);break;case`regex`:A1(n,r.regex,r.message,t);break;case`cuid`:A1(n,E1.cuid,r.message,t);break;case`cuid2`:A1(n,E1.cuid2,r.message,t);break;case`startsWith`:A1(n,RegExp(`^${O1(r.value,t)}`),r.message,t);break;case`endsWith`:A1(n,RegExp(`${O1(r.value,t)}$`),r.message,t);break;case`datetime`:k1(n,`date-time`,r.message,t);break;case`date`:k1(n,`date`,r.message,t);break;case`time`:k1(n,`time`,r.message,t);break;case`duration`:k1(n,`duration`,r.message,t);break;case`length`:b1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),b1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:A1(n,RegExp(O1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&k1(n,`ipv4`,r.message,t),r.version!==`v4`&&k1(n,`ipv6`,r.message,t);break;case`base64url`:A1(n,E1.base64url,r.message,t);break;case`jwt`:A1(n,E1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&A1(n,E1.ipv4Cidr,r.message,t),r.version!==`v4`&&A1(n,E1.ipv6Cidr,r.message,t);break;case`emoji`:A1(n,E1.emoji(),r.message,t);break;case`ulid`:A1(n,E1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:k1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:b1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:A1(n,E1.base64,r.message,t);break}break;case`nanoid`:A1(n,E1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function O1(e,t){return t.patternStrategy===`escape`?PCe(e):e}const NCe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function PCe(e){let t=``;for(let n=0;n<e.length;n++)NCe.has(e[n])||(t+=`\\`),t+=e[n];return t}function k1(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}}})):b1(e,`format`,t,n,r)}function A1(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:j1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):b1(e,`pattern`,j1(t,r),n,r)}function j1(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
1188
1188
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1189
1189
  ]))`;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 M1(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]:F1(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??S1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:F1(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}=D1(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}=C1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function FCe(e,t){return t.mapStrategy===`record`?M1(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[F1(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||S1(t),F1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||S1(t)],minItems:2,maxItems:2}}}function ICe(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 LCe(e){return e.target===`openAi`?void 0:{not:S1({...e,currentPath:[...e.currentPath,`not`]})}}function RCe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const N1={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function zCe(e,t){if(t.target===`openApi3`)return P1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in N1&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=N1[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 P1(e,t)}const P1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>F1(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 BCe(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:N1[e.innerType._def.typeName],nullable:!0}:{type:[N1[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=F1(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=F1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function VCe(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`,y1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?b1(n,`minimum`,r.value,r.message,t):b1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),b1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?b1(n,`maximum`,r.value,r.message,t):b1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),b1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:b1(n,`multipleOf`,r.value,r.message,t);break}return n}function HCe(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=WCe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=F1(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=UCe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function UCe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return F1(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 WCe(e){try{return e.isOptional()}catch{return!0}}const GCe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return F1(e.innerType._def,t);let n=F1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:S1(t)},n]}:S1(t)},KCe=(e,t)=>{if(t.pipeStrategy===`input`)return F1(e.in._def,t);if(t.pipeStrategy===`output`)return F1(e.out._def,t);let n=F1(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,F1(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function qCe(e,t){return F1(e.type._def,t)}function JCe(e,t){let n={type:`array`,uniqueItems:!0,items:F1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&b1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&b1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function YCe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>F1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:F1(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>F1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function XCe(e){return{not:S1(e)}}function ZCe(e){return S1(e)}const QCe=(e,t)=>F1(e.innerType._def,t),$Ce=(e,t,n)=>{switch(t){case Q.ZodString:return D1(e,n);case Q.ZodNumber:return VCe(e,n);case Q.ZodObject:return HCe(e,n);case Q.ZodBigInt:return CCe(e,n);case Q.ZodBoolean:return wCe();case Q.ZodDate:return w1(e,n);case Q.ZodUndefined:return XCe(n);case Q.ZodNull:return RCe(n);case Q.ZodArray:return SCe(e,n);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return zCe(e,n);case Q.ZodIntersection:return jCe(e,n);case Q.ZodTuple:return YCe(e,n);case Q.ZodRecord:return M1(e,n);case Q.ZodLiteral:return MCe(e,n);case Q.ZodEnum:return kCe(e);case Q.ZodNativeEnum:return ICe(e);case Q.ZodNullable:return BCe(e,n);case Q.ZodOptional:return GCe(e,n);case Q.ZodMap:return FCe(e,n);case Q.ZodSet:return JCe(e,n);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return qCe(e,n);case Q.ZodNaN:case Q.ZodNever:return LCe(n);case Q.ZodEffects:return OCe(e,n);case Q.ZodAny:return S1(n);case Q.ZodUnknown:return ZCe(n);case Q.ZodDefault:return DCe(e,n);case Q.ZodBranded:return C1(e,n);case Q.ZodReadonly:return QCe(e,n);case Q.ZodCatch:return TCe(e,n);case Q.ZodPipeline:return KCe(e,n);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(e=>void 0)(t)}};function F1(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==yCe)return i}if(r&&!n){let e=ewe(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=$Ce(e,e.typeName,t),o=typeof a==`function`?F1(a(),t):a;if(o&&twe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const ewe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:x1(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`),S1(t)):t.$refStrategy===`seen`?S1(t):void 0}},twe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),nwe=(e,t)=>{let n=xCe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:F1(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??S1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=F1(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??S1(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 rwe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function I1(e,t){return UQ(e)?ae(e,{target:rwe(t?.target),io:t?.pipeStrategy??`input`}):nwe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function L1(e){let t=qQ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=XQ(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function R1(e,t){let n=GQ(e,t);if(!n.success)throw n.error;return n.data}var iwe=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(x$,e=>{this._oncancel(e)}),this.setNotificationHandler(k$,e=>{this._onprogress(e)}),this.setRequestHandler(O$,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(F$,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new g1(g$.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(L$,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 g1(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 g1(g$.InvalidParams,`Task not found: ${r}`);if(!_1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(_1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[$Q]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(R$,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 g1(g$.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(B$,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new g1(g$.InvalidParams,`Task not found: ${e.params.taskId}`);if(_1(n.status))throw new g1(g$.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 g1(g$.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof g1?e:new g1(g$.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),g1.fromError(g$.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),h$(e)||v$(e)?this._onresponse(e):f$(e)?this._onrequest(e,t):tSe(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=g1.fromError(g$.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?.[$Q]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:g$.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=eSe(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 g1(g$.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:g$.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),h$(e)?n(e):n(new g1(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(h$(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),h$(e)?r(e):r(g1.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 g1?e:new g1(g$.InternalError,String(e))}}return}let i;try{let r=await this.request(e,N$,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new g1(g$.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},_1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new g1(g$.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new g1(g$.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 g1?e:new g1(g$.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||{},[$Q]: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 g1?e:new g1(g$.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=GQ(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(g1.fromError(g$.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},I$,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},z$,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},gSe,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||{},[$Q]: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||{},[$Q]: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||{},[$Q]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=L1(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=R1(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=L1(e);this._notificationHandlers.set(n,n=>{let r=R1(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`&&f$(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new g1(g$.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 g1(g$.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new g1(g$.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 g1(g$.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=P$.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),_1(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 g1(g$.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(_1(a.status))throw new g1(g$.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=P$.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),_1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function z1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function awe(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];z1(a)&&z1(i)?n[r]={...a,...i}:n[r]=i}return n}var owe=t(pa(),1),swe=t(ya(),1);function cwe(){let e=new owe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,swe.default)(e),e}var lwe=class{constructor(e){this._ajv=e??cwe()}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)}}},uwe=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},d1,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},p1,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 dwe(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 fwe(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 pwe=class extends iwe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(c1.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 lwe,this.setRequestHandler(T$,e=>this._oninitialize(e)),this.setNotificationHandler(D$,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(l1,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=c1.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new uwe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=awe(this._capabilities,e)}setRequestHandler(e,t){let n=qQ(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(UQ(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=GQ(s1,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new g1(g$.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=GQ(N$,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new g1(g$.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=GQ(o1,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new g1(g$.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){fwe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&dwe(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:QQ.includes(t)?t:ZQ,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`},b$)}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},f1,t):this.request({method:`sampling/createMessage`,params:e},d1,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},p1,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},p1,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new g1(g$.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof g1?e:new g1(g$.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},h1,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 B1=Symbol.for(`mcp.completable`);function V1(e){return!!e&&typeof e==`object`&&B1 in e}function mwe(e){return e[B1]?.complete}var hwe;(function(e){e.Completable=`McpCompletable`})(hwe||={});const gwe=/^[A-Za-z0-9._-]{1,128}$/;function _we(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`),!gwe.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 vwe(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 H1(e){let t=_we(e);return vwe(e,t.warnings),t.isValid}var ywe=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)}},U1=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 pwe(e,t)}get experimental(){return this._experimental||={tasks:new ywe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(J1(a1)),this.server.assertCanSetRequestHandler(J1(s1)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(a1,()=>({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=JQ(t.inputSchema);return e?I1(e,{strictUnions:!0,pipeStrategy:`input`}):bwe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=JQ(t.outputSchema);e&&(n.outputSchema=I1(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(s1,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new g1(g$.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new g1(g$.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 g1(g$.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new g1(g$.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 g1&&e.code===g$.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 KQ(JQ(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=YQ(`error`in r?r.error:`Unknown error`);throw new g1(g$.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 g1(g$.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await KQ(JQ(e.outputSchema),t.structuredContent);if(!r.success){let e=YQ(`error`in r?r.error:`Unknown error`);throw new g1(g$.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 g1(g$.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(J1(m1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(m1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return fCe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return pCe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new g1(g$.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new g1(g$.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new g1(g$.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return X1;let r=qQ(n.argsSchema)?.[e.params.argument.name];if(!V1(r))return X1;let i=mwe(r);return i?Y1(await i(e.params.argument.value,e.params.context)):X1}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 X1;throw new g1(g$.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Y1(await r(e.params.argument.value,e.params.context)):X1}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(J1(J$)),this.server.assertCanSetRequestHandler(J1(Y$)),this.server.assertCanSetRequestHandler(J1(Z$)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(J$,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(Y$,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Z$,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new g1(g$.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 g1(g$.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(J1(Q$)),this.server.assertCanSetRequestHandler(J1($$)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Q$,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?xwe(t.argsSchema):void 0}))})),this.server.setRequestHandler($$,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new g1(g$.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new g1(g$.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await KQ(JQ(n.argsSchema),e.params.arguments);if(!r.success){let t=YQ(`error`in r?r.error:`Unknown error`);throw new g1(g$.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:WQ(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=WQ(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=>V1(e instanceof te?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){H1(e);let l={title:t,description:n,inputSchema:q1(r),outputSchema:q1(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`&&H1(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=WQ(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=WQ(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(K1(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!K1(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 bwe={type:`object`,properties:{}};function W1(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function G1(e){return`_def`in e||`_zod`in e||W1(e)}function K1(e){return typeof e!=`object`||!e||G1(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(W1)}function q1(e){if(e){if(K1(e))return WQ(e);if(!G1(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function xwe(e){let t=qQ(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Xxe(t),required:!Zxe(t)})):[]}function J1(e){let t=qQ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=XQ(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Y1(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const X1={completion:{values:[],hasMore:!1}};var Z1=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Swe=e=>e instanceof Z1?e:new Z1(e.message,{cause:e}),Cwe=global.Request,Q1=class extends Cwe{constructor(e,t){typeof e==`object`&&e0 in e&&(e=e[e0]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},wwe=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)},$1=Symbol(`wrapBodyStream`),Twe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new Q1(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[$1]){let e;a.body=new ReadableStream({async pull(t){try{e||=id.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=id.toWeb(r);return new Q1(t,a)},e0=Symbol(`getRequestCache`),t0=Symbol(`requestCache`),n0=Symbol(`incomingKey`),r0=Symbol(`urlKey`),Ewe=Symbol(`headersKey`),i0=Symbol(`abortControllerKey`),a0={get method(){return this[n0].method||`GET`},get url(){return this[r0]},get headers(){return this[Ewe]||=wwe(this[n0])},[Symbol(`getAbortController`)](){return this[e0](),this[i0]},[e0](){return this[i0]||=new AbortController,this[t0]||=Twe(this.method,this[r0],this.headers,this[n0],this[i0])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(a0,e,{get(){return this[e0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(a0,e,{value:function(){return this[e0]()[e]()}})}),Object.defineProperty(a0,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[t0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(a0,Q1.prototype);var Dwe=(e,t)=>{let n=Object.create(a0);n[n0]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof dd)throw new Z1(`Absolute URL for :path is not allowed in HTTP/2`);try{n[r0]=new URL(r).href}catch(e){throw new Z1(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof dd?e.authority:e.headers.host)||t;if(!i)throw new Z1(`Missing host header`);let a;if(e instanceof dd){if(a=e.scheme,!(a===`http`||a===`https`))throw new Z1(`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 Z1(`Invalid host header`);return n[r0]=o.href,n},o0=Symbol(`responseCache`),s0=Symbol(`getResponseCache`),c0=Symbol(`cache`),l0=global.Response,u0=class e{#e;#t;[s0](){return delete this[c0],this[o0]||=new l0(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[o0];if(e){this.#t=e,this[s0]();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[c0]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[c0];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[s0]().headers}get status(){return this[c0]?.[0]??this[s0]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(u0.prototype,e,{get(){return this[s0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(u0.prototype,e,{value:function(){return this[s0]()[e]()}})}),Object.defineProperty(u0.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[o0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(u0,l0),Object.setPrototypeOf(u0.prototype,l0.prototype);async function Owe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function d0(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 kwe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:d0(e.getReader(),t)}var f0=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},Awe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Xte);var p0=Symbol(`outgoingEnded`),m0=Symbol(`incomingDraining`),jwe=500,Mwe=64*1024*1024,h0=e=>{let t=e;if(e.destroyed||t[m0])return;if(t[m0]=!0,e instanceof dd){try{e.stream?.close?.(pne.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,jwe);a.unref?.();let o=e=>{n+=e.length,n>Mwe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Nwe=()=>new Response(null,{status:400}),g0=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),_0=(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))},v0=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},y0=async(e,t)=>{let[n,r,i]=e[c0],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=f0(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=f0(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())):(v0(t),await kwe(r,t)?.catch(e=>_0(e,t))),t[p0]?.()},Pwe=e=>typeof e.then==`function`,Fwe=async(e,t,n={})=>{if(Pwe(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(g0);if(c0 in e)return y0(e,t);let r=f0(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 Owe(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&&v0(t),await d0(n,t,o))}else r[Awe]||(t.writeHead(e.status,r),t.end());t[p0]?.()},b0=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==Q1&&(Object.defineProperty(global,`Request`,{value:Q1}),Object.defineProperty(global,`Response`,{value:u0})),async(r,i)=>{let a,o;try{o=Dwe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[$1]=!0,r.on(`end`,()=>{s=!0}),r instanceof dd&&(i[p0]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{h0(r)})})}),i.on(`finish`,()=>{s||h0(r)})),i.on(`close`,()=>{o[i0]&&(r.errored?o[i0].abort(r.errored.toString()):i.writableFinished||o[i0].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{h0(r)})})}),a=e(o,{incoming:r,outgoing:i}),c0 in a)return y0(a,i)}catch(e){if(a)return _0(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Swe(e)),!a)return}else a=o?g0(e):Nwe()}try{return await Fwe(a,i,t)}catch(e){return _0(e,i)}}},Iwe=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
1190
1190
  `;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=>y$.parse(e)):[y$.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(E$);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(f$)){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=>E$(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)f$(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)f$(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;f$(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&&!QQ.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${QQ.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${QQ.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((h$(e)||v$(e))&&(n=e.id),n===void 0){if(h$(e)||v$(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(h$(e)||v$(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)}}}},Lwe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Iwe(e),this._requestListener=b0(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 b0(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const x0=`https://json-schema.org/draft/2020-12/schema`,S0=`tools/list`;function C0(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(S0);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${S0} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`);return}e.server.setRequestHandler(a1,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=x0),e.outputSchema&&(e.outputSchema.$schema=x0);return r}),t.__jsonSchemaDialectInstalled=!0}function w0(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||!Rwe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=_e(i.error);throw new g1(g$.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Rwe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const T0=2e3,E0=2e3,zwe=[/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 D0(e){return zwe.some(t=>t.test(e))}function Bwe(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 hu(e)?e:null}catch{return null}}function Vwe(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&&hu(a)?a:null}function Hwe(e){let t=[];for(let n of e.split(`
@@ -2033,7 +2033,7 @@ native-divergence-injected
2033
2033
  `)),`${n}${o}`}function LFe(e,t){let{bom:n,body:r}=B7(e),i=[],a=WP(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(IFe(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=GP(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=KP(s);if(!R7(c))return{kind:`declined`,reason:`foreign-entry`};let l=Yn(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:GP(a,[...o,e])})).filter(e=>e.node!==void 0).sort((e,t)=>t.node.offset-e.node.offset);for(let{key:e,node:n}of d){let r=JSON.stringify(H7(t,e));u=`${u.slice(0,n.offset)}${r}${u.slice(n.offset+n.length)}`}return{kind:`managed`,raw:e,shell:`${n}${u}`,entry:c,descriptor:l.descriptor}}function H7(e,t){return e.topLevelKey===`mcp`&&t===`type`?`__ok_managed_type__`:t===`command`&&e.topLevelKey===`mcp`?[`__ok_managed_command__`]:t===`command`?`__ok_managed_command__`:[`__ok_managed_args__`]}function RFe(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=B7(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=R7(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!R7(s))return{kind:`declined`,reason:`foreign-entry`};let c=Yn(s);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,`open-knowledge`,Object.fromEntries(t.managedKeys.map(e=>[e,H7(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=V7(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function U7(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?LFe(e,t):RFe(e,t,n)}function zFe(e,t,n){let{bom:r,body:i}=B7(e),a=i;for(let e of t.managedKeys){let r=WP(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?GP(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(KP(o))===JSON.stringify(n[e])||(a=JP(a,qP(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:FFe(i)})))}return`${r}${a}`}function W7(e,t,n,r){if(t.format===`json`)return zFe(e,t,n);if(!r)return null;let{body:i}=B7(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return V7(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function BFe(e){let t=z7(e.target);return t?W7(e.raw,t,e.entry,e.tomlEditor):null}function G7(e){let t=z7(e.target);if(!t)return null;let n=U7(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function VFe(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function K7(e){let t=z7(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:U7(e.layers.base,t,e.tomlEditor),head:U7(e.layers.head,t,e.tomlEditor),index:U7(e.layers.index,t,e.tomlEditor),worktree:U7(e.layers.worktree,t,e.tomlEditor),incoming:U7(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=VFe(a.base,a.worktree,a.incoming);if(o===null)return{kind:`declined`,reason:`unowned-shell-conflict`};let s=Object.values(a).map(e=>({entry:e.entry,descriptor:e.descriptor}));if(e.runningEntry){let t=Yn(e.runningEntry);t.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:t.descriptor})}if(new Set(s.map(e=>e.descriptor.family)).size!==1)return{kind:`declined`,reason:`mixed-launcher-family`};let c=s.reduce((e,t)=>t.descriptor.revision>e.descriptor.revision?t:e),l=[a.worktree,a.index,a.head,a.incoming,a.base].find(e=>e.shell===o);if(!l)return{kind:`declined`,reason:`unowned-shell-conflict`};let u=W7(l.raw,t,c.entry,e.tomlEditor);return u===null?{kind:`declined`,reason:e.tomlEditor?`unparseable`:`no-native-writer`}:{kind:`resolved`,raw:u,winner:c.descriptor,winnerEntry:c.entry}}const HFe=F(`github-account`),UFe=(e,t)=>{let n=uu(`git`,[`config`,`--get-urlmatch`,`credential`,e],Dw({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(HFe.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?cI(n.stderr).slice(0,200):void 0},`[github-account] git config --get-urlmatch failed — treating the URL as declaring no account`),null):n.status!==0||!n.stdout?null:n.stdout};function WFe(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function GFe(e){let t;for(let n of e.split(`
2034
2034
  `)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function q7(e,t={}){let n=JF(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??UFe)(WFe(e),t.cwd??process.cwd()),a=i?GF(GFe(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function KFe(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=Mhe(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=q7(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function J7(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 qFe(e,t){return t===`anonymous`?Math.max(180,e):e}const $=F(`sync-engine`),Y7=new Set(PFe),X7=/^[0-9a-f]{40}$/i,JFe=ld(cu);var Z7=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function YFe(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 XFe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function Q7(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.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const $7={syncScope:{pathBase:`content`}},e9={syncScope:{pathBase:`project`}},t9=new Set([`diverged-local-commits`,`external-changes-pending`]);function n9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function r9(e){let t=pd(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 ZFe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const i9=12e4;var QFe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;blockingPaths=[];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.rootOkOutsideContentWalk=rN(R(this.contentDir,L(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],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.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=xFe(e.detectGh),this.ghAccountResolver=KFe({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??kFe,this.statePath=z(KO(this.projectDir),`sync-state.json`),this.conflictStore=new TZ(this.projectDir,this.currentBranch)}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!WF(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?$.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):$.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){$.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return Ec(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??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){$.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),$.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){$.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=xd(this.projectDir),n=t?L(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){$.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 Xb(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&&$.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){$.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){$.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){$.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`),$.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=J7(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=J7(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),$.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()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||($.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,$.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(0),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){$.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await cd(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||r9(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||r9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){$.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){$.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 Tc(()=>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,$.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`,$.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.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(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}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.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?$.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}`):$.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.pushInFlight||this.pullInFlight){$.info({pushInFlight:this.pushInFlight,pullInFlight:this.pullInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){$.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){$.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote||r9(this.projectDir)){$.info({hasRemote:this.hasRemote},`[sync] one-shot push refused — no remote, or no commits yet`);return}let e=this.state;this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||r9(this.projectDir)||this.pullInFlight||this.pushInFlight||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return $.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){$.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return $.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.pullInFlight||this.pushInFlight)return $.info({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return $.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||r9(this.projectDir))return $.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);let t=this.mode,n=this.state,r=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.pullInFlight=!1,t===`off`?(t9.has(this.pausedReason)||t9.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,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?Nhe(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.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return Tc(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,`--`,...e]),(await Xb(t.git,[`diff`,`--cached`,`--name-only`,`--`,...e])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,`--`,...e])}catch(n){throw await t.git.raw([`reset`,`--`,...e]).catch(()=>{}),$.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),$.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutiveFailures=0,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await uB(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await uB(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;kc(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}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,Q7(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,$.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{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){$.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=XFe(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&$.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,$.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,$.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!Q7(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,$.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(L(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return $.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=xd(this.projectDir),r=n?L(n,`MERGE_HEAD`):null;if(r!==null&&V(r))try{let n=this.gitHandle(),r=new Set(await Xb(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&&$.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){$.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{$.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.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&&($.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0?(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=>{$.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??n9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){if(this.resolveRelayGhToken()!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(this.syncGhTarget().host))?.token)return`authenticated`}catch(e){$.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`?qFe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=ZFe(this.consecutiveFailures);return n9(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(r9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(e){let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(j7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=j7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}if(await this.refreshDivergenceCounts(t),this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(t);let e=await this.prepareForMerge(t,n);if(!e.proceed)return`refused`;let r=!0,i=!0;try{await this.applyCommitIdentity(t),await t.git.merge([`origin/${n}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{e.needsStashPop&&(r=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(e.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(e.reconciled),this.scheduleSaveState(),`succeeded`}catch(e){let t=j7(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`),$.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 Xb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Xb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(j7(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(j7(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){$.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 $.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(j7(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 $.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(j7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?($.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(j7(Error(`git merge --ff-only timed out after ${i9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),$.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 $.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(j7(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 $.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(j7(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.blockingPaths=[],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 $.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 JFe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:i9}),{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:YFe({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(L(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),$.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(L(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`&&$.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&&Y7.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=K7({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),$.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&$.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=ms(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){$.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){let n={allowShareableOkArtifact:rP};for(let{path:t,bytes:r}of e){let e=L(this.projectDir,t);SL(e,this.projectDir,n),gc(e,r)}for(let e of t){let t=L(this.projectDir,e);SL(t,this.projectDir,n);try{nc(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=L(this.projectDir,e),n=rN(R(this.contentDir,t));return!n.startsWith(`..`)&&Jx(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 Xb(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(this.conflictCount>0){this.schedulePush();return}if(r9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=L(Gu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;this.transitionTo(`pushing`);try{let e=this.gatherContentFilesSync();await Tc(async()=>{let r=this.gitHandle(t);if(r9(this.projectDir)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await r.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)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(j7(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(r,i),o=await this.stageContentFiles(r,e),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(r,c);let l=(await r.git.raw([`write-tree`])).trim(),u=``;try{u=(await r.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===i){$.info({contentFileCount:e.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.clearPushError(),this.transitionTo(`idle`);return}$.info({headSha:i,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=i;return}let d=[],f=[];try{let t=await Xb(r.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){d.push(e);let t=n.get(e)??rN(R(this.contentDir,L(this.projectDir,e)));t&&!t.startsWith(`..`)&&f.push(t)}}}catch{d=e.map(e=>e.projectRelPath).concat(c),f=e.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f);await this.applyCommitIdentity(r);let m=(await r.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!m||!X7.test(m)){$.warn({raw:m},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,m,i]),await this.resetRealIndexForPaths(d);let h=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),h=!0}catch{}h?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=m}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,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=t instanceof Error?t:Error(String(t));n instanceof Z7&&$.warn({err:n},`[sync] push cycle: staging error detail`);let r=j7(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){$.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}let n=!0,r=!0;try{await this.applyCommitIdentity(e),await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&(n=await this.popPreMergeStash(e)),r=this.restoreReconciledMcpOverlays(t.reconciled)}if(!n)throw Error(`failed to replay pre-merge working-tree state`);if(!r)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(t.reconciled)}catch(e){let t=j7(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():e instanceof Z7?($.warn({err:e},`[sync] push retry: staging error detail`),this.handleError(t,`push`)):this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}$.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{zu(t)}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=L(Gu(),`ok-sync-retry-idx-${process.pid}-${Date.now()}.idx`),a=this.gitHandle(i);try{await a.git.raw([`read-tree`,t]);let i=await this.stageContentFiles(a,n),o=new Set(i.map(e=>e.projectRelPath)),s=[...r].filter(e=>!o.has(e));await this.removePathsFromIndex(a,s);let c=(await a.git.raw([`write-tree`])).trim();if(c===(await a.git.raw([`rev-parse`,`${t}^{tree}`])).trim())return null;let l=[];try{l=await Xb(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}await this.applyCommitIdentity(a);let u=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!u||!X7.test(u)?($.warn({raw:u},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,u,t]),await this.resetRealIndexForPaths(l,e),u)}finally{try{zu(i)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,`origin/${t}`])).trim()}catch(e){return $.warn({err:e,branch:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,`origin/${t}`,n)]),c=null;try{c=H(L(this.projectDir,n),`utf8`)}catch{}return K7({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t){let n=[],r;try{r=await Xb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return $.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}if(r.length===0)return{proceed:!0,needsStashPop:!1,reconciled:n};let i;try{i=new Set(await Xb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return $.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}let a=r.filter(e=>i.has(e)),o=Y7,s=a.filter(e=>o.has(e));if(s.length>0){let r=await Promise.all(s.map(async n=>({path:n,plan:await this.planTrackedMcpOverlap(e,t,n)}))),i=r.find(({plan:e})=>e.kind===`declined`),c=a.some(e=>!o.has(e));if(!i&&!c){for(let{path:e,plan:t}of r)t.kind===`resolved`&&(n.push({path:e,raw:t.raw,winnerEntry:t.winnerEntry}),$.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));a=a.filter(e=>!o.has(e))}else i?$.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):c&&$.info({event:`mcp-config-reconcile`,targets:s,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(a.length>0){let e=a.slice(0,3).join(`, `),t=a.length>3?`, +${a.length-3} more`:``;return this.blockingPaths=a,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(),$.warn({files:a},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(n.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...n.map(e=>e.path)])}catch(e){return $.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let c=new Set(n.map(e=>e.path));if(r.every(e=>c.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:n};let l=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,l])}catch(e){return $.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:n}}return{proceed:!0,needsStashPop:!0,reconciled:n}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=L(this.projectDir,n.path);SL(e,this.projectDir);let t=null;try{t=H(e,`utf8`)}catch(e){$.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&gc(e,n.raw,`utf8`)}catch(e){t=!1,$.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return $.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}hasGitOperationInProgress(){let e=xd(this.projectDir);return e?[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>V(L(e,t))):!0}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw Error(`refusing MCP entry commit while a Git operation is in progress`);await Tc(async()=>{let t=L(Gu(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=BFe({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,`--`,o.path])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),Bu(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=G7({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=G7({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),Bu(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!X7.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){$.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=L(this.projectDir,e.path);SL(t,this.projectDir),H(t,`utf8`)!==e.raw&&gc(t,e.raw,`utf8`)}}catch(t){$.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path)),this.restoreReconciledMcpOverlays(e)}$.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{zu(e)}catch{}try{zu(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await Xb(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,$.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&$.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`,`--`],s],[[`add`,`-f`,`--`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...i])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new Z7(rN(R(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=Nu(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=L(r,c.name);if(c.isDirectory()){let e=rN(R(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=rN(R(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=rN(R(this.contentDir,s)),n=rN(R(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(V(this.contentDir)&&n(this.contentDir,this.contentDir,$7),this.rootOkOutsideContentWalk){let e=L(this.projectDir,`.ok`);V(e)&&!this.contentFilter.isDirExcluded(`.ok`,e9)&&n(e,this.projectDir,e9,t)}return e}isSyncScopedPath(e){let t=L(this.projectDir,e),n=rN(R(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,$7),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,e9);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Xb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&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 Xb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){$.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){$.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)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=rN(R(this.projectDir,Vs(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),t.toLowerCase()===a.toLowerCase()?$.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.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){$.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(),$.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`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=xd(this.projectDir);t=n===null||!V(L(n,`MERGE_HEAD`))}catch(e){$.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){$.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`),$.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){$.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){$.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),$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.ghAccountResolver.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`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.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,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,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)};Bu(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){$.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.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??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`||t.pausedReason===`external-changes-pending`?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){$.warn({err:e},`[sync] failed to load sync state`)}}};Ls();const $Fe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function eIe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(cS(e)||lS(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&$Fe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Us(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Rs.with(Fs.extract(Rs.active(),r),e)}else e()}catch(e){F(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let a9=!1;function o9(){if(a9)return;let e=gne;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){a9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),a9=!0}catch(e){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const tIe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),nIe=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function rIe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=uu(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],Dw({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return F(`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 F(`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(`
2035
2035
  `)){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=z(e,r);if(!oN(a,t))continue;let s=Sz(a,t);i.has(s)||V(a)&&i.set(s,o)}return i}function s9(e){o9();let t=e.ingressPolicy??FB({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:l=3e4,wipRef:u=`refs/wip/main`,configHomedirOverride:d,enableTestRoutes:f=!1,shadowRepo:p,contentRoot:m,destroyTimeoutMs:h=1e4,localOpCliArgs:g,authStreamHeartbeatMs:_,skipStateManifestCheck:v=!1,singleDocRelPath:y,ephemeral:b=!1}=e,x=F(`server`),S=new R5,C=()=>S.getActiveBranch(),w=e=>S.getReconciledBase(e),T=(e,t)=>S.setReconciledBase(e,t),E=e=>S.deleteReconciledBase(e),D=e=>S.switchReconciledBaseScope(e),O=e=>S.setBatchInProgress(e),te=()=>S.isBatchInProgress();function k(e){let t=Gs({absPath:Vs(`project`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=ce(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});x.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function A(){let e=Gs({absPath:Vs(`project-local`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project-local config`)}),t=c(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||x.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=Gs({absPath:Vs(`project`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project config`)});return n.valid||x.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Le(n.value.autoSync?.default)??`off`,source:`committed-default`}}function ne(){return ee(Gs({absPath:Vs(`project-local`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project-local config`)}).value.autoSync)}function re(){let e=Gs({absPath:Vs(`project`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?nt(e):Lo;return yPe(r,t.plugins.okf),t}function ie(){return Gs({absPath:Vs(`project`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function j(){return mM(r,{configHomedirOverride:d,onWarn:e=>x.warn({message:e},`[config] could not read project-local config`)})}function ae(){let e=Gs({absPath:Vs(`project-local`,r,d),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function oe(){return oc({cwd:r,homedirOverride:d,warn:e=>x.debug({message:e},`[config] diagnostics read`)})}function M(){for(let e of oe().diagnostics)e.code===`REMOVED_KEY`&&x.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 se(e){return`${iM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let le;function ue(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=A();i=t.mode,sn?.setMode(t.mode,t.source).catch(n=>{x.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=ne();sn?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=j();if(Fe.applyConfig({enabled:a.enabled,providerFingerprint:se(a)}),e===`__config__/project`){try{let e=k({requireValid:!0});ve?.setAttachmentFolderPath(e),le!==void 0&&e!==le&&x.warn({previous:le,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),le=e}catch(e){x.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}Oe?.signal(`lint-config`),(t??re().plugins.okf?.generate?.index===!0)||x5({projectDir:r,contentDir:n,generatedDocNames:At(),enabled:!1}).then(e=>{e.ok||x.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),Tt()}x.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}vc();let de=nd(),fe=KO(r),pe=new Zd({localDir:fe,log:F(`acp-registry`)}),me=new Vd(fe,F(`acp-permissions`));if(Pc(fe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!v)try{O7({lockDir:fe,shadowRepoDir:Sd(r)})}catch(e){throw Fc(fe),e}let he=Bo(),ge=(e,t)=>he.resolveEmbed(e,t),_e=(e,t)=>{let r=he.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(n,r);if(!iN(i,z(n)))return null;try{let e=Ru(i);return e.isFile()?e.size:null}catch{return null}},ve,ye,be,xe,N,Se,Ce,we,Te,Ee,De,Oe=null,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=j(),Fe=new npe({loadEmbedder:e.embedderLoader??(()=>{let t=j();return Hfe({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(KO(r),`embeddings`),enabled:Pe.enabled,providerFingerprint:se(Pe)}),Ie=null,ze=new Set,Be=!1,P=[],Ve,He,Ue,We=new Promise((e,t)=>{He=e,Ue=t}),Ge,Ke=new Promise(e=>{Ge=e});async function qe(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ke,n])!==t)return C()}finally{e&&clearTimeout(e)}try{return V5(r).branch??null}catch(e){return x.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function Je(e){Oe?.signal(e)}let Ye,Xe,Ze,Qe=!1,$e=!1,et=new AbortController,tt=new Set,rt=!1,it=!1,at=!1,ot=0,st,ct=new Promise(e=>{st=e});function lt(e){at||(at=!0,st(e))}function ut(){return rt||tt.size>0}function dt(){$e||!Qe||(Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,bt()},500),Ye.unref?.())}function ft(){if($e){lt({status:`cancelled`,indexCount:0});return}rt=!0,it=!0,Xe=setImmediate(()=>{Xe=void 0,bt()})}let pt,mt,ht=!1,gt=null;async function _t(){let e=be.current;if(!e||ht)return;let t=performance.now();x.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await Tx(e)}catch(e){x.warn({err:e},`failed to write gc config (non-fatal)`)}if(!ht){if(gt)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await iH(e,gt,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),ht)return}n||x.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){x.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!ht){try{await xe?.runBootMaintenance()}catch(e){x.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}x.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function vt(){ht||(pt=setImmediate(()=>{pt=void 0,mt=_t().catch(e=>{x.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function yt(){if(ht=!0,pt!==void 0&&(clearImmediate(pt),pt=void 0),!mt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),h)});try{if(await Promise.race([mt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${h}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function bt(){if($e||!Qe||!ut())return;if(Ze!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(S.isBatchInProgress()){dt();return}let t=rt,n=new Set(tt),r=it;rt=!1,tt.clear(),it=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Ze=(async()=>{let e=await Pt(i,et.signal);if(e.status===`deferred`){rt=!0,r&&(ot+=e.indexCount,it=!0);return}r&&(ot+=e.indexCount,e.status===`completed`&&ut()?it=!0:lt({...e,indexCount:ot}))})().catch(e=>{x.warn({err:e},`[index] index regeneration coordinator failed`),r&&lt({status:`failed`,indexCount:0})}).finally(()=>{if(Ze=void 0,$e){r&&lt({status:`cancelled`,indexCount:0});return}ut()&&Ye===void 0?dt():!ut()&&Ye===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function xt(){if(!$e){let e=Ze;$e=!0,et.abort(),Ye!==void 0&&(clearTimeout(Ye),Ye=void 0),Xe!==void 0&&(clearImmediate(Xe),Xe=void 0),tt.clear(),rt=!1,it=!1,e===void 0&&lt({status:`cancelled`,indexCount:0})}await Ze}function St(e){$e||sPe(e)||(tt.add(M5(e)),dt())}function Ct(e){if(!$e){for(let t of oPe(e))tt.add(t);dt()}}function wt(e){let t=an?.getFileIndex();if(!t){St(e);return}let n=M5(e);if(F5(t.keys()).has(n)){St(e);return}Ct(M5(n))}function Tt(){$e||(rt=!0,dt())}function Et(e){let t=an?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Dt=!1,Ot={origin:nIe,writer:sce,isConflict:e=>sn?.getConflicts().some(t=>s5(t,e,r,n))===!0,getDocument:e=>Ce.documents.get(e),writeDisk:async(e,t)=>{sc(I(e),{recursive:!0}),await Ws(e,t,{fs:Zs})},registerWrite:(e,t)=>lz(e,dz(t)),noteFileIndex:e=>an?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>Je(`files`),attribute:async(e,t)=>{Hj(e,t.id,t.name,t.id),Dt=!0}};function kt(e){return e===``?A5:`${e}/${A5}`}function At(){return[...an?F5(an.getFileIndex().keys()):new Set([``])].map(kt)}function jt(e){let t=re().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function Mt(){return jt(y5({projectDir:r,contentDir:n,generatedDocNames:At()}))}async function Nt(e){let t=await x5({projectDir:r,contentDir:n,generatedDocNames:At(),enabled:e});if(!t.ok)return{...Mt(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ac({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){x.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...Mt(),applied:!1,reason:`config-write`}}try{let e=H(i.path,`utf-8`);o5(Ce.documents.get(`__config__/project`)??null,lo,e,N.configPersistenceCtx)}catch(e){x.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return ue(lo,e),{...Mt(),applied:!0}}async function Pt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>re().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=an?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(S.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=cPe({docs:c,docExtension:nS,currentMarkdownFor:()=>null}),l=y5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>kt(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return x.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(S.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=kt(r),l=z(n,`${o}.md`),u;try{u=H(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&x.warn({err:e,path:lc(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await HNe({docName:o,absPath:l,markdown:c,currentMarkdown:u},Ot);d===`blocked-conflict`?x.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):x.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&Ct(M5(r))}}finally{Dt&&=(await N.waitForPendingCommits(),await N.flushContributors(),!1),o!==void 0&&($B(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),eV(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return x.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Ft=null,It=!1,Lt=()=>{try{y7(r,Rt.entries())}catch(e){x.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Rt=new ZPe(void 0,{onEviction:()=>Vse(),onSizeChange:e=>Hse(e),onMutate:()=>{!It||Ft!==null||(Ft=setTimeout(()=>{Ft=null,Lt()},2e3))}});for(let[e,t]of nFe(r))mS(e)||cZ(e)&&([`.md`,`.mdx`].some(t=>{let r=z(n,`${e}${t}`);return iN(r,z(n))&&V(r)})||Rt.restore(e,t));It=!0;let zt={current:null},Bt=(e,t)=>{mS(e)||Rt.setRenamed(e,t)},Vt=e=>{if(!mS(e)){if(Rt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Rt.setDeleted(e),zt.current?.deleted(e)}},Ht=e=>{mS(e)||Rt.delete(e)};try{let c=`./`;try{c=k()}catch(e){x.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}le=c,ve=_P({projectDir:r,contentDir:n,singleDocRelPath:y,attachmentFolderPath:c,inPlaceSkillDirs:xL(n),rescanInPlaceSkillDirs:()=>xL(n),skillRootPaths:Dge(n),onAfterRebuild:()=>{ye.refreshContentScope().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Jz(an).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`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=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ye=new zR({projectDir:r,contentDir:n,contentFilter:ve,getGlobalSkillRoots:()=>hH(N.managedArtifactCtx),signalChannel:Je,getLocalTargetInventory:()=>lve(an,n),onRecoveredFileTarget:(e,t)=>{an&&$Pe({watcher:an,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Me})}}),be={current:p},xe=s?RPe({getShadow:()=>be.current??null,getCurrentBranch:()=>on?.getLastKnownBranch()??null,contentRoot:m??``,projectGitDir:xd(r)??void 0,isWriterLive:e=>{if(!je&&!we)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let h=null;N=f7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:l,wipRef:u,shadowRef:be,ephemeral:b,contentRoot:m,derivedDocumentIndex:ye,configHomedirOverride:d,getCurrentBranch:()=>on?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,getPrincipal:()=>Ie,onAgentCommit:()=>Oe?.signal(`session-activity`),onFlushCommit:()=>xe?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{Oe?.emitDiskAck(e,t),!mS(e)&&(lPe(r,n,e)&&St(e),uV(r,n)&&(Me?.(),Je(`files`)))},onConfigRejected:(e,t)=>Oe?.emitConfigValidationRejected(e,t),onConfigPersisted:ue,onManagedSkillPersisted:e=>{let t=eo(e);t?.kind!==`skill`||t.scope!==`global`||(h!==null&&clearTimeout(h),h=setTimeout(()=>{h=null;let e=d??Hu();Uq(e,e,yL(e)).then(e=>{e>0&&x.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>x.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),h.unref?.())},isRecentlyRemoved:e=>Rt.has(e),mdManager:e.mdManager,getLossRing:()=>Se,durabilityState:S}),Ce=new ENe({quiet:i,debounce:a,maxDebounce:o,extensions:[N.extension]});let v=Ce.openDirectConnection.bind(Ce);Ce.openDirectConnection=((e,t)=>v(iS(e),t));let C=Ce;P.push(ple(()=>C.documents.size),mle(()=>N.getQueueDepths()),gle(()=>{let e=0;for(let t of C.documents.values())e+=t.directConnectionsCount;return{websocket:C.getConnectionsCount()-e,direct:e}})),vle(),b||(Ne=YPe({getLoadedDocuments:()=>C.documents,forceStore:(e,t)=>N.forceStore(e,t),getBase:e=>S.getReconciledBase(e),isBatchActive:()=>S.isBatchInProgress(),peekInFlight:e=>S.peekInFlightFlush(e),readDiskBytes:e=>{let t=aN(e,n),r,i;try{r=U(t),i=Ru(r).size}catch(t){let n=Lc(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new m7(`symlink cycle at content path: ${e}`):t}if(!oN(r,n))throw new m7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new m7(`document exceeds the open byte limit: ${e}`);try{return H(r,`utf-8`)}catch(e){if(Lc(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let T=Ce.shouldUnloadDocument.bind(Ce);Ce.shouldUnloadDocument=e=>{if(ze.has(e)||Be&&T(e))return!0;let t=e.name;return mS(t)||w(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:T(e)},Ve=async e=>{ze.add(e);try{await Ce.unloadDocument(e)}finally{ze.delete(e)}},Oe=new vS(Ce),Ae=new JE(Ce),je=new YE(Ce),we=new Ew(Ce,e.agentSessionOptions);let E=we;P.push(_le(()=>({active:E.liveSessionCount,limit:E.sessionLimit})));let D=W5({derivedDocumentIndex:ye,onDocumentSettled:e=>zt.current?.changed(e)});Ce.configuration.extensions.push(D);function O(e,t,n={}){x.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Ce.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=vZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==de)throw O(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:de}),new _Z(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${de}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await qe();if(t!==null&&i!==t)throw O(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new _Z(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?a.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Ce.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!lS(e.documentName)&&!uS(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!IB(r,t))throw O(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!RB(a,t))throw O(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let ee=z(n);function te(e){if(!cZ(e))return null;let t=z(ee,aS(e));return iN(t,ee)?t:null}Ce.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await eFe(e.documentName,{recentlyRemovedDocs:Rt,resolveFilePath:te,fileExists:V})}}),Ce.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=vZ(e.token);uPe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ce.documents.get(e)})}}),Ce.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E8(e.update);if(t.readVarString(),t.readVarUint()===L8.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ga} rejected — server-only channel`)}});let A=lZ({hocuspocus:Ce,durabilityState:S,ingressPolicy:t,sessionManager:we,commentDocHooksRef:zt,contentDir:n,getGeneratedIndexSettingsStatus:Mt,setGeneratedIndexEnabled:Nt,contentFilter:ve,serverInstanceId:de,getFileIndex:()=>an?an.getFileIndex():new Map,getAttachmentFolderPath:k,getAllFilesIndex:()=>an?an.getAllFilesIndex():new Map,getFileIndexGeneration:()=>an?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?Et(e.docName):void 0;switch(an?.mutateFileIndex(e),e.kind){case`update`:L5(t,e.content,e.docName)&&St(e.docName);break;case`create`:case`conflict`:St(e.docName);break;case`delete`:wt(e.docName);break;case`rename`:wt(e.oldDocName),St(e.newDocName);break;case`folder-create`:case`folder-delete`:Ct(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:iz(e)}},getFolderIndex:()=>an?an.getFolderIndex():new Map,getAliasMap:()=>an?an.getAliasMap():new Map,getFolderAliasIndex:()=>an?an.getFolderAliasIndex():new Map,rescanFiles:()=>an?.rescanFromDisk(),enableTestRoutes:f,shadowRef:be,flushGitCommit:()=>N.flushPendingGitCommit(),flushContributors:()=>N.flushContributors(),getCurrentBranch:()=>on?.getLastKnownBranch()??null,getDiskAckSVs:()=>Oe?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:m,derivedDocumentIndex:ye,signalChannel:Je,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>sn,localOpCliArgs:g,authStreamHeartbeatMs:_,projectDir:r,resolveEmbed:ge,getBridgeLossReporter:()=>De,getPrincipal:()=>Ie,acpRegistry:pe,loadAcpCustomAgents:()=>Qd(fe,F(`acp-registry`)),homeDirOverride:d,forceUnloadDocument:Ve,ready:We,recentlyRemovedDocs:Rt,serializeDoc:qt,evictManagedArtifactLkg:e=>{N.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Fe,getSemanticSimilarityFloor:()=>j().similarityFloor,getLinterBaseConfig:()=>re(),getLinksValidationSetting:()=>ie(),getLinkPreviewsEnabled:ae,getConfigDiagnostics:oe,embeddingsSecretsFile:dM(d),readSemanticProviderConfig:j,ephemeral:b,onReferencedAssetsCacheInvalidator:e=>{Me=e}});Ce.configuration.extensions.push(A),Te=A.nativeApi,Ee=A.localApi;let ne=Gs({absPath:Vs(`project`,r),sideline:!1,warn:e=>x.warn({message:e},`[config] could not read project config for bridge guards`)}),M=ne.value.bridge.deferGuard.enabled,se=ne.value.bridge.fixedPoint.enabled,ce=ne.value.bridge.preDrain.enabled;Se=ne.value.lossCapture.enabled?new Aoe({projectDir:r,maxBytes:ne.value.lossCapture.maxBytes}):void 0,ne.value.bridge.lossDetector.enabled&&(De=xce({shadow:()=>be.current,ring:Se,getBranch:()=>on?.getLastKnownBranch()??`main`,contentRoot:m??``}),we.attachBridgeLossReporter(De)),Ce.configuration.extensions.push(x7({mdManager:Bs,schema:zs,shadowRef:be,contentRoot:m,getCurrentBranch:()=>on?.getLastKnownBranch()??null,resolveEmbed:ge,resolveSize:_e,deferGuardEnabled:M,lossDetectorEnabled:ne.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:se,preDrainEnabled:ce,lossRing:Se})),Ce.configuration.extensions.push(eIe()),Ce.configuration.extensions.push(VNe({getSyncEngine:()=>sn,projectDir:r,contentDir:n}))}catch(e){for(let e of P.splice(0))e();throw Ne?.dispose(),Ne=null,Fc(fe),e}let Ut=null,Wt=new Map,Gt=[];function Kt(e,t){let n=z(e,`rescue`),r=z(n,aS(t));return iN(r,n)?r:null}function qt(e){let t=Ce.documents.get(e);return t?QR(t):null}let Jt=(e,t)=>YR(S,Ce,e,t,ge,_e,De);function Yt(e){if(!DS(e)||sn?.getConflicts().some(t=>s5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Xt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ce.documents){if(mS(n))continue;let r=Ce.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{VR(r,i,ge,n)},BR)}catch(t){x.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Zt=null,Qt=e=>{e&&(Zt===null&&(Zt=new Set,setImmediate(()=>{let e=Zt;if(Zt=null,e)try{for(let t of e)Xt(t)}catch(t){x.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Zt.add(e))};function $t(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 iz(e)}}async function en(e){try{switch(e.kind){case`create`:x.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await ye.recordDiskUpsert(e.docName,e.content),Je(`files`),St(e.docName),Ht(e.docName);break;case`update`:{let{docName:t,content:n}=e;L5(e.previousIndexedFields,n,t)&&St(t);let r=Ce.documents.get(t);if(!r){await ye.recordDiskUpsert(t,n);return}let i=w(t)??``,a=qt(t)??i,o=GR({docName:t,base:i,ours:a,theirs:n}),s=dz(i).slice(0,6),c=dz(a).slice(0,6),l=dz(n).slice(0,6);switch(x.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`:Yt(r),await ye.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{Jt(t,o.newContent),T(t,o.newContent),Qb(),Yt(r),e=!0}catch(e){x.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),T(t,n),Yt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{Jt(t,o.newContent),T(t,n),Qb(),Yt(r),e=!0}catch(e){x.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),T(t,n),Yt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{Jt(t,o.newContent),T(t,o.newContent),Qb(),$b(),e=!0}catch(e){x.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),T(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await ye.recordDiskUpsert(t,n);break}case`refused`:{$b();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n){await ye.recordDiskDelete(t),Je(`files`),Vt(t),wt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=w(t)??``,i=qt(t)??``,a=i!==r;if(a&&be.current){let e=be.current,n=on?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Vx(e,m??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{tx(),x.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{x.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),E(t),await ye.recordDiskDelete(t),x.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ce.closeConnections(t),await Ve(n),Je(`files`),Vt(t),wt(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=Ce.documents.get(t);if(E(t),T(n,r),await ye.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}x.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Je(`files`),Bt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),wt(t),St(n);break}case`conflict`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n)return;let r=qt(t);r===null?x.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):T(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),x.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:he.add(e.relativePath),Je(`files`),Qt(fu(e.relativePath));break;case`asset-delete`:he.remove(e.relativePath),Je(`files`),Qt(fu(e.relativePath));break;case`folder-create`:case`folder-delete`:Je(`files`),Ct(e.relativePath);break;case`file-create`:case`file-update`:await ye.recordFileTargetUpsert(e.relativePath),Me?.(),Je(`files`);break;case`file-delete`:await ye.recordFileTargetDelete(e.relativePath),Me?.(),Je(`files`);break;default:iz(e)}}catch(t){let n=$t(e);x.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let tn=[];async function nn(e){if(te()){tn.push(e);return}await en(e)}async function rn(){let e=tn.splice(0,tn.length);for(let t of e)await en(t)}let an=null,on=null,sn=null,cn=null;async function ln(e){if(Ce.documents.size===0)return;let t=!1,n=new Promise(e=>{Ce.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ce.documents.keys());Ce.closeConnections(),Ce.flushPendingStores();for(let e of Ce.documents.values())e.getConnectionsCount()===0&&Ce.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(Ce.documents.keys()),i=[],o=[];if(be.current){for(let e of n)if(!mS(e))try{let t=qt(e);if(t===null){x.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Kt(be.current.gitDir,e);if(!n){x.warn({docName:e,gitDir:be.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Ou(I(n),{recursive:!0}),Bu(n,t,`utf-8`),tx(),i.push(e),x.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),x.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else x.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 un(){return cn||(cn=(async()=>{let e=Date.now(),t=[];Be=!0;try{await xt()}catch(e){x.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of P.splice(0))e();try{await Ne?.dispose()}catch(e){x.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ne=null;try{Ete(fe)}catch(e){x.warn({err:e},`[server] failed to mark server.lock draining`)}xe?.destroy();try{await yt()}catch(e){x.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Ft!==null&&(clearTimeout(Ft),Ft=null),It)try{y7(r,Rt.entries())}catch(e){x.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([We.then(()=>`completed`,e=>(x.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&x.warn({},`[server] init did not complete within 5s during shutdown`);let a=Ce.documents.size;try{try{try{ke&&=(clearTimeout(ke),null),on&&=(await on.unsubscribe(),null),an&&=(await an.unsubscribe(),null);for(let{docName:e,cleanup:t}of Gt)try{await t()}catch(t){x.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Gt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{Oe?.destroy(),je?.destroy(),Ut&&=(await Ut.disconnect(),null);for(let[e,t]of Wt)try{await t.disconnect()}catch(t){x.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Wt.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await we.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await Rce()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await ln(h)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-3 flush failed`)}ye.close();let e;try{await Promise.race([(async()=>{await N.flushPendingGitCommit(),await N.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),h)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{sn&&=(await sn.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(be.current){let e;try{await Promise.race([yx(be.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),h)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await Oc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Bu(z(be.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{tce(be.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?x.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):x.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{Fc(fe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),x.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await _c()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),cn)}let dn=[];async function fn(){try{Ie=await h7(r),x.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){x.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!be.current)try{be.current=await Dx(r,{deferGcConfig:!0}),x.info({gitDir:be.current.gitDir},`[server] history repo initialized at ${be.current.gitDir}`)}catch(e){x.error({err:e},`[server] history repo init failed`),dn.push(`shadow-repo`)}if(be.current)try{let e=PV(be.current.gitDir);rH(be.current.gitDir,e),zV(be.current.gitDir,e),gt=e,x.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){x.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(be.current)try{await wx(be.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`)){x.warn({},`[server] history repo appears corrupted — reinitializing`);try{be.current=await Dx(r,{deferGcConfig:!0})}catch(e){x.error({err:e},`[server] history repo reinit failed`),be.current=void 0,dn.includes(`shadow-repo`)||dn.push(`shadow-repo`)}}else x.error({err:e},`[server] history repo check failed (transient?)`)}if(be.current){let e=be.current,t=rN(R(r,n))||`.`;setTimeout(()=>{jx(e,t).catch(e=>{x.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3).unref()}if(be.current)try{let e=z(be.current.gitDir,`last-known-head`),t=null;try{t=H(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await Oc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await Oc({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}x.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await Rx(be.current,m??``,t,n,e),ex()}catch(e){x.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else x.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{Bu(e,n,`utf-8`)}catch(e){x.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){x.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=xve(n,r);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;x.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){x.error({err:e},`[server] managed rename recovery failed`),dn.push(`managed-rename-recovery`)}try{let e=Pge(r);(e.deleted>0||e.errors>0)&&x.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){x.error({err:e},`[server] upload-tempfile sweep failed`),dn.push(`upload-tempfile-sweep`)}try{Ut=await Ce.openDirectConnection(Ga),Oe?.emitServerInfo(de,C())}catch(e){x.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),dn.push(`cc1-push`)}let t=b?[]:Zi;for(let e of t)try{let t=await Ce.openDirectConnection(e);Wt.set(e,t)}catch(t){x.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),dn.push(`config-doc:${e}`)}let i=new Map([[lo,Vs(`project`,r)],[Po,Vs(`project-local`,r)],[Ca,Vs(`user`,r,d)]]);for(let e of t){let t=i.get(e);if(t)try{x.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X8(t,t=>{let n=Ce.documents.get(e);x.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o5(n??null,e,t,N.configPersistenceCtx);x.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ue(e)});Gt.push({docName:e,cleanup:n}),x.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){x.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),dn.push(`config-file-watcher:${e}`)}}if(!b){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,ye.refreshGlobalSkillNodes().catch(e=>{x.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=bH(e,N.managedArtifactCtx);if(!r)return;let i=TH(Ce.documents.get(r)??null,r,n,N.managedArtifactCtx);x.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),Je(`files`),wo(r)&&t(r)},r=e=>{let n=bH(e,N.managedArtifactCtx);Je(`files`),n&&wo(n)&&t(n)};try{let e=hH(N.managedArtifactCtx),t=await zPe(e,n,r);Gt.push({docName:`__skill-files__`,cleanup:t}),x.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){x.warn({err:e},`[managed-artifact-watcher] skills failed to start`),dn.push(`managed-artifact-watcher:skills`)}try{let e=z(fH(N.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X8(e,()=>{Je(`files`)});Gt.push({docName:`__skill-state__`,cleanup:t}),x.info({path:e},`[skill-state-watcher] started`)}catch(e){x.warn({err:e},`[skill-state-watcher] failed to start`),dn.push(`skill-state-watcher`)}}try{let e=z(n,`.okignore`),t=z(r,`.gitignore`),i=null;try{let e=uu(`git`,[`rev-parse`,`--git-common-dir`],Dw({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(r,e.stdout.trim()),`info`,`exclude`);V(I(t))&&(i=t)}}catch{}let a=i?[e,t,i]:[e,t],o=x;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:b},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=b?null:await MNe(a,(t,n)=>{(async()=>{if(t===e)try{let e=o5(Ce.documents.get(`__config__/okignore`)??null,qo,n,N.configPersistenceCtx);o.info({docName:qo,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:R(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ve.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:R(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),Oe?.signal(`files`);else{let e=R(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),Oe?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Gt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){x.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),dn.push(`ignore-files-watcher`)}let a=V5(r).branch??`main`;D(a),Ge();let o=ye.beginStartup(a),s=!1,c=performance.now();try{await Ys(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&dn.push(`backlink-index`);let i=0;for(let t of e)mS(t)||Rt.peek(t)?.kind!==`renamed`&&(Rt.setDeleted(t),i++);i>0&&x.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=ve?xL(n):new Set,u=e=>{e.some(e=>c.test(R(n,e).split(B).join(`/`)))&&(ke&&clearTimeout(ke),ke=setTimeout(()=>{ke=null;try{Uq(r,n).then(e=>{e>0&&(x.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),Oe?.signal(`files`))}).catch(e=>x.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=xL(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ve.rebuildIgnorePatterns().then(t=>{t.ok?(x.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),Oe?.signal(`files`)):x.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>x.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){x.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};an=await Ys(`ok.boot.seed-walk`,void 0,async()=>qz(n,nn,ve,{onRawBatch:u})),Uq(r,n).then(e=>{e>0&&x.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>x.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=d??Hu();Uq(e,e,yL(e)).then(e=>{e>0&&x.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>x.warn({err:e},`[in-place-skills] global copy re-sync failed`))}$B(`seedWalkMs`,Math.round(performance.now()-a));{let e=z(n),t=0;for(let[n]of Rt.entries()){if(!cZ(n))continue;let r=z(e,`${n}${nS(n)}`);iN(r,e)&&V(r)&&(Rt.delete(n),t++)}t>0&&x.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await ye.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&dn.push(`tag-index`);let p=0;try{y===void 0?await fZ({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(e,t,n)=>{p++,x.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):axe({contentDir:n,basenameIndex:he,onSkip:(e,t,n)=>{p++,x.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(x.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),dn.push(`basename-index-partial`))}catch(e){x.error({err:e},`[basename-index] startup seed failed`),dn.push(`basename-index`)}})}catch(e){if(x.error({err:e},`[server] disk bridge watcher failed to start`),dn.push(`file-watcher`),!s){let e=await ye.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&dn.push(`tag-index`)}}finally{$B(`indexesMs`,Math.round(performance.now()-c)),an&&eV(`fileCount`,an.getFileIndex().size)}try{on=await hPe(r,async({trigger:e})=>{if(x.info({trigger:e},`[batch] begin trigger=${e}`),Roe(),Ce.flushPendingStores(),await N.flushPendingGitCommit(),O(!0),be.current){let e=C(),t=V5(r).branch??e,n=[];for(let[e,t]of Ce.documents){if(mS(e))continue;let r=null;if(t.transact(()=>{r=qt(e)},tIe),r===null)continue;let i=w(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await fce(be.current,e,Ix.id,n,t);r&&(Voe(),x.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){x.error({err:e},`[shadow] park failed`)}}},async e=>{let t=tn.length,i=e.newBranch??`main`;if(x.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(O(!1),await rn(),e.headMoved&&e.newHead){let t=rIe(r,z(n),e.oldHead,e.newHead);if(t.size>0){Uj(t.keys());for(let[e,n]of t)Hj(e,xne(n.email),n.name,n.email,Nd(e));await N.flushContributors()}}if(await N.flushDeferredStores(`within-branch`),sn!==null)try{await sn.reconcileConflictsFromGit()}catch(e){x.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Boe(),tn.splice(0,tn.length);let t=!1,r;try{D(i),r=await ye.beginBranchSwitch(i),ve.rebuildDirCount();try{let e=0;he.clear(),await fZ({contentDir:n,contentFilter:ve,basenameIndex:he,onSkip:(t,n,r)=>{e++,x.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(x.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`),dn.includes(`basename-index-partial`)||dn.push(`basename-index-partial`))}catch(e){x.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Ce.documents)if(!mS(e))try{let r=aN(e,n);if(!V(r)){let n=w(e)??``,r=qt(e)??``;if(r!==n&&be.current){let t=be.current;queueMicrotask(()=>{Vx(t,m??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{tx(),x.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{x.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),x.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=H(r,`utf-8`);Jt(e,a),T(e,a),x.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){x.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}x.info({branch:i,docCount:Ce.documents.size},`[branch-switch] loaded branch ${i} (${Ce.documents.size} docs)`);try{await ye.settleBranchFromDisk(r)}catch(e){ye.abortBranchSwitch(r),x.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(be.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ce.documents)if(!mS(t))try{let n=await mce(be.current,i,Ix.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=w(t);if(!r)continue;let a=GR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Jt(t,a.newContent),T(t,a.newContent),e++;break;case`conflicts`:Jt(t,a.newContent),T(t,a.newContent),$b(),e++;{let e=Ce.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){x.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&x.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&be.current)try{let t=wx(be.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await yx(be.current).withMutator(async()=>{for(let e of n.split(`
2036
- `))e&&await t.raw(`update-ref`,`-d`,e)}),x.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){x.error({err:e},`[branch-switch] detached cleanup failed`)}O(!1),await N.flushDeferredStores(`discard-stale`),t=!0,Oe?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(O(!1),await N.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=m??`.`;try{let n=await Rx(be.current,t,e.oldHead,e.newHead,i);ex(),x.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){x.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){x.error({err:e},`[server] HEAD watcher failed to start`),dn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=rN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Xx(e),a=Ce.documents.get(i);if(!a)continue;let o=qt(i);o===null?x.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):T(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),x.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){x.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function u(e){for(let t of e)try{let e=rN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Xx(e));i&&Yt(i)}catch(e){x.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=QF(r);x.debug({resetAmbientCredentials:f,originKind:XF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let p=Dc(g,{resetAmbient:f}),h=A(),_=ne();h.mode!==`off`&&x.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{sn=new QFe({projectDir:r,contentDir:n,contentFilter:ve,contentRoot:m,mcpTomlEditor:e.mcpTomlEditor,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:p,cc1Broadcaster:Oe,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{O(e),e||N.flushDeferredStores(`within-branch`).catch(e=>{x.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{x.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:u,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=be.current;n&&await Bx(n,m??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await Bx(n,m??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{x.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ac({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||x.error({result:t,reason:e,humanError:Re(t.error),configPath:Vs(`project-local`,r)},`[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 sn.start()}catch(e){x.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),sn=null}Je(`files`),ye.announceReadyViews();let v=QB();v!==void 0&&$B(`readyMs`,v),M()}return fn().then(()=>{Qe=!0,He(),ft(),vt()},e=>{$e=!0,et.abort(),lt({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:S,sessionManager:we,nativeApi:Te,localApi:Ee,cc1Broadcaster:Oe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:xe,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:un,ready:We,generatedIndexSweepReady:ct,degraded:dn,lockDir:fe,get syncEngine(){return sn},getLinkPreviewsEnabled:ae,resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function c9(e){return e/1048576}function iIe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:c9(e.rss),heapTotalMb:c9(e.heapTotal),heapUsedMb:c9(e.heapUsed),externalMb:c9(e.external),arrayBuffersMb:c9(e.arrayBuffers)}}}let l9=null,u9=null,d9=null;const f9=1e6;let p9=null,m9=null;Js(()=>{l9=null,u9=null,d9=null,p9?.disable(),p9=null,m9=null});function aIe(){if(l9)return;let e=yc().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}=iIe();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`})}),l9=e}function oIe(){if(!u9){let e=yc().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(!p9){p9=nne({resolution:20}),p9.enable();return}e.observe(p9.percentile(50)/f9,{stat:`p50`}),e.observe(p9.percentile(99)/f9,{stat:`p99`}),p9.reset()}),u9=e}if(!d9){let e=yc().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=m9;if(m9={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`}))}),d9=e}}const h9=F(`skill-migrate`);function g9(e){return[{host:`agents`,root:ma},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=CD.indexOf(e.host),r=CD.indexOf(t.host);return(n===-1?CD.length:n)-(r===-1?CD.length:r)||e.host.localeCompare(t.host)})}const sIe=g9(st),cIe=g9(Br);function lIe(e,t){return V(z(e,si(t)))}function uIe(e,t){sc(I(t),{recursive:!0});try{ec(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;uc(e,t,{recursive:!0}),dc(e,{recursive:!0,force:!0})}}function dIe(e,t,n){let r=zI(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 _9(e,t){let n;try{n=U(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(z(e,t.dir)).startsWith(n+B)}catch{return!0}}).map(e=>e.name))}async function v9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??sIe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=Nu(n)}catch{return a}let s=R(t,n).split(B).join(`/`),c=new Set;for(let[e,n]of Object.entries(Bq(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ta.test(e)||nO.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=z(n,e);if(!V(L(o,`SKILL.md`)))continue;let s=_D(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:qI(t,i),state:dIe(L(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=>lIe(t,e.root));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`?dc(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&dc(d.path,{recursive:!0,force:!0}),uIe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(dc(e.path,{recursive:!0,force:!0}),uc(d.path,e.path,{recursive:!0}));await LN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),h9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),h9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const y9=F(`skill-reconcile`),fIe=nO;function b9(){let e=[];for(let t of Pr){let n=st[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:ma,editor:null}),e}function pIe(e,t){let n=R(e,z(t));return hu(n)?z(t):n}function x9(e){let{frontmatter:t,body:n}=ns(e),r={};if(t!==``)try{let e=(0,ZD.parse)(Ji(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function mIe(e,t){let n=x9(e),r=x9(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 S9(e,t){let n=C9(e),r=C9(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=L(e,o),c=L(t,o);if(i+=Ru(s).size+Ru(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!mIe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function C9(e,t=``){let n=[];for(let r of Nu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...C9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function w9(e,t,n){dc(t,{recursive:!0,force:!0}),sc(e,{recursive:!0}),rc(pIe(e,n),t,`dir`)}function T9(e,t){try{let n=Pu(e);return z(hu(n)?n:z(I(e),n))===z(t)}catch{return!1}}function hIe(e,t){try{let n=Pu(e),r=hu(n)?z(n):z(I(e),n);if(!V(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||hu(i))}catch(t){return y9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const gIe=[...Pr,`agents`];function _Ie(e){for(let t of gIe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function vIe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=Nu(n)}catch{return}let i=b9();for(let e of r){let r=_Ie(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(V(o))try{let n=Du(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(L(a,`SKILL.md`))||!V(L(o,`SKILL.md`))||!S9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(qI(t,r))continue;let i=L(r,e);T9(i,a)&&w9(r,i,o)}dc(a,{recursive:!0,force:!0}),y9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){y9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function yIe(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 b9()){let o=z(t,e);if(!V(o)||qI(t,o))continue;let s;try{s=Nu(o)}catch(e){y9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(fIe.has(e))continue;let t=L(o,e),s=z(n,e),c=V(s);try{let l=Du(t);if(l.isSymbolicLink()){if(T9(t,s)&&c)continue;if(hIe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(w9(o,t,s),r.healed.push({name:e,editor:i})):(dc(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ta.test(e)){y9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&S9(t,s)){w9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){y9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=PN(t);for(let[r,a]of i){let i=z(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await IN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??HI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){y9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{vIe({projectDir:t,skillsRoot:n})}catch(e){y9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let E9=null,D9=!1;function O9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function k9(e){if(!O9())return;let t=KO(e);E9=new Sc({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Kn(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};E9?.append(`${JSON.stringify(t)}\n`).catch(e=>{D9||(D9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function A9(){Kn(null),await E9?.drain(),E9=null,D9=!1}Ls();const bIe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],xIe=[`cache`,`tmp`];function SIe(e){let t=z(e,Pe);if(!(()=>{if(!V(t))return!0;try{return Nu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of bIe)V(z(e,t))&&n.push(t);for(let t of xIe){let r=z(e,t);try{V(r)&&Ru(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function CIe(e){let t=bd(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 j9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function wIe(e){ZB();let t=e.projectDir??e.contentDir,n=bxe({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}`)}bc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}vc({localSink:n?.telemetry}),k9(t),aIe(),oIe();let{kind:r,gitdir:i}=CIe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=lc(i));let o=vxe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ys(`ok.boot`,{attributes:a},async()=>TIe(e)),l=()=>{if(s)try{let e=Fs.extract(Rs.active(),{traceparent:s});return Rs.with(e,c)}catch(e){F(`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 e=>{try{await d(e)}finally{o.uninstall()}},u}async function TIe(e){let t=e.skipAutoInit??!1,n=e.log??F(`boot`),r=e.serverRuntime??{...ds(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((dt(r)||!gr(i))&&!r.allowExternal)throw new MB(`refusing to start: the server would bind a non-loopback address (${(gr(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=FB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let 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:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-C_5VGPQF.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!V(z(m,`config.yml`)))throw new Y6(V(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);V(h)||F(`boot`).warn({path:h},"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 g=e.gitPreflight??Nw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof Aw||e instanceof jw){let t=e instanceof jw?e.detected:``,r=e instanceof jw?`too_old`:`not_available`;cJ(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await _c(),await Promise.race([A9(),new Promise(e=>setTimeout(e,j9))]),e}let _=SIe(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Pe}/.`);let v=null,y=s9({getCollabClientCount:()=>v?.getCount()??0,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,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,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O}=y,ee=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),te=e.port??0,k=()=>`http://${ee}:${te}`,A=e.ephemeral?void 0:H6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:y.localApi,log:n}),ne=c();ne.headersTimeout=3e4,ne.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:uZ({contentFilter:y.contentFilter,contentSirv:CZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Fe,assetExtensions:ve,blocklistExtensions:je,ingressPolicy:a}),ie=e.reactShellDistDir?CZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,j=e.ephemeral?null:new LE({contentDir:e.contentDir,localDir:w,globalDir:z(Hu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,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:()=>k(),getMcpStdioCommand:()=>IE(e.localOpCliArgs,te,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});j!==null&&await j.init();let ae=`pending`;S.then(()=>{ae=`ready`},()=>{ae=`failed`});let oe=q6({httpServer:ne,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:A,ingressPolicy:a,health:{readiness:()=>ae,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:ie,ephemeral:e.ephemeral,acpThreadManager:j}),M=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=OZ(ne);let se=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});se=kZ({httpServer:ne,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await M(`idle-shutdown`)})})}await M9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let ce=[...new Set(i)],le=ce[0],ue=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},de=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await de(ne,e.port??0,le??`127.0.0.1`)}catch(e){throw await ue(),e}let fe=ne.address(),pe=typeof fe==`object`&&fe?fe.port:e.port??0,me=[];for(let e of ce.slice(1)){let t=c();t.headersTimeout=ne.headersTimeout,t.requestTimeout=ne.requestTimeout;for(let e of ne.listeners(`request`))t.on(`request`,e);for(let e of ne.listeners(`upgrade`))t.on(`upgrade`,e);try{await de(t,pe,e)}catch(t){n.error({err:t,failedAddress:e,port:pe,alreadyBound:me.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...me,ne])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await ue(),t}me.push(t)}let he=QB();he!==void 0&&$B(`httpListenMs`,he);let ge=ne.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0;te=_e;let ye=k();d(w,_e,ye),n.info({event:`server-listening`,pid:process.pid,port:_e,addresses:ce,url:ye,lockDir:w},`[boot] listening on ${ye}`);let be=!1,xe=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${j9}ms`))},j9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};M=async(e=`unspecified`)=>{if(be)return;be=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),ae=`draining`;let t=[],r=async(e,r)=>{try{await xe(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{se?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(j!==null&&await r(`acpThreads.destroy`,()=>j.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of me)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>oe.shutdown()),A!==void 0&&await r(`mcpHttpHandler.close`,()=>A.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{oe.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{ne.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{ne.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>_c()),await r(`teardownToleranceTelemetry`,()=>A9()),await r(`flushLogFileSinks`,()=>bc.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await v9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:_9(e.contentDir,vL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Hu(),t=await v9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:cIe,inPlaceNames:_9(e,yL(e))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await yIe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ne,destroy:M,lockDir:w,contentDir:e.contentDir,port:_e,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:kMe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:j}}async function M9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new TZ(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=xd(n),t=e?L(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=Ste({baseDir:n,timeout:{block:5e3}});s=new Set(await Xb(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=Xx(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 EIe=i;function DIe(e={}){let t=e.home??Hu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var N9=t(yte(),1);const P9=L(Hu(),`.ok`,`logs`),OIe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function kIe(){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 AIe(e){Ou(e,{recursive:!0})}function F9(){return new Date().toISOString().slice(0,10)}function jIe(e){try{if(Ru(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{Fu(n,r)}catch{}}try{zu(`${e}.3`)}catch{}}function MIe(e){try{let t=Date.now(),n=10080*60*1e3,r=Nu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Ru(L(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{zu(L(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{zu(L(e,t.name)),a-=t.size}catch{}}}catch{}}function NIe(e){AIe(P9);let t=F9(),n=e.filePath??L(P9,`${e.name}.${t}.log`);jIe(n),(e._setTimeout??setTimeout)(()=>MIe(P9),5e3).unref();let r=N9.default.destination({dest:n,append:!0,sync:!0});return(0,N9.default)({level:kIe(),name:e.name,redact:{paths:OIe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:N9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function PIe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[N9.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 FIe(e){return L(P9,`${e}.${F9()}.log`)}function IIe(){return P9}function LIe(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=V(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const I9=ld(cu),L9=F(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function RIe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],Dw({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function zIe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],Dw({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function BIe(e){let t=z(e,`packed-refs`);if(V(t))try{if(H(t,`utf-8`).split(`
2036
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),x.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){x.error({err:e},`[branch-switch] detached cleanup failed`)}O(!1),await N.flushDeferredStores(`discard-stale`),t=!0,Oe?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(O(!1),await N.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=m??`.`;try{let n=await Rx(be.current,t,e.oldHead,e.newHead,i);ex(),x.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){x.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){x.error({err:e},`[server] HEAD watcher failed to start`),dn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=rN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Xx(e),a=Ce.documents.get(i);if(!a)continue;let o=qt(i);o===null?x.warn({docName:i,file:t},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):T(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),x.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){x.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function u(e){for(let t of e)try{let e=rN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Xx(e));i&&Yt(i)}catch(e){x.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=QF(r);x.debug({resetAmbientCredentials:f,originKind:XF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let p=Dc(g,{resetAmbient:f}),h=A(),_=ne();h.mode!==`off`&&x.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{sn=new QFe({projectDir:r,contentDir:n,contentFilter:ve,contentRoot:m,mcpTomlEditor:e.mcpTomlEditor,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:p,cc1Broadcaster:Oe,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{O(e),e||N.flushDeferredStores(`within-branch`).catch(e=>{x.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{x.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:u,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=be.current;n&&await Bx(n,m??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await Bx(n,m??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{x.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ac({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||x.error({result:t,reason:e,humanError:Re(t.error),configPath:Vs(`project-local`,r)},`[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 sn.start()}catch(e){x.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),sn=null}Je(`files`),ye.announceReadyViews();let v=QB();v!==void 0&&$B(`readyMs`,v),M()}return fn().then(()=>{Qe=!0,He(),ft(),vt()},e=>{$e=!0,et.abort(),lt({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:S,sessionManager:we,nativeApi:Te,localApi:Ee,cc1Broadcaster:Oe,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:xe,contentFilter:ve,basenameIndex:he,serverInstanceId:de,destroy:un,ready:We,generatedIndexSweepReady:ct,degraded:dn,lockDir:fe,get syncEngine(){return sn},getLinkPreviewsEnabled:ae,resolveEmbed:ge,acpRegistry:pe,acpPermissions:me}}function c9(e){return e/1048576}function iIe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:c9(e.rss),heapTotalMb:c9(e.heapTotal),heapUsedMb:c9(e.heapUsed),externalMb:c9(e.external),arrayBuffersMb:c9(e.arrayBuffers)}}}let l9=null,u9=null,d9=null;const f9=1e6;let p9=null,m9=null;Js(()=>{l9=null,u9=null,d9=null,p9?.disable(),p9=null,m9=null});function aIe(){if(l9)return;let e=yc().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}=iIe();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`})}),l9=e}function oIe(){if(!u9){let e=yc().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(!p9){p9=nne({resolution:20}),p9.enable();return}e.observe(p9.percentile(50)/f9,{stat:`p50`}),e.observe(p9.percentile(99)/f9,{stat:`p99`}),p9.reset()}),u9=e}if(!d9){let e=yc().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=m9;if(m9={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`}))}),d9=e}}const h9=F(`skill-migrate`);function g9(e){return[{host:`agents`,root:ma},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=CD.indexOf(e.host),r=CD.indexOf(t.host);return(n===-1?CD.length:n)-(r===-1?CD.length:r)||e.host.localeCompare(t.host)})}const sIe=g9(st),cIe=g9(Br);function lIe(e,t){return V(z(e,si(t)))}function uIe(e,t){sc(I(t),{recursive:!0});try{ec(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;uc(e,t,{recursive:!0}),dc(e,{recursive:!0,force:!0})}}function dIe(e,t,n){let r=zI(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 _9(e,t){let n;try{n=U(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!U(z(e,t.dir)).startsWith(n+B)}catch{return!0}}).map(e=>e.name))}async function v9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??sIe,a={migrated:[],skipped:[]};if(!V(n))return a;let o;try{o=Nu(n)}catch{return a}let s=R(t,n).split(B).join(`/`),c=new Set;for(let[e,n]of Object.entries(Bq(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ta.test(e)||nO.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=z(n,e);if(!V(L(o,`SKILL.md`)))continue;let s=_D(o)?.contentHash;if(s===void 0)continue;let l=U(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:qI(t,i),state:dIe(L(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=>lIe(t,e.root));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`?dc(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&dc(d.path,{recursive:!0,force:!0}),uIe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(dc(e.path,{recursive:!0,force:!0}),uc(d.path,e.path,{recursive:!0}));await LN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),h9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),h9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const y9=F(`skill-reconcile`),fIe=nO;function b9(){let e=[];for(let t of Pr){let n=st[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:ma,editor:null}),e}function pIe(e,t){let n=R(e,z(t));return hu(n)?z(t):n}function x9(e){let{frontmatter:t,body:n}=ns(e),r={};if(t!==``)try{let e=(0,ZD.parse)(Ji(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function mIe(e,t){let n=x9(e),r=x9(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 S9(e,t){let n=C9(e),r=C9(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=L(e,o),c=L(t,o);if(i+=Ru(s).size+Ru(c).size,i>1048576)return!1;let l=H(s),u=H(c);if(!l.equals(u)&&(o!==`SKILL.md`||!mIe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function C9(e,t=``){let n=[];for(let r of Nu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...C9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function w9(e,t,n){dc(t,{recursive:!0,force:!0}),sc(e,{recursive:!0}),rc(pIe(e,n),t,`dir`)}function T9(e,t){try{let n=Pu(e);return z(hu(n)?n:z(I(e),n))===z(t)}catch{return!1}}function hIe(e,t){try{let n=Pu(e),r=hu(n)?z(n):z(I(e),n);if(!V(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||hu(i))}catch(t){return y9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const gIe=[...Pr,`agents`];function _Ie(e){for(let t of gIe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function vIe(e){let{projectDir:t,skillsRoot:n}=e;if(!V(n))return;let r;try{r=Nu(n)}catch{return}let i=b9();for(let e of r){let r=_Ie(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(V(o))try{let n=Du(a);if(n.isSymbolicLink()||!n.isDirectory()||!V(L(a,`SKILL.md`))||!V(L(o,`SKILL.md`))||!S9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(qI(t,r))continue;let i=L(r,e);T9(i,a)&&w9(r,i,o)}dc(a,{recursive:!0,force:!0}),y9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){y9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function yIe(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 b9()){let o=z(t,e);if(!V(o)||qI(t,o))continue;let s;try{s=Nu(o)}catch(e){y9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(fIe.has(e))continue;let t=L(o,e),s=z(n,e),c=V(s);try{let l=Du(t);if(l.isSymbolicLink()){if(T9(t,s)&&c)continue;if(hIe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(w9(o,t,s),r.healed.push({name:e,editor:i})):(dc(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ta.test(e)){y9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&S9(t,s)){w9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){y9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=PN(t);for(let[r,a]of i){let i=z(n,r);if(!V(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await IN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??HI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){y9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{vIe({projectDir:t,skillsRoot:n})}catch(e){y9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let E9=null,D9=!1;function O9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function k9(e){if(!O9())return;let t=KO(e);E9=new Sc({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),Kn(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};E9?.append(`${JSON.stringify(t)}\n`).catch(e=>{D9||(D9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function A9(){Kn(null),await E9?.drain(),E9=null,D9=!1}Ls();const bIe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],xIe=[`cache`,`tmp`];function SIe(e){let t=z(e,Pe);if(!(()=>{if(!V(t))return!0;try{return Nu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of bIe)V(z(e,t))&&n.push(t);for(let t of xIe){let r=z(e,t);try{V(r)&&Ru(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function CIe(e){let t=bd(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 j9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function wIe(e){ZB();let t=e.projectDir??e.contentDir,n=bxe({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}`)}bc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}vc({localSink:n?.telemetry}),k9(t),aIe(),oIe();let{kind:r,gitdir:i}=CIe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=lc(i));let o=vxe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ys(`ok.boot`,{attributes:a},async()=>TIe(e)),l=()=>{if(s)try{let e=Fs.extract(Rs.active(),{traceparent:s});return Rs.with(e,c)}catch(e){F(`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 e=>{try{await d(e)}finally{o.uninstall()}},u}async function TIe(e){let t=e.skipAutoInit??!1,n=e.log??F(`boot`),r=e.serverRuntime??{...ds(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((dt(r)||!gr(i))&&!r.allowExternal)throw new MB(`refusing to start: the server would bind a non-loopback address (${(gr(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=FB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let 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:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-D8d0WVYU.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!V(z(m,`config.yml`)))throw new Y6(V(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);V(h)||F(`boot`).warn({path:h},"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 g=e.gitPreflight??Nw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof Aw||e instanceof jw){let t=e instanceof jw?e.detected:``,r=e instanceof jw?`too_old`:`not_available`;cJ(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await _c(),await Promise.race([A9(),new Promise(e=>setTimeout(e,j9))]),e}let _=SIe(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${Pe}/.`);let v=null,y=s9({getCollabClientCount:()=>v?.getCount()??0,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,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,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O}=y,ee=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),te=e.port??0,k=()=>`http://${ee}:${te}`,A=e.ephemeral?void 0:H6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:y.localApi,log:n}),ne=c();ne.headersTimeout=3e4,ne.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:uZ({contentFilter:y.contentFilter,contentSirv:CZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Fe,assetExtensions:ve,blocklistExtensions:je,ingressPolicy:a}),ie=e.reactShellDistDir?CZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,j=e.ephemeral?null:new LE({contentDir:e.contentDir,localDir:w,globalDir:z(Hu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,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:()=>k(),getMcpStdioCommand:()=>IE(e.localOpCliArgs,te,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});j!==null&&await j.init();let ae=`pending`;S.then(()=>{ae=`ready`},()=>{ae=`failed`});let oe=q6({httpServer:ne,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:A,ingressPolicy:a,health:{readiness:()=>ae,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:O,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:ie,ephemeral:e.ephemeral,acpThreadManager:j}),M=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=OZ(ne);let se=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});se=kZ({httpServer:ne,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await M(`idle-shutdown`)})})}await M9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let ce=[...new Set(i)],le=ce[0],ue=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},de=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await de(ne,e.port??0,le??`127.0.0.1`)}catch(e){throw await ue(),e}let fe=ne.address(),pe=typeof fe==`object`&&fe?fe.port:e.port??0,me=[];for(let e of ce.slice(1)){let t=c();t.headersTimeout=ne.headersTimeout,t.requestTimeout=ne.requestTimeout;for(let e of ne.listeners(`request`))t.on(`request`,e);for(let e of ne.listeners(`upgrade`))t.on(`upgrade`,e);try{await de(t,pe,e)}catch(t){n.error({err:t,failedAddress:e,port:pe,alreadyBound:me.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...me,ne])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await ue(),t}me.push(t)}let he=QB();he!==void 0&&$B(`httpListenMs`,he);let ge=ne.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0;te=_e;let ye=k();d(w,_e,ye),n.info({event:`server-listening`,pid:process.pid,port:_e,addresses:ce,url:ye,lockDir:w},`[boot] listening on ${ye}`);let be=!1,xe=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${j9}ms`))},j9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};M=async(e=`unspecified`)=>{if(be)return;be=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),ae=`draining`;let t=[],r=async(e,r)=>{try{await xe(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{se?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(j!==null&&await r(`acpThreads.destroy`,()=>j.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of me)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>oe.shutdown()),A!==void 0&&await r(`mcpHttpHandler.close`,()=>A.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{oe.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{ne.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{ne.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>_c()),await r(`teardownToleranceTelemetry`,()=>A9()),await r(`flushLogFileSinks`,()=>bc.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await v9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:_9(e.contentDir,vL(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Hu(),t=await v9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:cIe,inPlaceNames:_9(e,yL(e))});t.migrated.length+t.skipped.length>0&&n.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){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await yIe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ne,destroy:M,lockDir:w,contentDir:e.contentDir,port:_e,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:kMe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:j}}async function M9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new TZ(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=xd(n),t=e?L(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=Ste({baseDir:n,timeout:{block:5e3}});s=new Set(await Xb(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=Xx(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 EIe=i;function DIe(e={}){let t=e.home??Hu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?V(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?V(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var N9=t(yte(),1);const P9=L(Hu(),`.ok`,`logs`),OIe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function kIe(){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 AIe(e){Ou(e,{recursive:!0})}function F9(){return new Date().toISOString().slice(0,10)}function jIe(e){try{if(Ru(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{Fu(n,r)}catch{}}try{zu(`${e}.3`)}catch{}}function MIe(e){try{let t=Date.now(),n=10080*60*1e3,r=Nu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Ru(L(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{zu(L(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{zu(L(e,t.name)),a-=t.size}catch{}}}catch{}}function NIe(e){AIe(P9);let t=F9(),n=e.filePath??L(P9,`${e.name}.${t}.log`);jIe(n),(e._setTimeout??setTimeout)(()=>MIe(P9),5e3).unref();let r=N9.default.destination({dest:n,append:!0,sync:!0});return(0,N9.default)({level:kIe(),name:e.name,redact:{paths:OIe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:N9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function PIe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[N9.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 FIe(e){return L(P9,`${e}.${F9()}.log`)}function IIe(){return P9}function LIe(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=V(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const I9=ld(cu),L9=F(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function RIe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],Dw({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function zIe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],Dw({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function BIe(e){let t=z(e,`packed-refs`);if(V(t))try{if(H(t,`utf-8`).split(`
2037
2037
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return Nu(z(e,`refs/heads`)).length>0}catch{return!1}}function z9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function B9(e,t){if(await zIe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await RIe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await I9(e,i,Dw({cwd:t,encoding:`utf-8`})),r||L9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){L9.warn({path:t,stderr:z9(e)},`could not create initial commit`)}}async function VIe(e,t){try{let{stdout:n}=await I9(e,[`rev-parse`,`--is-inside-work-tree`],Dw({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function HIe(e){let t=z(e);Jq(t);let n=z(t,`.git`),r=z(n,`HEAD`),i=!1,a=!1;if(V(n)){if(!Ru(n).isDirectory())return{didInit:!1};if(V(r)){if(BIe(n))return{didInit:!1};a=!0}else L9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=Nw()}catch(e){throw e instanceof Aw||e instanceof jw?(cJ(e),L9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof jw?`too_old`:`not_available`,detectedVersion:e instanceof jw?e.detected:``},e instanceof jw?`git binary too old`:`git binary not found`)):L9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await B9(s,t),{didInit:!1};if(!i&&await VIe(s,t))return{didInit:!1};let c=``;try{c=(await I9(s,[`init`,`--initial-branch=main`,t],Dw({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new R9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!V(r))throw new R9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await B9(s,t),i?(L9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(L9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const V9=F(`project-skill-git`),H9=/^[0-9a-f]{40}$/,UIe=Kr.map(e=>e.replace(/\/$/,``));async function WIe(e){let t=xd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(JIe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Ec(e,{credentialConfig:[]});if((await U9(n)).length===0)return{kind:`nothing-tracked`};try{return await Tc(async()=>{let t=await GIe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await KIe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await U9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Ec(e,{gitIndexFile:L(Gu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`),credentialConfig:[]});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 qIe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await uB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;kc(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 \`${Jt}\` 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(!H9.test(f))return V9.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 V9.info({branch:t,err:W9(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){V9.info({err:W9(e)},`real-index reset after untrack failed (cosmetic)`)}return V9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:W9(e)}}}async function U9(e){let t=[];for(let n of UIe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function GIe(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 KIe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return H9.test(t)?t:null}catch{return null}}async function qIe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return H9.test(n)?n:null}catch{return null}}function JIe(e){return V(L(e,`MERGE_HEAD`))||V(L(e,`rebase-merge`))||V(L(e,`rebase-apply`))||V(L(e,`CHERRY_PICK_HEAD`))||V(L(e,`REVERT_HEAD`))}function W9(e){return e instanceof Error?e.message:String(e)}async function YIe(e,t){let n;try{n=su(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=I(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(V(n))try{let t=JSON.parse(await Yu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=I(t);if(r===t)return;t=r}}const XIe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function G9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of XIe)t=t.replace(e,n);return t}function K9(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:G9(e.message)??``,stack:G9(e.stack),code:e.code,cause:e.cause===void 0?void 0:K9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:G9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:G9(String(r.message??``))??``,stack:G9(r.stack),code:r.code,cause:r.cause===void 0?void 0:K9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var q9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},J9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},Y9=class extends Error{constructor(e,t){super(`Cannot open with --project ${e}: ${t}`),this.projectRoot=e,this.name=`SingleFileProjectOverrideError`}},X9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function ZIe(e,t={}){if(!Jx(e))throw new X9(e);let n;try{n=U(z(e))}catch(t){throw t.code===`ENOENT`?new q9(e):t}if(!Ru(n).isFile())throw new J9(e);let r=I(n);if(t.projectRoot!==void 0){let e=z(t.projectRoot);if(!zN(e))throw new Y9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=R(Z9(e),n);if(r.startsWith(`..`)||hu(r))throw new Y9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:Xx(r.split(B).join(`/`)),canonicalFilePath:n}}let i=BN(r);if(i){let e=i.rootPath;return{mode:`project`,projectRoot:e,docName:Xx(R(Z9(e),n).split(B).join(`/`)),canonicalFilePath:n}}let a=fu(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:Xx(a)}}function Z9(e){return z(e,Gs({absPath:Vs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}const Q9=`ok-ephemeral-`;function $9(e,t){let n=z(e,`.ok`);return Ou(n,{recursive:!0}),Bu(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),Bu(z(n,`.gitignore`),`local/
2038
2038
  `,`utf-8`),e}function QIe(e){return $9(ku(z(Gu(),Q9)),e)}export{k6 as $,vS as $i,RI as $n,Jfe as $r,XJ as $t,T7 as A,Hd as Aa,Hw as Ai,wB as An,qP as Ar,fZ as At,Q5 as B,Dw as Bi,qz as Bn,vN as Br,aY as Bt,k9 as C,ax as Ca,qD as Ci,UB as Cn,tF as Cr,mZ as Ct,o9 as D,Th as Da,LE as Di,IB as Dn,XP as Dr,hZ as Dt,s9 as E,Ch as Ea,qE as Ei,zB as En,ZP as Er,gZ as Et,x7 as F,zd as Fa,Nw as Fi,jz as Fn,BN as Fr,Kbe as Ft,R5 as G,Sw as Gi,HR as Gn,aN as Gr,eY as Gt,SPe as H,Cw as Hi,sz as Hn,mN as Hr,WJ as Ht,h7 as I,Sd as Ia,Vw as Ii,Dz as In,zN as Ir,lZ as It,q6 as J,KC as Ji,WR as Jn,mM as Jr,Bve as Jt,J6 as K,gw as Ki,UR as Kn,GM as Kr,JJ as Kt,f7 as L,md as La,Mw as Li,Sz as Ln,_N as Lr,sZ as Lt,C7 as M,Vd as Ma,Aw as Mi,Az as Mn,WP as Mr,jX as Mt,E7 as N,Td as Na,jw as Ni,dz as Nn,_P as Nr,AX as Nt,q7 as O,wh as Oa,DE as Oi,EB as On,JP as Or,oxe as Ot,D7 as P,wd as Pa,Ow as Pi,uz as Pn,vme as Pr,Gbe as Pt,z6 as Q,TS as Qi,sR as Qn,Kfe as Qr,$J as Qt,X5 as R,Rw as Ri,lz as Rn,gN as Rr,PX as Rt,M9 as S,fx as Sa,ofe as Si,FB as Sn,iF as Sr,yZ as St,A9 as T,Uie as Ta,JE as Ti,RB as Tn,YP as Tr,pZ as Tt,W5 as U,Ew as Ui,YR as Un,lN as Ur,Vve as Ut,Z5 as V,dw as Vi,Oz as Vn,yN as Vr,rY as Vt,V5 as W,xw as Wi,XR as Wn,fN as Wr,zve as Wt,W6 as X,ES as Xi,jR as Xn,uM as Xr,QJ as Xt,K6 as Y,lw as Yi,BR as Yn,pM as Yr,tY as Yt,H6 as Z,K as Zi,gR as Zn,Yfe as Zr,ZJ as Zt,FIe as _,Vx as _a,iO as _i,Gq as _n,ZF as _r,uSe as _t,Y9 as a,Ux as aa,qj as ai,cJ as an,OI as ar,I0 as at,EIe as b,gx as ba,afe as bi,qq as bn,nF as br,OZ as bt,$9 as c,Ix as ca,Hj as ci,iJ as cn,EI as cr,Gwe as ct,WIe as d,kx as da,KO as di,tJ as dn,DI as dr,w0 as dt,lS as ea,qfe as ei,zJ as en,II as er,H0 as et,R9 as f,Nx as fa,GO as fi,Zq as fn,fI as fr,x0 as ft,PIe as g,Bx as ga,dO as gi,G_e as gn,KF as gr,ZQ as gt,NIe as h,Hx as ha,lO as hi,H_e as hn,cI as hr,y$ as ht,X9 as i,cS as ia,Cfe as ii,sJ as in,jI as ir,iTe as it,O7 as j,Qd as ja,Ww as ji,iz as jn,UP as jr,uZ as jt,S7 as k,Zd as ka,IE as ki,TB as kn,KP as kr,vZ as kt,K9 as l,jx as la,Gj as li,Yq as ln,TI as lr,Kwe as lt,LIe as m,Dx as ma,fO as mi,nJ as mn,dI as mr,U1 as mt,J9 as n,uS as na,$j as ni,uJ as nn,oge as nr,W0 as nt,QIe as o,Px as oa,xfe as oi,Z_e as on,kI as or,F0 as ot,HIe as p,Wx as pa,qO as pi,q_e as pn,uI as pr,C0 as pt,Y6 as q,GC as qi,GR as qn,WM as qr,YJ as qt,q9 as r,mS as ra,oM as ri,$_e as rn,NI as rr,Y0 as rt,ZIe as s,Fx as sa,Kj as si,X_e as sn,AI as sr,A0 as st,Q9 as t,hS as ta,Ife as ti,BJ as tn,dge as tr,U0 as tt,YIe as u,Rx as ua,Wj as ui,eJ as un,Qhe as ur,qwe as ut,IIe as v,Gx as va,aO as vi,Jq as vn,WF as vr,f$ as vt,O9 as w,Yse as wa,YE as wi,AB as wn,Lme as wr,_Z as wt,wIe as x,mx as xa,oO as xi,MB as xn,rF as xr,kZ as xt,DIe as y,wx as ya,tO as yi,Kq as yn,_F as yr,h$ as yt,PPe as z,Fw as zi,kz as zn,bN as zr,Jve as zt};
2039
- //# sourceMappingURL=src-CjFV1e1Z.mjs.map
2039
+ //# sourceMappingURL=src-CNSuUQTi.mjs.map