@inkeep/open-knowledge 0.50.0-beta.4 → 0.50.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (443) hide show
  1. package/dist/acp-harness-probe-PEHo_hYG.mjs +3 -0
  2. package/dist/cli.mjs +20 -20
  3. package/dist/constants-D9HRzNQG.mjs +2 -0
  4. package/dist/git-handle-B24ZRv9k.mjs +1 -0
  5. package/dist/{git-handle-oaKkz-wn.mjs → git-handle-D48CPnbp.mjs} +2 -2
  6. package/dist/index.d.mts +22 -20
  7. package/dist/index.mjs +135 -135
  8. package/dist/{init-GU2008y6.mjs → init-BJCusUuy.mjs} +3 -3
  9. package/dist/init-zePCt6tf.mjs +1 -0
  10. package/dist/{launch-json-removal-CBvAsHwv.mjs → launch-json-removal-BXFgQzfH.mjs} +2 -2
  11. package/dist/loader-DDNAwcPM.mjs +1 -0
  12. package/dist/{loader-C07VPlQo.mjs → loader-DbPx77mt.mjs} +2 -2
  13. package/dist/md-manager-DLcJdRDn.mjs +2 -0
  14. package/dist/{open-browser-S-UcIs_h.mjs → open-browser-DITljs8e.mjs} +2 -2
  15. package/dist/parse-worker.mjs +1 -1
  16. package/dist/preview-AsssSL6s.mjs +1 -0
  17. package/dist/{preview-JHv_lbF-.mjs → preview-DXyVMz8b.mjs} +2 -2
  18. package/dist/public/assets/{ActivityModeContent-oK0Ukipq.js → ActivityModeContent-c7Ng5dOt.js} +1 -1
  19. package/dist/public/assets/{AgentDiffPane-c-eXlgET.js → AgentDiffPane-CdvdlrTA.js} +2 -2
  20. package/dist/public/assets/{AgentThreadClientBinder-BjgVrGGG.js → AgentThreadClientBinder-CvHvukLZ.js} +1 -1
  21. package/dist/public/assets/{AppMenubar-Dk1BEmD9.js → AppMenubar-DzKyqu4x.js} +1 -1
  22. package/dist/public/assets/{BugReportHistory-CRlvJE2K.js → BugReportHistory-BJFLBqUw.js} +1 -1
  23. package/dist/public/assets/{BugReportHistoryDialog-DIqnZXkT.js → BugReportHistoryDialog-y4fa4pzg.js} +1 -1
  24. package/dist/public/assets/{ChangedOutsideBadge-Tm9eQzQd.js → ChangedOutsideBadge-Bu8uPTJS.js} +1 -1
  25. package/dist/public/assets/CodeMirrorPropInput-fWbdlCkS.js +3 -0
  26. package/dist/public/assets/{ConfigSharingInfoTooltip-BNI3Q3Qo.js → ConfigSharingInfoTooltip-BPA8HEYl.js} +1 -1
  27. package/dist/public/assets/{ConsentDialogBody-BlayjFQq.js → ConsentDialogBody-KXeO_ZFL.js} +1 -1
  28. package/dist/public/assets/{CopyButton-Q-6hSzy6.js → CopyButton-DhHoiQJR.js} +1 -1
  29. package/dist/public/assets/{DiffView-BnNY_4OT.js → DiffView-BjOsi4GM.js} +1 -1
  30. package/dist/public/assets/{DocumentContext-BZs9wGsy.js → DocumentContext-sNpqhUlI.js} +11 -11
  31. package/dist/public/assets/{EditorModeToggle-Dx-H0DAT.js → EditorModeToggle-D4871FSZ.js} +1 -1
  32. package/dist/public/assets/{EnableSyncConfirmDialog-Djkj66_G.js → EnableSyncConfirmDialog-cBuI6coM.js} +1 -1
  33. package/dist/public/assets/FeedbackForm-BFd0ubqI.js +1 -0
  34. package/dist/public/assets/{GraphPanel-5y13eIH-.js → GraphPanel-CAMYjjtr.js} +2 -2
  35. package/dist/public/assets/{ImportSkillDialog-BpbNmo53.js → ImportSkillDialog-BepHDHz6.js} +1 -1
  36. package/dist/public/assets/{LintConfigEditor-B8UqIDri.js → LintConfigEditor-DRA7zDJD.js} +1 -1
  37. package/dist/public/assets/ManagedArtifactProperties-CLh5T0qS.js +2 -0
  38. package/dist/public/assets/ManagedArtifactProperties-Ct_XfVJo.js +1 -0
  39. package/dist/public/assets/{McpConsentDialogBody-DmSeUtFh.js → McpConsentDialogBody-ONRUf-u9.js} +1 -1
  40. package/dist/public/assets/{Mermaid-cUFqNhzC.js → Mermaid-D-pcyGRV.js} +2 -2
  41. package/dist/public/assets/{MermaidDocEditor-yGV5TYvo.js → MermaidDocEditor-DC95RR-G.js} +1 -1
  42. package/dist/public/assets/{RegisteredAgentIcon-CCgDsAUc.js → RegisteredAgentIcon-BgDInKA9.js} +1 -1
  43. package/dist/public/assets/{ReportBugDialogBody-B0bj47YU.js → ReportBugDialogBody-7VaenClj.js} +1 -1
  44. package/dist/public/assets/{SchemaConfigEditor-OWVRrCyd.js → SchemaConfigEditor-B2VRQNhY.js} +1 -1
  45. package/dist/public/assets/SessionsHost-CJM2wXx0.js +2 -0
  46. package/dist/public/assets/SettingsDialogBody-LwuRFjnU.js +12 -0
  47. package/dist/public/assets/{ShareBranchSwitchDialog-295DE9n_.js → ShareBranchSwitchDialog-DD7xybfa.js} +1 -1
  48. package/dist/public/assets/{ShareReceiveDialog-BbOB46ar.js → ShareReceiveDialog-Bz3zpKKF.js} +1 -1
  49. package/dist/public/assets/{ShareReceiveMissDialog-iz73ffK2.js → ShareReceiveMissDialog-DqXylco3.js} +1 -1
  50. package/dist/public/assets/{SkillEditBanner-C0motCdk.js → SkillEditBanner-BwzPIxd8.js} +1 -1
  51. package/dist/public/assets/{SkillOriginInline-BKp-kWXv.js → SkillOriginInline-BFCXo8sI.js} +1 -1
  52. package/dist/public/assets/SkillToolbarControls-DF0m8f6g.js +1 -0
  53. package/dist/public/assets/{SlidesToolbarControls-CD_n21A3.js → SlidesToolbarControls-DJXDoZdd.js} +1 -1
  54. package/dist/public/assets/SourceEditor-CBToWgb8.js +1 -0
  55. package/dist/public/assets/{TerminalPanel-CLfRiG4p.js → TerminalPanel-BlK8X0ar.js} +2 -2
  56. package/dist/public/assets/{TerminalWindowApp-B2TPEGtR.js → TerminalWindowApp-Cy9Ov0_z.js} +1 -1
  57. package/dist/public/assets/{TextDocEditor-DmN6Zt5R.js → TextDocEditor-D3Hjb2Vu.js} +1 -1
  58. package/dist/public/assets/{ThreadView-Cn6Viupp.js → ThreadView-YWeuTsL5.js} +3 -3
  59. package/dist/public/assets/{TimelineDiffPane-DzMaO_MM.js → TimelineDiffPane-CGiWI4cl.js} +2 -2
  60. package/dist/public/assets/{abnfDiagram-VRR7QNED-zrdnvCxH.js → abnfDiagram-VRR7QNED-CQ5y3jGZ.js} +1 -1
  61. package/dist/public/assets/{agent-diff-store-CBfJPWXq.js → agent-diff-store-CEeOURzl.js} +1 -1
  62. package/dist/public/assets/{arc-DNWUH4a1.js → arc-DllfmQO6.js} +1 -1
  63. package/dist/public/assets/architecture-TIHT7OUA-CIR5HZsg.js +1 -0
  64. package/dist/public/assets/{architectureDiagram-ZJ3FMSHR-C8Bd5LWV.js → architectureDiagram-ZJ3FMSHR-DEDVgPeV.js} +1 -1
  65. package/dist/public/assets/arrow-up-right-D_WN0VGP.js +1 -0
  66. package/dist/public/assets/{auth-state-cache-DBVfH7MV.js → auth-state-cache-kFk2nWdi.js} +4 -4
  67. package/dist/public/assets/{blockDiagram-677ZJIJ3-B9IYmQZQ.js → blockDiagram-677ZJIJ3-Biovo5Vk.js} +1 -1
  68. package/dist/public/assets/{braces-54VO1tdr.js → braces-B2tgJ4cu.js} +1 -1
  69. package/dist/public/assets/{c4Diagram-LMCZKHZV-BAmqGVbu.js → c4Diagram-LMCZKHZV-BUMbkcfU.js} +1 -1
  70. package/dist/public/assets/{calendar-BhCmsdcp.js → calendar-q3K0fDI1.js} +1 -1
  71. package/dist/public/assets/{case-sensitive-BpYLDHFG.js → case-sensitive-Cz58rAyi.js} +1 -1
  72. package/dist/public/assets/channel-C6KgPQqg.js +1 -0
  73. package/dist/public/assets/check-xiKupoJh.js +1 -0
  74. package/dist/public/assets/{checkbox-gpfWb1pY.js → checkbox-DxTkAw0k.js} +1 -1
  75. package/dist/public/assets/{chevron-down-Ccgt58N5.js → chevron-down-DmoBYxyq.js} +1 -1
  76. package/dist/public/assets/chevron-left-CiNweXA3.js +1 -0
  77. package/dist/public/assets/chevron-right-DJvandMc.js +1 -0
  78. package/dist/public/assets/{chevron-up-DXAtCwKR.js → chevron-up-eNJS5_XA.js} +1 -1
  79. package/dist/public/assets/chunk-2Q5K7J3B-CgG_zTm9.js +1 -0
  80. package/dist/public/assets/{chunk-32BRIVSS-DMLdlgjI.js → chunk-32BRIVSS-CJfLw0io.js} +1 -1
  81. package/dist/public/assets/{chunk-52WLFC77-CA6wNZGK.js → chunk-52WLFC77-CKUXR-Lo.js} +1 -1
  82. package/dist/public/assets/{chunk-5FCAYU7R-DqJZ_M2Z.js → chunk-5FCAYU7R-Blhoqerk.js} +1 -1
  83. package/dist/public/assets/{chunk-5HE753X5-xEmSuz1X.js → chunk-5HE753X5-Be3l52OO.js} +1 -1
  84. package/dist/public/assets/{chunk-5JV3BV7I-Ck8lDs_Z.js → chunk-5JV3BV7I-COJRGdXn.js} +1 -1
  85. package/dist/public/assets/{chunk-5TONJI2A-PrC_RJYQ.js → chunk-5TONJI2A-6Fwn-ZXg.js} +1 -1
  86. package/dist/public/assets/{chunk-5VM5RSS4-uHW5nKzV.js → chunk-5VM5RSS4-CBB7ddJZ.js} +1 -1
  87. package/dist/public/assets/{chunk-7BUUIJ7U-QsQRXodN.js → chunk-7BUUIJ7U-BCqa-5nq.js} +1 -1
  88. package/dist/public/assets/{chunk-BIQX33UG-Bn3R7PMg.js → chunk-BIQX33UG-DzD4i2B0.js} +1 -1
  89. package/dist/public/assets/{chunk-BO2N2NFS-XrP3H1kD.js → chunk-BO2N2NFS-KCTBsTca.js} +3 -3
  90. package/dist/public/assets/{chunk-C7G6YPKG-Cyi6lMg0.js → chunk-C7G6YPKG-DxT1wdEz.js} +1 -1
  91. package/dist/public/assets/{chunk-CQNSW5MT-DcGjpkNq.js → chunk-CQNSW5MT-DFeH5OJq.js} +1 -1
  92. package/dist/public/assets/{chunk-CYSBUYHQ-DtqK9e9B.js → chunk-CYSBUYHQ-BnJMwkKI.js} +1 -1
  93. package/dist/public/assets/{chunk-EMLP6XTP-CwGsiDUi.js → chunk-EMLP6XTP-MSvlJ735.js} +1 -1
  94. package/dist/public/assets/{chunk-EX3LRPZG-DLPjvnJt.js → chunk-EX3LRPZG-DUzsTxw6.js} +1 -1
  95. package/dist/public/assets/{chunk-FWX5IMBZ-Dl1Yx5lK.js → chunk-FWX5IMBZ-D3EMolHi.js} +2 -2
  96. package/dist/public/assets/{chunk-HOUHSVGY-DV13h0Pr.js → chunk-HOUHSVGY-CA499J_e.js} +1 -1
  97. package/dist/public/assets/{chunk-ICXQ74PX-INpeR2_Y.js → chunk-ICXQ74PX-CNLojPkU.js} +1 -1
  98. package/dist/public/assets/{chunk-JG7HCLWE-DjqF4wz1.js → chunk-JG7HCLWE-BjvLoZ4O.js} +1 -1
  99. package/dist/public/assets/{chunk-JWPE2WC7-ChNUGWh8.js → chunk-JWPE2WC7-DKo0ygBr.js} +1 -1
  100. package/dist/public/assets/{chunk-MOJQB5TN-DYAyc4PI.js → chunk-MOJQB5TN-hxtcpfx_.js} +1 -1
  101. package/dist/public/assets/{chunk-MOZMSUNE-DAoBuwD4.js → chunk-MOZMSUNE-DQOK9LgW.js} +1 -1
  102. package/dist/public/assets/{chunk-OGEWGWER-_vqBGeRc.js → chunk-OGEWGWER-DmUP6YIh.js} +1 -1
  103. package/dist/public/assets/{chunk-OSBZ3O6U-SeZvOun8.js → chunk-OSBZ3O6U-D1WpsIpR.js} +1 -1
  104. package/dist/public/assets/{chunk-PUDLZKDR-C184t24_.js → chunk-PUDLZKDR-CQKVQESS.js} +1 -1
  105. package/dist/public/assets/{chunk-Q4XR5HBZ-SaCK9erE.js → chunk-Q4XR5HBZ-CChmYrK9.js} +1 -1
  106. package/dist/public/assets/{chunk-QBLGF6JB-CJVMUUtn.js → chunk-QBLGF6JB-CgndLuEz.js} +1 -1
  107. package/dist/public/assets/{chunk-R7FJI6CG-q21e0CIM.js → chunk-R7FJI6CG-DCv2sUq2.js} +1 -1
  108. package/dist/public/assets/{chunk-RYQCIY6F-nQAz-0yS.js → chunk-RYQCIY6F-AIaldrY4.js} +1 -1
  109. package/dist/public/assets/{chunk-U6XO7XAA-hembI7o8.js → chunk-U6XO7XAA-CxMMdww-.js} +1 -1
  110. package/dist/public/assets/{chunk-V7JOEXUC-3RMXHrzo.js → chunk-V7JOEXUC-CXy9SmJk.js} +1 -1
  111. package/dist/public/assets/chunk-VAUOI2AC-ujVxk4Ze.js +1 -0
  112. package/dist/public/assets/{chunk-VR4S4FIN-YHQiPjFo.js → chunk-VR4S4FIN-KG7H_g4c.js} +1 -1
  113. package/dist/public/assets/{chunk-WYO6CB5R-tHLnBMnY.js → chunk-WYO6CB5R-B368j75q.js} +1 -1
  114. package/dist/public/assets/chunk-XXDRQBXY-B7w13F3i.js +1 -0
  115. package/dist/public/assets/{chunk-YOTPTUD7-u4FR_PoG.js → chunk-YOTPTUD7-Cqb1OWoI.js} +1 -1
  116. package/dist/public/assets/{chunk-ZGVPDNZ5-BFUSTZTU.js → chunk-ZGVPDNZ5-BKdDRJat.js} +1 -1
  117. package/dist/public/assets/{chunk-ZIRB5QZD-D120inkG.js → chunk-ZIRB5QZD-CvXXd6Mf.js} +1 -1
  118. package/dist/public/assets/classDiagram-OUVF2IWQ-CrrbWSrl.js +1 -0
  119. package/dist/public/assets/classDiagram-v2-EOCWNBFH-BYbi6pvW.js +1 -0
  120. package/dist/public/assets/client-version-B0MkkJjB.js +1 -0
  121. package/dist/public/assets/{cm-theme-DPWSzbOc.js → cm-theme-ChFGbVCe.js} +1 -1
  122. package/dist/public/assets/{comment-chips-DYqcIz_E.js → comment-chips-CmSdX8nJ.js} +1 -1
  123. package/dist/public/assets/{config-provider-DAxeLK4k.js → config-provider-BkvKKK43.js} +3 -3
  124. package/dist/public/assets/context-menu-CYgsnEgV.js +1 -0
  125. package/dist/public/assets/{cose-bilkent-JH36ORCC-D0CYnCA3.js → cose-bilkent-JH36ORCC-CwtkHR1Y.js} +1 -1
  126. package/dist/public/assets/cynefin-VYW2F7L2-BdPtv88z.js +1 -0
  127. package/dist/public/assets/{cynefinDiagram-TSTJHNR4-Bgric3JJ.js → cynefinDiagram-TSTJHNR4-LsplRO2K.js} +1 -1
  128. package/dist/public/assets/{dagre-uJOGPMM-.js → dagre-C6VKrNvO.js} +1 -1
  129. package/dist/public/assets/{dagre-VKFMJZFB-BXjUnJMs.js → dagre-VKFMJZFB-DhzjgRUZ.js} +1 -1
  130. package/dist/public/assets/{diagram-FQU43EPY-dXOWFjMG.js → diagram-FQU43EPY-a4jh9ybB.js} +1 -1
  131. package/dist/public/assets/{diagram-G47NLZAW-zdJG9pHl.js → diagram-G47NLZAW-Jgkwuc6y.js} +1 -1
  132. package/dist/public/assets/{diagram-NH7WQ7WH-BVYbs_C0.js → diagram-NH7WQ7WH-Cz1HEitz.js} +1 -1
  133. package/dist/public/assets/{diagram-OA4YK3LP-Ds5ohbs1.js → diagram-OA4YK3LP-CIcVtjXP.js} +1 -1
  134. package/dist/public/assets/{diagram-WEI45ONY-BluqqbZ4.js → diagram-WEI45ONY-C8wU887b.js} +1 -1
  135. package/dist/public/assets/{dialog-O4u6_xiQ.js → dialog-Bxcn1sLm.js} +1 -1
  136. package/dist/public/assets/{dist-C1TyNsxp.js → dist-BOhFaMG0.js} +1 -1
  137. package/dist/public/assets/{dist-tByLfm_n.js → dist-Bb1r1o6u.js} +1 -1
  138. package/dist/public/assets/{dist-CNm9tACe.js → dist-Bx9oFJRu.js} +1 -1
  139. package/dist/public/assets/{dist-CpwfhxFl.js → dist-C9uRrl_E.js} +1 -1
  140. package/dist/public/assets/{dist-hrQOAqN1.js → dist-CFyOS6pn.js} +1 -1
  141. package/dist/public/assets/{dist-CI5_cNui.js → dist-CXSIgvvA.js} +1 -1
  142. package/dist/public/assets/{dist-D1vjmDZ_2.js → dist-Cy5lktAQ2.js} +181 -181
  143. package/dist/public/assets/{dist-CJuiZAB0.js → dist-DL1WTl5d.js} +1 -1
  144. package/dist/public/assets/{dist-CDMQmWZl.js → dist-DRg5A_HQ.js} +1 -1
  145. package/dist/public/assets/{dist-CebtYbHb.js → dist-D_1xxRDt.js} +1 -1
  146. package/dist/public/assets/{dist-DU2smIGg.js → dist-DgRDZMLf.js} +1 -1
  147. package/dist/public/assets/{dist-BpOfJRMm.js → dist-DrCK4JBL.js} +1 -1
  148. package/dist/public/assets/{dist-y6w4IT08.js → dist-DuPjpj5-.js} +1 -1
  149. package/dist/public/assets/{dist-wfUjMP-v.js → dist-EpVTQF77.js} +1 -1
  150. package/dist/public/assets/{doc-paths-v_LqWyej.js → doc-paths-CBKXYveW.js} +1 -1
  151. package/dist/public/assets/{documents-events-BVk5JL1j.js → documents-events-DNLLVEPR.js} +1 -1
  152. package/dist/public/assets/{download-BuEN0lZf.js → download-btG_KeFQ.js} +1 -1
  153. package/dist/public/assets/{dropdown-menu-CP1RnfZI.js → dropdown-menu-K4eCFwQy.js} +1 -1
  154. package/dist/public/assets/{ebnfDiagram-CCIWWBDH-BWiN4nWj.js → ebnfDiagram-CCIWWBDH-CjptFZja.js} +1 -1
  155. package/dist/public/assets/{erDiagram-Q63AITRT-5GE6Syx5.js → erDiagram-Q63AITRT-BYiJa_5G.js} +1 -1
  156. package/dist/public/assets/eventmodeling-45OFAUF4-ur3Hg9pT.js +1 -0
  157. package/dist/public/assets/{eye-CYj_zi2W.js → eye-j_4QS15C.js} +1 -1
  158. package/dist/public/assets/{field-BADrt9_J.js → field-9eXIpxzl.js} +1 -1
  159. package/dist/public/assets/{file-tree-adapter-j4_0rR4k.js → file-tree-adapter-BQ9idF-F.js} +1 -1
  160. package/dist/public/assets/{file-tree-utils-ChaLadja.js → file-tree-utils-DrTcSGTj.js} +1 -1
  161. package/dist/public/assets/flowDiagram-23GEKE2U-C1BAvCbz.js +1 -0
  162. package/dist/public/assets/{folder-CWVPrRtx.js → folder-C8rE1Soy.js} +1 -1
  163. package/dist/public/assets/{folder-config-api-Cyxss03I.js → folder-config-api-Cf3ca6iE.js} +1 -1
  164. package/dist/public/assets/{folder-open-BXfoqsrp.js → folder-open-CB-trByC.js} +1 -1
  165. package/dist/public/assets/{follow-file-BMJH7ZWv.js → follow-file-Ctr47jtP.js} +1 -1
  166. package/dist/public/assets/{ganttDiagram-NO4QXBWP-DGnL6oh-.js → ganttDiagram-NO4QXBWP-TYuuGc0X.js} +1 -1
  167. package/dist/public/assets/{git-branch-CMN6cdzm.js → git-branch-JnfmLuHd.js} +1 -1
  168. package/dist/public/assets/gitGraph-TEB2WS4Q-l_1SzZcb.js +1 -0
  169. package/dist/public/assets/{gitGraphDiagram-IHSO6WYX-mMfBO0xv.js → gitGraphDiagram-IHSO6WYX-BrjUrrk2.js} +1 -1
  170. package/dist/public/assets/globals-B-lWUzDu.css +1 -0
  171. package/dist/public/assets/{graphlib-CS7i3af0.js → graphlib-D8PlvV2o.js} +1 -1
  172. package/dist/public/assets/{hash-BS4ux6bl.js → hash-DKiwvmF3.js} +1 -1
  173. package/dist/public/assets/{highlighted-body-OFNGDK62-Bc_b2HT_.js → highlighted-body-OFNGDK62-eJrwOujA.js} +1 -1
  174. package/dist/public/assets/{history-CiIvI4I4.js → history-eaFgPZWX.js} +1 -1
  175. package/dist/public/assets/i18n-CC8DkJXO.js +1 -0
  176. package/dist/public/assets/index-DrqV8949.js +2097 -0
  177. package/dist/public/assets/{info-160SNOuG.js → info-CsTy513y.js} +1 -1
  178. package/dist/public/assets/info-DKCQHKI2-CCDXfGhV.js +1 -0
  179. package/dist/public/assets/{infoDiagram-FWYZ7A6U-DuU1GDQ6.js → infoDiagram-FWYZ7A6U-B6_Knuir.js} +1 -1
  180. package/dist/public/assets/{input-group-CPKSxoq5.js → input-group-BA2Li4LU.js} +1 -1
  181. package/dist/public/assets/{ishikawaDiagram-FXEZZL3T-Bg0KJFCj.js → ishikawaDiagram-FXEZZL3T-CqxHoebw.js} +1 -1
  182. package/dist/public/assets/{journeyDiagram-5HDEW3XC-DLWkGhNH.js → journeyDiagram-5HDEW3XC-B1-3fVtR.js} +1 -1
  183. package/dist/public/assets/{kanban-definition-HUTT4EX6-BhYGhRMu.js → kanban-definition-HUTT4EX6-CdhMOBCU.js} +1 -1
  184. package/dist/public/assets/{line-e19R8FCM.js → line-C0o9Fjf4.js} +1 -1
  185. package/dist/public/assets/{linear-a82bFSBJ.js → linear-CjM1R4zy.js} +1 -1
  186. package/dist/public/assets/{lint-config-client-CN7WtJJN.js → lint-config-client-DzdtSJp-.js} +1 -1
  187. package/dist/public/assets/{list-plus-BPvSuFZX.js → list-plus-ByOuGBSE.js} +1 -1
  188. package/dist/public/assets/loader-circle-BJLNGSB4.js +1 -0
  189. package/dist/public/assets/{local-menu-action-bus-BDB0W02w.js → local-menu-action-bus-BKJCODnD.js} +1 -1
  190. package/dist/public/assets/{map-il90ypLM.js → map-Cu759seX.js} +1 -1
  191. package/dist/public/assets/{markdownlint-rule-browser-uB5xoBRt.js → markdownlint-rule-browser-DMQXiRek.js} +1 -1
  192. package/dist/public/assets/mermaid-GHXKKRXX-C9G7CQ6h.js +1 -0
  193. package/dist/public/assets/{mermaid-parser.core-ueh8mdU-.js → mermaid-parser.core-DpHycRcl.js} +2 -2
  194. package/dist/public/assets/{mermaid.core-RZ5le45c.js → mermaid.core-BnYdLHjl.js} +3 -3
  195. package/dist/public/assets/messages-BNq0JS1I.js +1 -0
  196. package/dist/public/assets/messages-C1QZwdEx.js +1 -0
  197. package/dist/public/assets/messages-CAevTmZQ.js +1 -0
  198. package/dist/public/assets/messages-CG-GHBB9.js +1 -0
  199. package/dist/public/assets/messages-CIxg-v3C.js +1 -0
  200. package/dist/public/assets/messages-CKi8pZ4Q.js +1 -0
  201. package/dist/public/assets/messages-Cv5HHzZF.js +1 -0
  202. package/dist/public/assets/messages-DTRz3g9F.js +1 -0
  203. package/dist/public/assets/messages-DWBpIisU.js +1 -0
  204. package/dist/public/assets/messages-XzeH2iOB.js +1 -0
  205. package/dist/public/assets/messages-bBtIkGs7.js +1 -0
  206. package/dist/public/assets/{mindmap-definition-LN4V7U3C-Bcv7y0kn.js → mindmap-definition-LN4V7U3C-D6FYi_vY.js} +1 -1
  207. package/dist/public/assets/minus-H7UCODAH.js +1 -0
  208. package/dist/public/assets/{miss-dialog-store-CdaZpyLg.js → miss-dialog-store-DKfFwAsF.js} +1 -1
  209. package/dist/public/assets/navigation-targets-Ce74CisT.js +1 -0
  210. package/dist/public/assets/{now-CZywS9tX.js → now-Cd_fQsCQ.js} +1 -1
  211. package/dist/public/assets/{open-managed-artifact-tab-CFg9s1Dl.js → open-managed-artifact-tab-B84Y6EsP.js} +1 -1
  212. package/dist/public/assets/{ordinal-Bj6MlRdi.js → ordinal-oNJqAlZi.js} +1 -1
  213. package/dist/public/assets/packet-7NZHBO7P-BBeRj-Du.js +1 -0
  214. package/dist/public/assets/{panel-right-open-_nL1w4h-.js → panel-right-open-JxkSMPMb.js} +1 -1
  215. package/dist/public/assets/{paperclip-DV67TMJS.js → paperclip-BxFhnUjq.js} +1 -1
  216. package/dist/public/assets/{pegDiagram-2B236MQR-Du6F68bP.js → pegDiagram-2B236MQR-Cic2_Ooi.js} +1 -1
  217. package/dist/public/assets/{pending-receive-nav-store-By3F7IeX.js → pending-receive-nav-store-DosIhFkt.js} +1 -1
  218. package/dist/public/assets/pie-RZYD4A2V-BszLCTWh.js +1 -0
  219. package/dist/public/assets/{pieDiagram-ENE6RG2P-Du-eEA1d.js → pieDiagram-ENE6RG2P-DgqO0C3j.js} +1 -1
  220. package/dist/public/assets/{project-paths-BWmSfpDI.js → project-paths-DC6bWLUQ.js} +1 -1
  221. package/dist/public/assets/{prop-types-BUGU9oYX.js → prop-types-BxhIEdp4.js} +1 -1
  222. package/dist/public/assets/{quadrantDiagram-ABIIQ3AL-NefyxxyK.js → quadrantDiagram-ABIIQ3AL-CC3ZGpWb.js} +1 -1
  223. package/dist/public/assets/radar-I7S5WNFK-CG0ShGDu.js +1 -0
  224. package/dist/public/assets/railroad-3IZDKUUU-N5ekmrCL.js +1 -0
  225. package/dist/public/assets/railroad-abnf-AHOZXSZD-DnjoKlG9.js +1 -0
  226. package/dist/public/assets/railroad-ebnf-EBAXGLYW-qDwmtJRh.js +1 -0
  227. package/dist/public/assets/railroad-peg-LSFZ7HO6-DSfMsKSD.js +1 -0
  228. package/dist/public/assets/{railroadDiagram-RFXS5EU6-CN_1Ywzn.js → railroadDiagram-RFXS5EU6-DaoKPEli.js} +1 -1
  229. package/dist/public/assets/{receive-store-DQ2cxNlN.js → receive-store-DO5w93VK.js} +1 -1
  230. package/dist/public/assets/{refresh-cw-Bjv-Fpq5.js → refresh-cw-CAV3aG7d.js} +1 -1
  231. package/dist/public/assets/{requirementDiagram-TGXJPOKE-bDLvkWBT.js → requirementDiagram-TGXJPOKE-qmFI0ev3.js} +1 -1
  232. package/dist/public/assets/{sankeyDiagram-HTMAVEWB-CyhjQEet.js → sankeyDiagram-HTMAVEWB-CYeZQsa5.js} +1 -1
  233. package/dist/public/assets/{schema-fields-view-intent-BMlW8LRz.js → schema-fields-view-intent-CeZOW3HG.js} +1 -1
  234. package/dist/public/assets/{select-BaOsrrG7.js → select-BjNoD_FX.js} +1 -1
  235. package/dist/public/assets/{selection-context-Q2igplxe.js → selection-context-DAl-Wxy6.js} +1 -1
  236. package/dist/public/assets/{separator-BXBsYPiB.js → separator-BKbgOjgy.js} +1 -1
  237. package/dist/public/assets/{sequenceDiagram-DBY2YBRQ-BeYilBxj.js → sequenceDiagram-DBY2YBRQ-DfXkoRwp.js} +1 -1
  238. package/dist/public/assets/{sizeCapture-X5ZJPWSS-Mb3J__hm.js → sizeCapture-X5ZJPWSS-Bd7A4fpz.js} +1 -1
  239. package/dist/public/assets/skill-actions-1VvTttnO.js +2 -0
  240. package/dist/public/assets/{skill-scope-CLm-DjVO.js → skill-scope-uWACL-4X.js} +1 -1
  241. package/dist/public/assets/{skills-api-Do-yD8Wd.js → skills-api-S9b1zvZ6.js} +1 -1
  242. package/dist/public/assets/{square-pen-CW0s3lqC.js → square-pen-hwoIfi3M.js} +1 -1
  243. package/dist/public/assets/{src-rGs2GXpJ.js → src-CVA7Dtfv.js} +1 -1
  244. package/dist/public/assets/{src-DT86yydp.js → src-XHagG0Wj.js} +1 -1
  245. package/dist/public/assets/{stateDiagram-2N3HPSRC-D0WNjYjx.js → stateDiagram-2N3HPSRC-CCh_abZC.js} +1 -1
  246. package/dist/public/assets/stateDiagram-v2-6OUMAXLB-CUhlDos5.js +1 -0
  247. package/dist/public/assets/{swimlanes-5IMT3BWC-BAPdgrYU.js → swimlanes-5IMT3BWC-Dk2uoutn.js} +2 -2
  248. package/dist/public/assets/swimlanesDiagram-G3AALYLV-DHL99Ckz.js +8 -0
  249. package/dist/public/assets/{tag-pill-input-DLcAHAth.js → tag-pill-input-er0MqvFK.js} +1 -1
  250. package/dist/public/assets/{target-navigation-intent-AJHzhxLh.js → target-navigation-intent-DBvgpA7l.js} +1 -1
  251. package/dist/public/assets/{telemetry-impl-DFcgjFFc.js → telemetry-impl-LPWb9DJh.js} +2 -2
  252. package/dist/public/assets/{telemetry-startup-0F_AW_hr.js → telemetry-startup-B-jACYNe.js} +1 -1
  253. package/dist/public/assets/terminal-bCsp6kPz.js +1 -0
  254. package/dist/public/assets/{terminal-cli-display-DcmUJBJ0.js → terminal-cli-display-CBMTYLbQ.js} +1 -1
  255. package/dist/public/assets/terminal-launch-events-CbqKUJ57.js +1 -0
  256. package/dist/public/assets/{terminal-telemetry-BaIL0R4h.js → terminal-telemetry-BRNk9k9Y.js} +1 -1
  257. package/dist/public/assets/{text-viewer-languages-BBrkAtBf.js → text-viewer-languages-BmEIetCD.js} +2 -2
  258. package/dist/public/assets/{timeline-definition-FHXFAJF6-BnIpQBQO.js → timeline-definition-FHXFAJF6-tb13RhWP.js} +1 -1
  259. package/dist/public/assets/{trash-2-rgduGgZB.js → trash-2-CSpv7np3.js} +1 -1
  260. package/dist/public/assets/treeView-QDETBFTQ-DwFOcFO4.js +1 -0
  261. package/dist/public/assets/treemap-6X3UGDF4-D_-cggQd.js +1 -0
  262. package/dist/public/assets/{triangle-alert-CnW4IElJ.js → triangle-alert-xKPljhlK.js} +1 -1
  263. package/dist/public/assets/typing-burst-detector-D114TNgO.js +8 -0
  264. package/dist/public/assets/{undo-2-BmxrL5XS.js → undo-2-D5cqFzyJ.js} +1 -1
  265. package/dist/public/assets/{uninstall-DEqbq9oi.js → uninstall-B7OIrc24.js} +1 -1
  266. package/dist/public/assets/{use-activity-panel-HhWhJyPS.js → use-activity-panel-DnpzFXIs.js} +1 -1
  267. package/dist/public/assets/{use-apply-config-color-theme-dRh7Xul9.js → use-apply-config-color-theme-DLZre1dS.js} +1 -1
  268. package/dist/public/assets/{use-collab-url-CtzTnNTo.js → use-collab-url-CjkHphlr.js} +1 -1
  269. package/dist/public/assets/{use-live-xterm-theme-CEFo40Qe.js → use-live-xterm-theme-CVQrPooY.js} +1 -1
  270. package/dist/public/assets/{use-open-skill-Cscl8Yx2.js → use-open-skill-DImLrKgY.js} +1 -1
  271. package/dist/public/assets/{use-popular-skills-Yh3HxWUQ.js → use-popular-skills-Dj_DcxJ4.js} +1 -1
  272. package/dist/public/assets/{use-settings-route-BDWFTRtx.js → use-settings-route-DEoOHvHf.js} +1 -1
  273. package/dist/public/assets/{use-skill-origin-JUAmtC9e.js → use-skill-origin-Bj3wYKq2.js} +1 -1
  274. package/dist/public/assets/{use-skills-BmTj83Vv.js → use-skills-k_NyqOb0.js} +1 -1
  275. package/dist/public/assets/{use-terminal-enabled-BJe4ZzuL.js → use-terminal-enabled-D2ShR7ZJ.js} +1 -1
  276. package/dist/public/assets/{use-timeline-entry-diff-BEA4Wm90.js → use-timeline-entry-diff-CjhWQfrw.js} +4 -4
  277. package/dist/public/assets/{use-workspace-BJfeN9YT.js → use-workspace-D0EhHpoU.js} +1 -1
  278. package/dist/public/assets/{vennDiagram-L72KCM5P-C38RYC28.js → vennDiagram-L72KCM5P-Cyp_-2xs.js} +1 -1
  279. package/dist/public/assets/wardley-OPB4EBWU-Dz0s9mBi.js +1 -0
  280. package/dist/public/assets/{wardleyDiagram-EHGQE667-B0VRsKo1.js → wardleyDiagram-EHGQE667-C5z1_r-x.js} +1 -1
  281. package/dist/public/assets/{wrench-DtGaC8XY.js → wrench-yAsO-Pm9.js} +1 -1
  282. package/dist/public/assets/x-BopM5CF8.js +1 -0
  283. package/dist/public/assets/{xychartDiagram-FW5EYKEG-jAQK9E85.js → xychartDiagram-FW5EYKEG-DH9RxgRE.js} +1 -1
  284. package/dist/public/index.html +134 -133
  285. package/dist/public/uninstall.html +14 -14
  286. package/dist/{repair-launch-json-Dnhl7E_E.mjs → repair-launch-json-DJCBlxLw.mjs} +2 -2
  287. package/dist/{repair-mcp-configs-BTst6dOY.mjs → repair-mcp-configs-C8bpTpxh.mjs} +2 -2
  288. package/dist/repair-skills-BK1EcvXS.mjs +1 -0
  289. package/dist/{repair-skills-hf9Efmkp.mjs → repair-skills-CMm13M8P.mjs} +2 -2
  290. package/dist/server-lock-Dy_yO6Nk.mjs +1 -0
  291. package/dist/{server-lock-DEOF_T1n.mjs → server-lock-V3bg8zL0.mjs} +2 -2
  292. package/dist/{skill-teardown-B7FIoHkS.mjs → skill-teardown-CO4xteJC.mjs} +2 -2
  293. package/dist/{src-EOJBnmi7.mjs → src-C2Gyjygx.mjs} +1 -1
  294. package/dist/src-CRHuZPcr.mjs +1 -0
  295. package/dist/src-DwT4IlXo.mjs +20 -0
  296. package/dist/{src-v83peLAF.mjs → src-IM6msWeV.mjs} +2 -2
  297. package/dist/{src-T22OxNCJ.mjs → src-bozJXbns.mjs} +4 -4
  298. package/dist/start-BGjifSjp.mjs +1 -0
  299. package/dist/start-Bua6MR2W.mjs +4 -0
  300. package/dist/{write-project-skill-Ds6QPmhs.mjs → write-project-skill-BoeD2RUw.mjs} +2 -2
  301. package/package.json +5 -5
  302. package/dist/acp-harness-probe-BL-kL5a3.mjs +0 -3
  303. package/dist/constants-BsKxR1wP.mjs +0 -2
  304. package/dist/git-handle-Rma56ZDs.mjs +0 -1
  305. package/dist/init-Dc-aeDeC.mjs +0 -1
  306. package/dist/loader-BLWCSy5o.mjs +0 -1
  307. package/dist/md-manager-wsrK03Vr.mjs +0 -2
  308. package/dist/preview-DMl0bCHE.mjs +0 -1
  309. package/dist/public/assets/CodeMirrorPropInput-D6Vpy6cC.js +0 -3
  310. package/dist/public/assets/FeedbackForm-DK3Eafhu.js +0 -1
  311. package/dist/public/assets/ManagedArtifactProperties-BoQaa-VP.js +0 -2
  312. package/dist/public/assets/ManagedArtifactProperties-F3vbLcfn.js +0 -1
  313. package/dist/public/assets/SessionsHost-CldPPD2R.js +0 -2
  314. package/dist/public/assets/SettingsDialogBody-B-5j1KKE.js +0 -12
  315. package/dist/public/assets/SkillToolbarControls-DnCihwAh.js +0 -1
  316. package/dist/public/assets/SourceEditor-BuOJMaXx.js +0 -1
  317. package/dist/public/assets/architecture-TIHT7OUA-DHywK0qf.js +0 -1
  318. package/dist/public/assets/arrow-up-right-CXYxHO7Z.js +0 -1
  319. package/dist/public/assets/channel-BNyr5ucm.js +0 -1
  320. package/dist/public/assets/check-DA6LolTH.js +0 -1
  321. package/dist/public/assets/chevron-left-DY9flfyc.js +0 -1
  322. package/dist/public/assets/chevron-right-2RK4DD3b.js +0 -1
  323. package/dist/public/assets/chunk-2Q5K7J3B-UKfnOi4g.js +0 -1
  324. package/dist/public/assets/chunk-VAUOI2AC-ChJppfl7.js +0 -1
  325. package/dist/public/assets/chunk-XXDRQBXY-Bsh29NfZ.js +0 -1
  326. package/dist/public/assets/classDiagram-OUVF2IWQ-6PbrHEW6.js +0 -1
  327. package/dist/public/assets/classDiagram-v2-EOCWNBFH-B4bz8Etj.js +0 -1
  328. package/dist/public/assets/client-version-BESEvZR7.js +0 -1
  329. package/dist/public/assets/cynefin-VYW2F7L2-CjkKc5Wd.js +0 -1
  330. package/dist/public/assets/eventmodeling-45OFAUF4-GQ05Sah7.js +0 -1
  331. package/dist/public/assets/flowDiagram-23GEKE2U-CwO12b-s.js +0 -1
  332. package/dist/public/assets/gitGraph-TEB2WS4Q-Da8kWWZb.js +0 -1
  333. package/dist/public/assets/globals-CyYdI-wx.css +0 -1
  334. package/dist/public/assets/i18n-CqChyNE3.js +0 -1
  335. package/dist/public/assets/index-CJ9IqjVe.js +0 -2097
  336. package/dist/public/assets/info-DKCQHKI2-BPZv5cfZ.js +0 -1
  337. package/dist/public/assets/loader-circle-BbuX0POi.js +0 -1
  338. package/dist/public/assets/mermaid-GHXKKRXX-CaB-_LCR.js +0 -1
  339. package/dist/public/assets/messages-BTQ6QHGD.js +0 -1
  340. package/dist/public/assets/messages-C1_vqjO0.js +0 -1
  341. package/dist/public/assets/messages-CcNmHSRm.js +0 -1
  342. package/dist/public/assets/messages-CuCFXL8u.js +0 -1
  343. package/dist/public/assets/messages-D-wGArHz.js +0 -1
  344. package/dist/public/assets/messages-DCORBVvf.js +0 -1
  345. package/dist/public/assets/messages-DK20PMTg.js +0 -1
  346. package/dist/public/assets/messages-DaaRRAol.js +0 -1
  347. package/dist/public/assets/messages-TrWXqll1.js +0 -1
  348. package/dist/public/assets/messages-_5gcf9E8.js +0 -1
  349. package/dist/public/assets/messages-l5kO2Bq5.js +0 -1
  350. package/dist/public/assets/minus-Ba4o_31L.js +0 -1
  351. package/dist/public/assets/navigation-targets-BmGfXtLg.js +0 -1
  352. package/dist/public/assets/packet-7NZHBO7P-BtkfuFQU.js +0 -1
  353. package/dist/public/assets/pie-RZYD4A2V-DipSPJ4R.js +0 -1
  354. package/dist/public/assets/radar-I7S5WNFK-CsW1Ke6j.js +0 -1
  355. package/dist/public/assets/railroad-3IZDKUUU-CDGYvuvs.js +0 -1
  356. package/dist/public/assets/railroad-abnf-AHOZXSZD-IJHoKQ5T.js +0 -1
  357. package/dist/public/assets/railroad-ebnf-EBAXGLYW-DiwXL3Zg.js +0 -1
  358. package/dist/public/assets/railroad-peg-LSFZ7HO6-B4tduAeK.js +0 -1
  359. package/dist/public/assets/skill-actions-CBlHW4d_.js +0 -2
  360. package/dist/public/assets/stateDiagram-v2-6OUMAXLB-NccT1PAw.js +0 -1
  361. package/dist/public/assets/swimlanesDiagram-G3AALYLV-CIDy7tZE.js +0 -8
  362. package/dist/public/assets/terminal-BNdVsbND.js +0 -1
  363. package/dist/public/assets/terminal-launch-events-DL9JJPUH.js +0 -1
  364. package/dist/public/assets/treeView-QDETBFTQ-DCy4i-OI.js +0 -1
  365. package/dist/public/assets/treemap-6X3UGDF4-BrUnfA75.js +0 -1
  366. package/dist/public/assets/typing-burst-detector-CPW5PZdn.js +0 -8
  367. package/dist/public/assets/wardley-OPB4EBWU-yXijkZ08.js +0 -1
  368. package/dist/public/assets/x-D8xzRaMT.js +0 -1
  369. package/dist/repair-skills-BmOui_rF.mjs +0 -1
  370. package/dist/server-lock-Rh5J9yH2.mjs +0 -1
  371. package/dist/src-CDtgwazs.mjs +0 -20
  372. package/dist/src-f1gCZ4_a.mjs +0 -1
  373. package/dist/start-D1GiMBz1.mjs +0 -4
  374. package/dist/start-DvQmqx2l.mjs +0 -1
  375. /package/dist/public/assets/{ActivityPanelDiffView-aQoOngI6.js → ActivityPanelDiffView-fDxLwTi2.js} +0 -0
  376. /package/dist/public/assets/{SkillModeBanner-Y5LYtJrC.js → SkillModeBanner-d0ZDkWTk.js} +0 -0
  377. /package/dist/public/assets/{__vite-browser-external-6FU8ctEn.js → __vite-browser-external-D_48KNDi.js} +0 -0
  378. /package/dist/public/assets/{agent-presence-DntZZFlY.js → agent-presence-DK_W4GTa.js} +0 -0
  379. /package/dist/public/assets/{array-Ce922FV9.js → array-DYKIbRR-.js} +0 -0
  380. /package/dist/public/assets/{asset-dispatch-_dEhJuVP.js → asset-dispatch-DsHoHhCG.js} +0 -0
  381. /package/dist/public/assets/{auth-prompt-store-CeaWNesV.js → auth-prompt-store-CyiGTt3C.js} +0 -0
  382. /package/dist/public/assets/{badge-CY_v_nGy.js → badge-zHd29IKW.js} +0 -0
  383. /package/dist/public/assets/{chunk-KEIR6QF5-88h2AcFS.js → chunk-KEIR6QF5-Z0IgTo4K.js} +0 -0
  384. /package/dist/public/assets/{chunk-Y2CYZVJY-B-DQ9l1H.js → chunk-Y2CYZVJY-Bmis3P2F.js} +0 -0
  385. /package/dist/public/assets/{clike-DDeLLKpf.js → clike-l3ublWpW.js} +0 -0
  386. /package/dist/public/assets/{clipboard-adapter-C4L1qX1X.js → clipboard-adapter-DEJxizFj.js} +0 -0
  387. /package/dist/public/assets/{code-highlighter-impl-Bq6VPPCL.js → code-highlighter-impl-CHS525hA.js} +0 -0
  388. /package/dist/public/assets/{colors-DXv_7g0X.js → colors-C77NTF6g.js} +0 -0
  389. /package/dist/public/assets/{copilot-D0J83lOh.js → copilot-BdGxiVpg.js} +0 -0
  390. /package/dist/public/assets/{createLucideIcon-BcLKHslE.js → createLucideIcon-6iYxif1u.js} +0 -0
  391. /package/dist/public/assets/{cursor-B6-YoFzF.js → cursor-CUtcHGV-.js} +0 -0
  392. /package/dist/public/assets/{cytoscape.esm-61X9Wf4W.js → cytoscape.esm-C2gIT5zZ.js} +0 -0
  393. /package/dist/public/assets/{defaultLocale-BypL9rsE.js → defaultLocale-BugBqEWo.js} +0 -0
  394. /package/dist/public/assets/{desktop-bridge-types-rBjHIYSI.js → desktop-bridge-types-oYPdTDmz.js} +0 -0
  395. /package/dist/public/assets/{diff-CUOV9XAb.js → diff-TXhtTD_D.js} +0 -0
  396. /package/dist/public/assets/{dist-BSzXg9wc.js → dist-1ia0sKe1.js} +0 -0
  397. /package/dist/public/assets/{dist-BTu6o3T-.js → dist-B0Beym3_.js} +0 -0
  398. /package/dist/public/assets/{dist-CG-e4AlS.js → dist-DNiTklSL.js} +0 -0
  399. /package/dist/public/assets/{documents-fetch-B8A9IAH3.js → documents-fetch-I34CgFeh.js} +0 -0
  400. /package/dist/public/assets/{external-link-Bw5EK5AQ.js → external-link-CHCx4FXC.js} +0 -0
  401. /package/dist/public/assets/{file-tree-rename-validation-Dt6fQYnB.js → file-tree-rename-validation-DEuNOzhg.js} +0 -0
  402. /package/dist/public/assets/{form-WTEKK5Th.js → form-_Bm7VdZa.js} +0 -0
  403. /package/dist/public/assets/{format-C7y0e043.js → format-Dx1Bv63R.js} +0 -0
  404. /package/dist/public/assets/{gherkin-DHKdvgzn.js → gherkin-Bu_VunKM.js} +0 -0
  405. /package/dist/public/assets/{globals-fH7sZOn9.js → globals-CZJtsuL5.js} +0 -0
  406. /package/dist/public/assets/{go-C7e4ztpP.js → go-BYJ3ESi0.js} +0 -0
  407. /package/dist/public/assets/{init-DQ9T43b9.js → init-B44NBVpk.js} +0 -0
  408. /package/dist/public/assets/{input-_CzMpvY9.js → input-VnbFvuKd.js} +0 -0
  409. /package/dist/public/assets/{isObject-B3vD71ho.js → isObject-Dhzo1ma6.js} +0 -0
  410. /package/dist/public/assets/{libesm-DLjHMG6S.js → libesm-BYxokP1G.js} +0 -0
  411. /package/dist/public/assets/{lint-plugin-meta-D6yg1VIa.js → lint-plugin-meta-FPoTE-0t.js} +0 -0
  412. /package/dist/public/assets/{lru-string-cache-D1rxjuni.js → lru-string-cache-BgNKFfCO.js} +0 -0
  413. /package/dist/public/assets/{lua-BbsHik3c.js → lua-De9v6Xwm.js} +0 -0
  414. /package/dist/public/assets/{mcp-consent-store-yqsuAEir.js → mcp-consent-store-CBPF1Ll9.js} +0 -0
  415. /package/dist/public/assets/{min-LWIJDKXt.js → min-CgRbfTQR.js} +0 -0
  416. /package/dist/public/assets/{panel-DVJ8gssn.js → panel-9S5Pf2VO.js} +0 -0
  417. /package/dist/public/assets/{panzoom.es-CnTJleIF.js → panzoom.es-CebiCTnw.js} +0 -0
  418. /package/dist/public/assets/{path-CdhP4z-N.js → path-DNVjzh9n.js} +0 -0
  419. /package/dist/public/assets/{pdf-CvpTyCsQ.js → pdf-19dxfod4.js} +0 -0
  420. /package/dist/public/assets/{pdf.worker-Dwl0H-tq.js → pdf.worker-Cn0IyjYR.js} +0 -0
  421. /package/dist/public/assets/{perl-B_IBZ74F.js → perl-DAC-0-L4.js} +0 -0
  422. /package/dist/public/assets/{properties-DC2eg36q.js → properties-BuEq0L0N.js} +0 -0
  423. /package/dist/public/assets/{r-Cuws8T_X.js → r-D6J_8GbJ.js} +0 -0
  424. /package/dist/public/assets/{rough.esm-Bmw38t74.js → rough.esm-hH2VdTtm.js} +0 -0
  425. /package/dist/public/assets/{ruby-B4Exyfkx.js → ruby-BulDdqGQ.js} +0 -0
  426. /package/dist/public/assets/{share-metadata-rows-a0ScdR3d.js → share-metadata-rows-CBd7DuHz.js} +0 -0
  427. /package/dist/public/assets/{shell-DA6f2ert.js → shell-FYbPjPiK.js} +0 -0
  428. /package/dist/public/assets/{skeleton-ColtBPsg.js → skeleton-BOVIbSHk.js} +0 -0
  429. /package/dist/public/assets/{sortable.esm-DlAqBM0z.js → sortable.esm-mqYoEMD5.js} +0 -0
  430. /package/dist/public/assets/{sql-gKfhysbI.js → sql-BTcd-g6A.js} +0 -0
  431. /package/dist/public/assets/{src-l8acH7-t.js → src-D2oHIihg.js} +0 -0
  432. /package/dist/public/assets/{startup-marks-BPO-vrjH.js → startup-marks-BYurBbnW.js} +0 -0
  433. /package/dist/public/assets/{stex-Cj2UNqUe.js → stex-BmYSnOnf.js} +0 -0
  434. /package/dist/public/assets/{swift-D4PiCeXt.js → swift-CnW5XUwC.js} +0 -0
  435. /package/dist/public/assets/{terminal-command-events-BBYZtptJ.js → terminal-command-events-mSM3ArSl.js} +0 -0
  436. /package/dist/public/assets/{textarea-C5-cm3M6.js → textarea-D59GB_Zy.js} +0 -0
  437. /package/dist/public/assets/{thread-client-CER-baRK.js → thread-client-DySYYPC9.js} +0 -0
  438. /package/dist/public/assets/{thread-draft-staging-DZhf3sQU.js → thread-draft-staging-BZaq81Sj.js} +0 -0
  439. /package/dist/public/assets/{timeline-diff-store-BpUHW_Yp.js → timeline-diff-store-cCBpDgND.js} +0 -0
  440. /package/dist/public/assets/{toml-BAg1ozw3.js → toml-vEnVjPi4.js} +0 -0
  441. /package/dist/public/assets/{use-installed-clis-CsPJ2Mod.js → use-installed-clis-CdB0ME5s.js} +0 -0
  442. /package/dist/public/assets/{useLintConfigViewMode-shAfv89B.js → useLintConfigViewMode-C89oTBHY.js} +0 -0
  443. /package/dist/public/assets/{workspace-paths-D7hYulMY.js → workspace-paths-C2pS_Pbn.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as E,W as ee,Y as D,Z as O,_ as te,_t as k,at as A,b as ne,bt as j,ct as re,d as ie,dt as M,et as ae,f as oe,ft as se,g as ce,gt as le,ht as ue,i as de,it as N,jt as fe,kt as pe,l as me,lt as he,mt as P,n as ge,nt as _e,ot as ve,pt as F,q as ye,r as be,st as xe,t as Se,tt as Ce,v as we,vt as I,w as Te,wt as Ee,xt as De,y as Oe,yt as ke}from"./sleep-DVOInM4H.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Cr as et,Cs as tt,Ct as nt,D as rt,Da as it,Di as at,Dn as ot,Do as st,Dr as ct,Dt as lt,E as ut,Ea as dt,Ei as ft,En as pt,Eo as mt,Er as ht,Et as gt,F as _t,Fa as vt,Fi as eee,Fn as yt,Fo as bt,Fr as xt,Ft as St,G as Ct,Ga as wt,Gi as Tt,Gn as Et,Go as Dt,Gr as tee,Gt as Ot,H as kt,Ha as At,Hi as nee,Hn as ree,Ho as jt,Hr as iee,Ht as Mt,I as Nt,Ia as Pt,Ii as Ft,In as aee,Io as It,Ir as Lt,J as Rt,Ja as oee,Ji as zt,Jn as see,Jo as Bt,Jr as Vt,Jt as Ht,K as Ut,Ka as Wt,Ki as Gt,Kn as Kt,Ko as qt,Kr as cee,Kt as Jt,L as Yt,La as Xt,Li as lee,Ln as Zt,Lr as Qt,M as $t,Ma as en,Mi as uee,Mn as tn,Mo as nn,Mr as rn,Mt as an,N as on,Na as sn,Ni as cn,Nn as ln,No as un,Nr as dn,Nt as fn,O as pn,Oa as mn,Oi as hn,On as dee,Oo as gn,Or as _n,Os as vn,Ot as fee,P as yn,Pi as bn,Pn as pee,Po as xn,Pr as mee,Pt as Sn,Qa as Cn,Qi as wn,Qn as hee,Qo as Tn,Qr as En,Qt as Dn,Ra as On,Ri as kn,Rn as An,Ro as jn,Rr as Mn,Rt as Nn,S as Pn,Sa as Fn,Si as In,Sn as Ln,So as Rn,Sr as zn,Ss as Bn,St as Vn,T as Hn,Ta as Un,Ti as Wn,Tn as gee,Tr as Gn,Ts as Kn,Tt as qn,U as Jn,Ua as _ee,Ui as vee,Un as Yn,Uo as Xn,Ur as yee,Ut as Zn,V as Qn,Va as bee,Vi as xee,Vn as See,Vo as $n,Vr as er,Vt as tr,W as nr,Wa as rr,Wi as ir,Wn as ar,Wr as or,Wt as sr,X as cr,Xa as lr,Xi as ur,Xn as dr,Xo as fr,Xr as pr,Xt as mr,Ya as hr,Yi as gr,Yn as _r,Yo as vr,Yr as yr,Yt as br,Za as xr,Zi as Sr,Zn as Cr,Zo as wr,Zr as Tr,Zt as Er,_ as Dr,_a as Or,_i as kr,_n as Ar,_o as jr,_r as Mr,_s as Nr,_t as Pr,a as Fr,aa as Ir,ai as Lr,an as Cee,ao as wee,ar as Tee,as as Rr,at as zr,b as Br,ba as Eee,bi as Dee,bn as Vr,br as Oee,bs as Hr,bt as Ur,c as Wr,ca as Gr,ci as Kr,cn as kee,cr as Aee,cs as qr,ct as Jr,d as Yr,da as Xr,di as Zr,dn as jee,do as Qr,dr as Mee,ds as $r,dt as ei,ea as ti,ei as Nee,en as Pee,eo as Fee,er as Iee,es as ni,et as ri,f as ii,fa as Lee,fi as Ree,fn as zee,fr as Bee,fs as Vee,ft as ai,g as oi,ga as si,gi as ci,gn as li,go as ui,gr as di,gs as fi,gt as pi,h as mi,ha as hi,hi as gi,hn as _i,hr as vi,hs as yi,ht as bi,i as xi,ia as Si,ii as Ci,in as wi,io as Ti,ir as Ei,is as Di,it as Oi,j as ki,ja as Ai,ji,jn as Mi,jr as Ni,jt as Pi,k as Fi,ka as Ii,ki as Li,kn as Ri,ko as zi,kr as Bi,kt as Vi,l as Hi,la as Ui,li as Wi,ln as Gi,lo as Ki,lr as qi,lt as Ji,m as Yi,ma as Xi,mi as Zi,mn as Qi,mr as $i,ms as ea,mt as ta,n as na,na as ra,ni as ia,nn as aa,no as oa,nr as sa,ns as ca,nt as la,o as ua,oa as da,oi as fa,on as Hee,oo as pa,or as Uee,os as ma,ot as ha,p as ga,pa as Wee,pi as _a,pn as Gee,po as va,pr as ya,ps as ba,pt as xa,q as Sa,qa as Ca,qi as Kee,qn as qee,qo as wa,qr as Ta,qt as Ea,r as Da,ra as Oa,ri as ka,rn as Jee,ro as Aa,rr as Yee,rs as ja,rt as Ma,s as Na,sa as Pa,si as Fa,sn as Xee,so as Ia,sr as Zee,ss as La,st as Ra,t as za,ta as Ba,ti as Qee,tn as Va,to as $ee,tr as Ha,tt as Ua,u as Wa,ua as Ga,ui as Ka,un as ete,uo as qa,ur as tte,us as Ja,ut as Ya,v as Xa,va as Za,vi as Qa,vn as $a,vo as eo,vr as to,vs as no,vt as ro,w as io,wa as ao,wi as oo,wn as so,wo as co,wr as lo,ws as uo,wt as fo,x as po,xa as mo,xi as ho,xn as go,xo as _o,xr as vo,xs as yo,xt as bo,y as xo,ya as So,yi as Co,yn as wo,yo as To,yr as Eo,ys as Do,yt as Oo,z as ko,za as Ao,zi as jo,zn as Mo,zo as No,zr as Po,zt as Fo}from"./src-v83peLAF.mjs";import{c as Io,i as Lo,l as Ro,n as zo,s as Bo}from"./esm-DxvI2ZVA.mjs";import{n as Vo,t as Ho}from"./md-manager-wsrK03Vr.mjs";import{A as Uo,C as Wo,D as Go,E as Ko,F as qo,N as Jo,O as Yo,S as Xo,T as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-DVpoNaQJ.mjs";import{D as Ss,E as Cs,S as ws,T as Ts,a as Es,b as Ds,l as Os,p as ks,r as L,s as As,x as js,y as Ms}from"./logger-DFxEUjvj.mjs";import{a as Ns,i as Ps,o as Fs,r as Is,s as Ls,t as Rs}from"./git-handle-oaKkz-wn.mjs";import{C as zs,S as Bs,_ as Vs,a as Hs,b as Us,c as Ws,f as Gs,g as Ks,h as qs,i as Js,l as Ys,n as Xs,p as Zs,r as Qs,u as $s,x as nte}from"./server-lock-DEOF_T1n.mjs";import{t as ec}from"./libesm-DzwC_yFw.mjs";import{t as tc}from"./yazl-DZr4PyKA.mjs";import{n as nc,t as rc}from"./build-CJW5ggp6.mjs";import{t as ic}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ac,c as oc,d as sc,f as cc,h as lc,i as uc,l as dc,m as fc,n as pc,o as mc,p as hc,r as gc,s as _c,t as vc,u as yc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as bc,B as xc,C as Sc,D as Cc,E as wc,F as Tc,H as Ec,I as Dc,L as Oc,M as kc,N as Ac,O as jc,P as Mc,S as Nc,T as Pc,V as Fc,_ as Ic,a as Lc,b as Rc,c as zc,d as Bc,f as Vc,g as Hc,h as Uc,i as Wc,j as Gc,k as Kc,l as qc,m as Jc,n as Yc,o as Xc,p as Zc,r as Qc,s as $c,t as el,u as tl,v as nl,w as rl,x as il,y as al,z as ol}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as sl,c as cl,d as ll,i as ul,l as dl,n as fl,o as pl,r as ml,s as hl,t as gl,u as _l}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as vl,r as yl,t as bl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as xl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Sl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Cl,t as wl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Tl,t as El}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Dl,r as Ol,t as kl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Al,t as jl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Ml}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Nl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Pl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Fl}from"node:module";import{execFile as Il,execFileSync as Ll,spawn as Rl,spawnSync as zl}from"node:child_process";import*as Bl from"node:path";import{basename as Vl,delimiter as Hl,dirname as R,extname as Ul,isAbsolute as Wl,join as z,normalize as Gl,posix as Kl,relative as B,resolve as V,sep as ql,win32 as rte}from"node:path";import{URLSearchParams as ite,fileURLToPath as Jl,pathToFileURL as ate}from"node:url";import*as Yl from"node:fs";import{appendFileSync as ote,chmodSync as Xl,closeSync as Zl,constants as ste,createReadStream as Ql,createWriteStream as $l,existsSync as H,lstatSync as eu,mkdirSync as tu,mkdtempSync as nu,openSync as ru,readFile as cte,readFileSync as U,readSync as lte,readdirSync as iu,readlinkSync as au,realpathSync as W,renameSync as ou,rmSync as su,rmdirSync as cu,statSync as lu,unlinkSync as uu,writeFileSync as du,writeSync as ute}from"node:fs";import{arch as fu,availableParallelism as dte,homedir as pu,hostname as mu,platform as hu,tmpdir as gu}from"node:os";import{access as _u,chmod as fte,constants as vu,lstat as yu,readFile as bu,readdir as xu,realpath as Su,stat as Cu,writeFile as pte}from"node:fs/promises";import{Readable as wu,Transform as mte,Writable as hte}from"node:stream";import Tu,{createHash as Eu,randomUUID as Du,webcrypto as Ou}from"node:crypto";import gte from"crypto";import{Readable as ku}from"stream";import{EventEmitter as _te}from"node:events";import{Worker as vte}from"node:worker_threads";import{monitorEventLoopDelay as yte,performance as Au}from"node:perf_hooks";import{createInterface as bte}from"node:readline";import{pipeline as ju}from"node:stream/promises";import{setImmediate as xte,setTimeout as Mu}from"node:timers/promises";import{promisify as Nu}from"node:util";import{request as Ste}from"node:http";import{Http2ServerRequest as Pu,constants as Cte}from"node:http2";import{lookup as wte}from"node:dns/promises";import{request as Fu}from"node:https";import{createBrotliDecompress as Iu,createGunzip as Lu,createInflate as Ru}from"node:zlib";import{Http2ServerRequest as zu,constants as Bu}from"http2";import{AsyncLocalStorage as Vu}from"node:async_hooks";import{lookup as Hu}from"node:dns";import Uu from"node:tls";function Wu(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Gu(n)}function Gu(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Ku=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Wl(t)?t:V(this.gitDir,t))}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:nd(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=U(z(t.path,`config`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Xu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!ed(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Wl(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=td(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return nd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function qu(e){return Yu(V(e),``)}function Ju(e){let t=V(e),n=V(pu());if(t===n)return{kind:`absent`};let r=Yu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=R(i);if(e===i||e===n)return{kind:`absent`};let r=Yu(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Yu(e,t){let n=z(e,`.git`),r;try{r=lu(n)}catch(e){return $u(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Ku(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Wl(o)?o:V(e,o);try{if(!lu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Ku(`linked`,e,t,n,s)}}function Xu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Zu(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=Qu(i[1]);if(a.length>0)return a}return null}function Zu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Qu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function $u(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function ed(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function td(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?ed(t[1])?{kind:`symbolic`,target:t[1]}:null:nd(e)?{kind:`oid`,oid:e}:null}function nd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function rd(e){return`git-author-${qn(e.trim().toLowerCase())}`}const id=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ad(e){let t=Ju(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function od(e){let t=ad(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function sd(e){let t=ad(e);switch(t.kind){case`directory`:return V(t.path,cd(t.projectSubPath));case`linked`:if(!H(t.path))throw new dd(t.gitPath,t.path);return V(t.path,cd(t.projectSubPath));case`malformed-pointer`:throw new dd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new fd(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function cd(e){return e===``?`ok`:`ok-${ld(e)}`}function ld(e){let t=e.split(ql).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=ud(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function ud(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var dd=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}},fd=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 pd(e){let t;try{t=sd(e)}catch(e){if(e instanceof dd||e instanceof fd)return null;throw e}return H(V(t,`HEAD`))?t:null}function md(e){return`refs/wip/${e}/`}function hd(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{At as r,Ct as i,D as a,Dt as o,E as s,F as c,Ft as l,H as u,It as d,J as f,K as p,Lt as m,Mt as h,Nt as g,O as _,Ot as v,Pt as y,Q as b,R as x,Rt as S,St as C,T as w,U as T,V as E,W as ee,Y as D,Z as O,_ as te,_t as k,at as A,b as ne,bt as j,ct as re,d as ie,dt as M,et as ae,f as oe,ft as se,g as ce,gt as le,ht as ue,i as de,it as N,jt as fe,kt as pe,l as me,lt as he,mt as P,n as ge,nt as _e,ot as ve,pt as F,q as ye,r as be,st as xe,t as Se,tt as Ce,v as we,vt as I,w as Te,wt as Ee,xt as De,y as Oe,yt as ke}from"./sleep-DVOInM4H.mjs";import{$ as Ae,$a as je,$i as Me,$n as Ne,$o as Pe,$r as Fe,$t as Ie,A as Le,Aa as Re,Ai as ze,An as Be,Ao as Ve,Ar as He,At as Ue,B as We,Ba as Ge,Bi as Ke,Bn as qe,Br as Je,Bt as Ye,C as Xe,Ca as Ze,Ci as Qe,Cn as $e,Cr as et,Cs as tt,Ct as nt,D as rt,Da as it,Di as at,Dn as ot,Do as st,Dr as ct,Dt as lt,E as ut,Ea as dt,Ei as ft,En as pt,Eo as mt,Er as ht,Et as gt,F as _t,Fa as vt,Fi as eee,Fn as yt,Fo as bt,Fr as xt,Ft as St,G as Ct,Ga as wt,Gi as Tt,Gn as Et,Go as Dt,Gr as tee,Gt as Ot,H as kt,Ha as At,Hi as nee,Hn as ree,Ho as jt,Hr as iee,Ht as Mt,I as Nt,Ia as Pt,Ii as Ft,In as aee,Io as It,Ir as Lt,J as Rt,Ja as oee,Ji as zt,Jn as see,Jo as Bt,Jr as Vt,Jt as Ht,K as Ut,Ka as Wt,Ki as Gt,Kn as Kt,Ko as qt,Kr as cee,Kt as Jt,L as Yt,La as Xt,Li as lee,Ln as Zt,Lr as Qt,M as $t,Ma as en,Mi as uee,Mn as tn,Mo as nn,Mr as rn,Mt as an,N as on,Na as sn,Ni as cn,Nn as ln,No as un,Nr as dn,Nt as fn,O as pn,Oa as mn,Oi as hn,On as dee,Oo as gn,Or as _n,Os as vn,Ot as fee,P as yn,Pi as bn,Pn as pee,Po as xn,Pr as mee,Pt as Sn,Qa as Cn,Qi as wn,Qn as hee,Qo as Tn,Qr as En,Qt as Dn,Ra as On,Ri as kn,Rn as An,Ro as jn,Rr as Mn,Rt as Nn,S as Pn,Sa as Fn,Si as In,Sn as Ln,So as Rn,Sr as zn,Ss as Bn,St as Vn,T as Hn,Ta as Un,Ti as Wn,Tn as gee,Tr as Gn,Ts as Kn,Tt as qn,U as Jn,Ua as _ee,Ui as vee,Un as Yn,Uo as Xn,Ur as yee,Ut as Zn,V as Qn,Va as bee,Vi as xee,Vn as See,Vo as $n,Vr as er,Vt as tr,W as nr,Wa as rr,Wi as ir,Wn as ar,Wr as or,Wt as sr,X as cr,Xa as lr,Xi as ur,Xn as dr,Xo as fr,Xr as pr,Xt as mr,Ya as hr,Yi as gr,Yn as _r,Yo as vr,Yr as yr,Yt as br,Za as xr,Zi as Sr,Zn as Cr,Zo as wr,Zr as Tr,Zt as Er,_ as Dr,_a as Or,_i as kr,_n as Ar,_o as jr,_r as Mr,_s as Nr,_t as Pr,a as Fr,aa as Ir,ai as Lr,an as Cee,ao as wee,ar as Tee,as as Rr,at as zr,b as Br,ba as Eee,bi as Dee,bn as Vr,br as Oee,bs as Hr,bt as Ur,c as Wr,ca as Gr,ci as Kr,cn as kee,cr as Aee,cs as qr,ct as Jr,d as Yr,da as Xr,di as Zr,dn as jee,do as Qr,dr as Mee,ds as $r,dt as ei,ea as ti,ei as Nee,en as Pee,eo as Fee,er as Iee,es as ni,et as ri,f as ii,fa as Lee,fi as Ree,fn as zee,fr as Bee,fs as Vee,ft as ai,g as oi,ga as si,gi as ci,gn as li,go as ui,gr as di,gs as fi,gt as pi,h as mi,ha as hi,hi as gi,hn as _i,hr as vi,hs as yi,ht as bi,i as xi,ia as Si,ii as Ci,in as wi,io as Ti,ir as Ei,is as Di,it as Oi,j as ki,ja as Ai,ji,jn as Mi,jr as Ni,jt as Pi,k as Fi,ka as Ii,ki as Li,kn as Ri,ko as zi,kr as Bi,kt as Vi,l as Hi,la as Ui,li as Wi,ln as Gi,lo as Ki,lr as qi,lt as Ji,m as Yi,ma as Xi,mi as Zi,mn as Qi,mr as $i,ms as ea,mt as ta,n as na,na as ra,ni as ia,nn as aa,no as oa,nr as sa,ns as ca,nt as la,o as ua,oa as da,oi as fa,on as Hee,oo as pa,or as Uee,os as ma,ot as ha,p as ga,pa as Wee,pi as _a,pn as Gee,po as va,pr as ya,ps as ba,pt as xa,q as Sa,qa as Ca,qi as Kee,qn as qee,qo as wa,qr as Ta,qt as Ea,r as Da,ra as Oa,ri as ka,rn as Jee,ro as Aa,rr as Yee,rs as ja,rt as Ma,s as Na,sa as Pa,si as Fa,sn as Xee,so as Ia,sr as Zee,ss as La,st as Ra,t as za,ta as Ba,ti as Qee,tn as Va,to as $ee,tr as Ha,tt as Ua,u as Wa,ua as Ga,ui as Ka,un as ete,uo as qa,ur as tte,us as Ja,ut as Ya,v as Xa,va as Za,vi as Qa,vn as $a,vo as eo,vr as to,vs as no,vt as ro,w as io,wa as ao,wi as oo,wn as so,wo as co,wr as lo,ws as uo,wt as fo,x as po,xa as mo,xi as ho,xn as go,xo as _o,xr as vo,xs as yo,xt as bo,y as xo,ya as So,yi as Co,yn as wo,yo as To,yr as Eo,ys as Do,yt as Oo,z as ko,za as Ao,zi as jo,zn as Mo,zo as No,zr as Po,zt as Fo}from"./src-IM6msWeV.mjs";import{c as Io,i as Lo,l as Ro,n as zo,s as Bo}from"./esm-DxvI2ZVA.mjs";import{n as Vo,t as Ho}from"./md-manager-DLcJdRDn.mjs";import{A as Uo,C as Wo,D as Go,E as Ko,F as qo,N as Jo,O as Yo,S as Xo,T as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-DVpoNaQJ.mjs";import{D as Ss,E as Cs,S as ws,T as Ts,a as Es,b as Ds,l as Os,p as ks,r as L,s as As,x as js,y as Ms}from"./logger-DFxEUjvj.mjs";import{a as Ns,i as Ps,o as Fs,r as Is,s as Ls,t as Rs}from"./git-handle-D48CPnbp.mjs";import{C as zs,S as Bs,_ as Vs,a as Hs,b as Us,c as Ws,f as Gs,g as Ks,h as qs,i as Js,l as Ys,n as Xs,p as Zs,r as Qs,u as $s,x as nte}from"./server-lock-V3bg8zL0.mjs";import{t as ec}from"./libesm-DzwC_yFw.mjs";import{t as tc}from"./yazl-DZr4PyKA.mjs";import{n as nc,t as rc}from"./build-CJW5ggp6.mjs";import{t as ic}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as ac,c as oc,d as sc,f as cc,h as lc,i as uc,l as dc,m as fc,n as pc,o as mc,p as hc,r as gc,s as _c,t as vc,u as yc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as bc,B as xc,C as Sc,D as Cc,E as wc,F as Tc,H as Ec,I as Dc,L as Oc,M as kc,N as Ac,O as jc,P as Mc,S as Nc,T as Pc,V as Fc,_ as Ic,a as Lc,b as Rc,c as zc,d as Bc,f as Vc,g as Hc,h as Uc,i as Wc,j as Gc,k as Kc,l as qc,m as Jc,n as Yc,o as Xc,p as Zc,r as Qc,s as $c,t as el,u as tl,v as nl,w as rl,x as il,y as al,z as ol}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as sl,c as cl,d as ll,i as ul,l as dl,n as fl,o as pl,r as ml,s as hl,t as gl,u as _l}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as vl,r as yl,t as bl}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as xl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as Sl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as Cl,t as wl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Tl,t as El}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Dl,r as Ol,t as kl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Al,t as jl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Ml}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Nl}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Pl}from"./wrapper-BcpqREsI.mjs";import{createRequire as Fl}from"node:module";import{execFile as Il,execFileSync as Ll,spawn as Rl,spawnSync as zl}from"node:child_process";import*as Bl from"node:path";import{basename as Vl,delimiter as Hl,dirname as R,extname as Ul,isAbsolute as Wl,join as z,normalize as Gl,posix as Kl,relative as B,resolve as V,sep as ql,win32 as rte}from"node:path";import{URLSearchParams as ite,fileURLToPath as Jl,pathToFileURL as ate}from"node:url";import*as Yl from"node:fs";import{appendFileSync as ote,chmodSync as Xl,closeSync as Zl,constants as ste,createReadStream as Ql,createWriteStream as $l,existsSync as H,lstatSync as eu,mkdirSync as tu,mkdtempSync as nu,openSync as ru,readFile as cte,readFileSync as U,readSync as lte,readdirSync as iu,readlinkSync as au,realpathSync as W,renameSync as ou,rmSync as su,rmdirSync as cu,statSync as lu,unlinkSync as uu,writeFileSync as du,writeSync as ute}from"node:fs";import{arch as fu,availableParallelism as dte,homedir as pu,hostname as mu,platform as hu,tmpdir as gu}from"node:os";import{access as _u,chmod as fte,constants as vu,lstat as yu,readFile as bu,readdir as xu,realpath as Su,stat as Cu,writeFile as pte}from"node:fs/promises";import{Readable as wu,Transform as mte,Writable as hte}from"node:stream";import Tu,{createHash as Eu,randomUUID as Du,webcrypto as Ou}from"node:crypto";import gte from"crypto";import{Readable as ku}from"stream";import{EventEmitter as _te}from"node:events";import{Worker as vte}from"node:worker_threads";import{monitorEventLoopDelay as yte,performance as Au}from"node:perf_hooks";import{createInterface as bte}from"node:readline";import{pipeline as ju}from"node:stream/promises";import{setImmediate as xte,setTimeout as Mu}from"node:timers/promises";import{promisify as Nu}from"node:util";import{request as Ste}from"node:http";import{Http2ServerRequest as Pu,constants as Cte}from"node:http2";import{lookup as wte}from"node:dns/promises";import{request as Fu}from"node:https";import{createBrotliDecompress as Iu,createGunzip as Lu,createInflate as Ru}from"node:zlib";import{Http2ServerRequest as zu,constants as Bu}from"http2";import{AsyncLocalStorage as Vu}from"node:async_hooks";import{lookup as Hu}from"node:dns";import Uu from"node:tls";function Wu(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),Gu(n)}function Gu(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Ku=class{kind;projectRoot;projectSubPath;gitPath;gitDir;cachedCommonDir;constructor(e,t,n,r,i){this.kind=e,this.projectRoot=t,this.projectSubPath=n,this.gitPath=r,this.gitDir=i}readCommonDir(){if(this.cachedCommonDir!==void 0)return{kind:`resolved`,path:this.cachedCommonDir};let e=this.gitDir;try{let t=U(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Wl(t)?t:V(this.gitDir,t))}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=U(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}let t=/^ref:[ \t]*(refs\/heads\/(.+))$/.exec(e);return t?.[2]?{kind:`branch`,branch:t[2],ref:t[1]}:nd(e)?{kind:`detached`,oid:e}:{kind:`malformed`,raw:e}}readRemoteUrl(e){let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n;try{n=U(z(t.path,`config`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Xu(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!ed(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=V(t.path,e),r=B(t.path,n);if(r.startsWith(`..`)||Wl(r))return{kind:`invalid`};try{let e=U(n,`utf-8`).trim(),t=td(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!$u(e))return{kind:`unreadable`,cause:e}}let i;try{i=U(z(t.path,`packed-refs`),`utf-8`)}catch(e){return $u(e)?{kind:`absent`}:{kind:`unreadable`,cause:e}}for(let t of i.split(/\r?\n/)){let n=t.trim();if(n.length===0||n.startsWith(`#`)||n.startsWith(`^`))continue;let r=n.split(/\s+/);if(r.length===2&&r[1]===e)return nd(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function qu(e){return Yu(V(e),``)}function Ju(e){let t=V(e),n=V(pu());if(t===n)return{kind:`absent`};let r=Yu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=R(i);if(e===i||e===n)return{kind:`absent`};let r=Yu(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Yu(e,t){let n=z(e,`.git`),r;try{r=lu(n)}catch(e){return $u(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Ku(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=U(n,`utf-8`).trim()}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:``,cause:e}}let a=/^gitdir:[ \t]*(.+)$/.exec(i);if(!a)return{kind:`malformed-pointer`,gitPath:n,target:``};let o=a[1].trim(),s=Wl(o)?o:V(e,o);try{if(!lu(s).isDirectory())return{kind:`malformed-pointer`,gitPath:n,target:s}}catch(e){return{kind:`malformed-pointer`,gitPath:n,target:s,cause:e}}return{kind:`repository`,repository:new Ku(`linked`,e,t,n,s)}}function Xu(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Zu(r);if(e.length===0)continue;if(e.startsWith(`[`)){n=/^\[\s*remote\s+["'](.+)["']\s*\]$/.exec(e)?.[1]===t;continue}if(!n)continue;let i=/^url\s*=\s*(.*)$/.exec(e);if(!i)continue;let a=Qu(i[1]);if(a.length>0)return a}return null}function Zu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Qu(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function $u(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function ed(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function td(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?ed(t[1])?{kind:`symbolic`,target:t[1]}:null:nd(e)?{kind:`oid`,oid:e}:null}function nd(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function rd(e){return`git-author-${qn(e.trim().toLowerCase())}`}const id=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function ad(e){let t=Ju(e);if(t.kind!==`repository`)return t;let{repository:n}=t;return n.kind===`directory`?{kind:`directory`,path:n.gitDir,projectSubPath:n.projectSubPath}:{kind:`linked`,path:n.gitDir,gitPath:n.gitPath,projectSubPath:n.projectSubPath}}function od(e){let t=ad(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function sd(e){let t=ad(e);switch(t.kind){case`directory`:return V(t.path,cd(t.projectSubPath));case`linked`:if(!H(t.path))throw new dd(t.gitPath,t.path);return V(t.path,cd(t.projectSubPath));case`malformed-pointer`:throw new dd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new fd(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function cd(e){return e===``?`ok`:`ok-${ld(e)}`}function ld(e){let t=e.split(ql).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=ud(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function ud(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var dd=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}},fd=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 pd(e){let t;try{t=sd(e)}catch(e){if(e instanceof dd||e instanceof fd)return null;throw e}return H(V(t,`HEAD`))?t:null}function md(e){return`refs/wip/${e}/`}function hd(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 gd=`ok-actor: `;function _d(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),`${gd}${JSON.stringify(i)}`}function vd(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=yd(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 yd(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 bd(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(gd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:vd(n)}return null}function xd(e){if(!e)return[];let t=[];for(let n of e.split(`
4
4
  `)){let e=n.trim();if(!e.startsWith(gd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=vd(r);i&&t.push(i)}return t}function Sd(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 Cd(e){let t=xd(e);return t.length>0?t.map(Sd):hd(e)}function wd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Td(e){return`reconcile: ${e}`}function Ed(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Dd(e,t){return`park: ${e} -> ${t}`}function Od(e,t){return`rename: ${e} -> ${t}`}function kd(e){return`checkpoint: ${e}`}function Ad(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const jd=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Md(e){return e.replace(jd,` `)}function Nd(e,t){let n=Md(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=Md(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 Pd(e){return id.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Fd(e){let t=ad(e);if(t.kind!==`linked`)return V(e);try{let n=U(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function Id(e){return e.kind??`other`}function Ld(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Rd=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Id(t),i=Ld(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=Id(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-_QGcVmcb.mjs`);await e(z(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(U(this.filePath,`utf8`));this.grants=Array.isArray(e?.grants)?e.grants.filter(e=>typeof e?.agentId==`string`&&typeof e?.toolKind==`string`):[]}catch{this.grants=[]}return this.grants}};const zd=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Bd={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Vd=`acp-agents.json`,Hd=`acp-registry-cache.json`;function Ud(){let e=hu(),t=fu(),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 Wd=new Set([`goose`,`fast-agent`,`crow-cli`]);function Gd(e,t){let n=t.trim();return n.length===0?e:Wd.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Kd(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 qd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Kd).map(e=>({...e,name:Gd(e.id,e.name)})):null}var Jd=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=qd(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-_QGcVmcb.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Hd),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=qd(await bu(z(this.localDir,Hd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Yd(e,t){let n;try{n=await bu(z(e,Vd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Vd} 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 ${Vd} entry`)}return i}const Xd={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`},Zd={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`},Qd={cancel_request:`$/cancel_request`},$d=Symbol(`skippedItem`);function G(e,t){return e.catch(t)}function ef(e,t){let n=e.catch(t);return j().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),S):n.parse(e))}function tf(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function nf(e,t,n){return e.superRefine((e,r)=>{let i=tf(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 rf(e,t,n){return j().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return S}let o=a.data,s=tf(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 af(e){return N(e.catch($d)).transform(e=>e.filter(e=>e!==$d))}const of=ke([F(),I()]).nullable(),sf=I(),cf=P({sessionId:sf,path:I(),content:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),lf=P({sessionId:sf,path:I(),line:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),uf=I(),df=ke([M(`read`),M(`edit`),M(`delete`),M(`move`),M(`search`),M(`execute`),M(`think`),M(`fetch`),M(`switch_mode`),M(`other`)]),ff=ke([M(`pending`),M(`in_progress`),M(`completed`),M(`failed`)]),pf=P({audience:G(af(ke([M(`assistant`),M(`user`)])).nullish(),()=>void 0),lastModified:G(I().nullish(),()=>void 0),priority:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),mf=P({annotations:G(pf.nullish(),()=>void 0),text:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),hf=P({annotations:G(pf.nullish(),()=>void 0),data:I(),mimeType:I(),uri:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),gf=P({annotations:G(pf.nullish(),()=>void 0),data:I(),mimeType:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),_f=P({annotations:G(pf.nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),mimeType:G(I().nullish(),()=>void 0),name:I(),size:G(F().nullish(),()=>void 0),title:G(I().nullish(),()=>void 0),uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),vf=ke([P({mimeType:G(I().nullish(),()=>void 0),text:I(),uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),P({blob:I(),mimeType:G(I().nullish(),()=>void 0),uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)})]),yf=P({annotations:G(pf.nullish(),()=>void 0),resource:vf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),bf=ke([mf.and(P({type:M(`text`)})),hf.and(P({type:M(`image`)})),gf.and(P({type:M(`audio`)})),_f.and(P({type:M(`resource_link`)})),yf.and(P({type:M(`resource`)}))]),xf=P({content:bf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Sf=P({path:I(),oldText:G(I().nullish(),()=>void 0),newText:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Cf=I(),wf=P({terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Tf=ke([xf.and(P({type:M(`content`)})),Sf.and(P({type:M(`diff`)})),wf.and(P({type:M(`terminal`)}))]),Ef=P({path:I(),line:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Df=P({toolCallId:uf,kind:G(df.nullish(),()=>void 0),status:G(ff.nullish(),()=>void 0),title:G(I().nullish(),()=>void 0),content:G(af(Tf).nullish(),()=>void 0),locations:G(af(Ef).nullish(),()=>void 0),rawInput:G(j().optional(),()=>void 0),rawOutput:G(j().optional(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Of=I(),kf=ke([M(`allow_once`),M(`allow_always`),M(`reject_once`),M(`reject_always`)]),Af=P({sessionId:sf,toolCall:Df,options:N(P({optionId:Of,name:I(),kind:kf,_meta:G(k(I(),j()).nullish(),()=>void 0)})),_meta:G(k(I(),j()).nullish(),()=>void 0)}),jf=P({name:I(),value:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Mf=P({sessionId:sf,command:I(),args:G(af(I()).optional(),()=>[]),env:G(af(jf).optional(),()=>[]),cwd:G(I().nullish(),()=>void 0),outputByteLimit:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Nf=P({sessionId:sf,terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Pf=P({sessionId:sf,terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ff=P({sessionId:sf,terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),If=P({sessionId:sf,terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Lf=P({sessionId:sf,toolCallId:G(uf.nullish(),()=>void 0)}),Rf=P({requestId:of}),zf=M(`object`),Bf=ke([M(`email`),M(`uri`),M(`date`),M(`date-time`)]),Vf=P({const:I(),title:I(),description:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Hf=P({title:G(I().nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),minLength:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:I().nullish(),format:Bf.nullish(),default:G(I().nullish(),()=>void 0),enum:N(I()).nullish(),oneOf:N(Vf).nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Uf=P({title:G(I().nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),minimum:F().nullish(),maximum:F().nullish(),default:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Wf=P({title:G(I().nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),minimum:F().nullish(),maximum:F().nullish(),default:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Gf=P({title:G(I().nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),default:G(A().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Kf=P({enum:N(I()),_meta:G(k(I(),j()).nullish(),()=>void 0)}),qf=P({anyOf:N(Vf),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Jf=rf(ke([Kf.and(P({type:M(`string`)})),nf(P({type:I()}),`type`,[`string`]),qf]),`type`,[`string`]),Yf=P({title:G(I().nullish(),()=>void 0),description:G(I().nullish(),()=>void 0),minItems:F().nullish(),maxItems:F().nullish(),items:Jf,default:G(af(I()).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Xf=rf(ke([Hf.and(P({type:M(`string`)})),Uf.and(P({type:M(`number`)})),Wf.and(P({type:M(`integer`)})),Gf.and(P({type:M(`boolean`)})),Yf.and(P({type:M(`array`)})),nf(P({type:I()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Zf=P({type:G(zf.optional().default(`object`),()=>`object`),title:G(I().nullish(),()=>void 0),properties:k(I(),Xf).optional().default({}),required:N(I()).nullish(),description:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Qf=he(ke([Lf,Rf]),P({requestedSchema:Zf})),$f=I(),ep=he(ke([Lf,Rf]),P({elicitationId:$f,url:De()})),tp=rf(he(ke([Qf.and(P({mode:M(`form`)})),ep.and(P({mode:M(`url`)})),nf(he(ke([Lf,Rf]),P({mode:I()})),`mode`,[`form`,`url`])]),P({message:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),np=I(),Tte=P({serverId:np,_meta:G(k(I(),j()).nullish(),()=>void 0)}),rp=I(),ip=P({connectionId:rp,method:I(),params:k(I(),j()).nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ete=P({connectionId:rp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),ap=j();P({id:of,method:I(),params:ke([cf,lf,Af,Mf,Nf,Pf,Ff,If,tp,Tte,ip,Ete,ap]).nullish()});const op=re().gte(0).lte(65535),Dte=P({image:G(A().optional().default(!1),()=>!1),audio:G(A().optional().default(!1),()=>!1),embeddedContext:G(A().optional().default(!1),()=>!1),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ote=P({http:G(A().optional().default(!1),()=>!1),sse:G(A().optional().default(!1),()=>!1),acp:G(A().optional().default(!1),()=>!1),_meta:G(k(I(),j()).nullish(),()=>void 0)}),kte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ate=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),jte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Mte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Nte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Pte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Fte=P({list:G(kte.nullish(),()=>void 0),delete:G(Ate.nullish(),()=>void 0),additionalDirectories:G(jte.nullish(),()=>void 0),fork:G(Mte.nullish(),()=>void 0),resume:G(Nte.nullish(),()=>void 0),close:G(Pte.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ite=P({logout:G(P({_meta:G(k(I(),j()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Lte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Rte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),zte=P({syncKind:ke([M(`full`),M(`incremental`)]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Bte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Vte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Hte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ute=P({document:G(P({didOpen:G(Rte.nullish(),()=>void 0),didChange:G(zte.nullish(),()=>void 0),didClose:G(Bte.nullish(),()=>void 0),didSave:G(Vte.nullish(),()=>void 0),didFocus:G(Hte.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Wte=P({maxCount:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Gte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Kte=P({maxCount:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),qte=P({maxCount:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Jte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Yte=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Xte=P({recentFiles:G(Wte.nullish(),()=>void 0),relatedSnippets:G(Gte.nullish(),()=>void 0),editHistory:G(Kte.nullish(),()=>void 0),userActions:G(qte.nullish(),()=>void 0),openFiles:G(Jte.nullish(),()=>void 0),diagnostics:G(Yte.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Zte=P({events:G(Ute.nullish(),()=>void 0),context:G(Xte.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),sp=ke([M(`utf-16`),M(`utf-32`),M(`utf-8`)]),Qte=P({loadSession:G(A().optional().default(!1),()=>!1),promptCapabilities:G(Dte.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:G(Ote.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:G(Fte.optional().default({}),()=>({})),auth:G(Ite.optional().default({}),()=>({})),providers:G(Lte.nullish(),()=>void 0),nes:G(Zte.nullish(),()=>void 0),positionEncoding:G(sp.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),cp=I(),$te=P({name:I(),label:G(I().nullish(),()=>void 0),secret:G(A().optional().default(!0),()=>!0),optional:G(A().optional().default(!1),()=>!1),_meta:G(k(I(),j()).nullish(),()=>void 0)}),ene=P({id:cp,name:I(),description:G(I().nullish(),()=>void 0),vars:ef(af($te),()=>[]),link:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),tne=P({id:cp,name:I(),description:G(I().nullish(),()=>void 0),args:G(af(I()).optional(),()=>[]),env:G(k(I(),I()).optional(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),nne=P({id:cp,name:I(),description:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),rne=ke([ene.and(P({type:M(`env_var`)})),tne.and(P({type:M(`terminal`)})),nne]),lp=P({name:I(),title:G(I().nullish(),()=>void 0),version:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),ine=P({protocolVersion:op,agentCapabilities:G(Qte.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:G(af(rne).optional().default([]),()=>[]),agentInfo:G(lp.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),ane=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),up=I(),dp=ke([M(`anthropic`),M(`openai`),M(`azure`),M(`vertex`),M(`bedrock`),I()]),one=P({apiType:dp,baseUrl:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),sne=P({providers:N(P({providerId:up,supported:ef(af(dp),()=>[]),required:A(),current:one.nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)})),_meta:G(k(I(),j()).nullish(),()=>void 0)}),cne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),lne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),une=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),fp=I(),pp=P({currentModeId:fp,availableModes:ef(af(P({id:fp,name:I(),description:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)})),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),mp=I(),dne=ke([M(`mode`),M(`model`),M(`model_config`),M(`thought_level`),I()]),hp=I(),gp=P({value:hp,name:I(),description:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),fne=P({group:I(),name:I(),options:ef(af(gp),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),pne=P({currentValue:hp,options:ke([N(gp),N(fne)])}),mne=P({currentValue:A()}),_p=he(ke([pne.and(P({type:M(`select`)})),mne.and(P({type:M(`boolean`)}))]),P({id:mp,name:I(),description:G(I().nullish(),()=>void 0),category:G(dne.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)})),hne=P({sessionId:sf,modes:G(pp.nullish(),()=>void 0),configOptions:G(af(_p).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),gne=P({modes:G(pp.nullish(),()=>void 0),configOptions:G(af(_p).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),_ne=P({sessions:ef(af(P({sessionId:sf,cwd:I(),additionalDirectories:G(af(I()).optional(),()=>[]),title:G(I().nullish(),()=>void 0),updatedAt:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)})),()=>[]),nextCursor:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),vne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),yne=P({sessionId:sf,modes:G(pp.nullish(),()=>void 0),configOptions:G(af(_p).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),bne=P({modes:G(pp.nullish(),()=>void 0),configOptions:G(af(_p).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),xne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Sne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Cne=P({configOptions:ef(af(_p),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),wne=P({stopReason:ke([M(`end_turn`),M(`max_tokens`),M(`max_turn_requests`),M(`refusal`),M(`cancelled`)]),usage:G(P({totalTokens:F(),inputTokens:F(),outputTokens:F(),thoughtTokens:G(F().nullish(),()=>void 0),cachedReadTokens:G(F().nullish(),()=>void 0),cachedWriteTokens:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Tne=P({sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),vp=I(),yp=P({line:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:G(k(I(),j()).nullish(),()=>void 0)}),bp=P({start:yp,end:yp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ene=P({range:bp,newText:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Dne=P({id:vp,uri:I(),edits:N(Ene),cursorPosition:G(yp.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),One=P({id:vp,uri:I(),position:yp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),kne=P({id:vp,uri:I(),position:yp,newName:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ane=P({id:vp,uri:I(),search:I(),replace:I(),isRegex:A().nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),jne=P({suggestions:N(ke([Dne.and(P({kind:M(`edit`)})),One.and(P({kind:M(`jump`)})),kne.and(P({kind:M(`rename`)})),Ane.and(P({kind:M(`searchAndReplace`)}))])),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Mne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),xp=j(),Sp=j(),Cp=P({code:ke([M(-32700),M(-32600),M(-32601),M(-32602),M(-32603),M(-32800),M(-32e3),M(-32002),re().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:I(),data:G(j().optional(),()=>void 0)});ke([P({id:of,result:ke([ine,ane,sne,cne,lne,une,hne,gne,_ne,vne,yne,bne,xne,Sne,Cne,wne,Tne,jne,Mne,xp,Sp])}),P({id:of,error:Cp})]);const wp=P({content:bf,messageId:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Nne=P({toolCallId:uf,title:I(),kind:G(df.optional(),()=>void 0),status:G(ff.optional(),()=>void 0),content:G(af(Tf).optional(),()=>[]),locations:G(af(Ef).optional(),()=>[]),rawInput:G(j().optional(),()=>void 0),rawOutput:G(j().optional(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Pne=ke([M(`high`),M(`medium`),M(`low`)]),Fne=ke([M(`pending`),M(`in_progress`),M(`completed`)]),Tp=P({content:I(),priority:Pne,status:Fne,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ine=P({entries:ef(af(Tp),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ep=I(),Lne=P({planId:Ep,entries:ef(af(Tp),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Rne=P({planId:Ep,uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),zne=P({planId:Ep,content:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Bne=P({plan:ke([Lne.and(P({type:M(`items`)})),Rne.and(P({type:M(`file`)})),zne.and(P({type:M(`markdown`)}))]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Vne=P({planId:Ep,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Hne=P({hint:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Une=P({availableCommands:ef(af(P({name:I(),description:I(),input:G(Hne.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)})),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Wne=P({currentModeId:fp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Gne=P({configOptions:ef(af(_p),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Kne=P({title:G(I().nullish(),()=>void 0),updatedAt:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),qne=P({amount:F(),currency:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Jne=P({used:F(),size:F(),cost:G(qne.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Dp=P({sessionId:sf,update:ke([wp.and(P({sessionUpdate:M(`user_message_chunk`)})),wp.and(P({sessionUpdate:M(`agent_message_chunk`)})),wp.and(P({sessionUpdate:M(`agent_thought_chunk`)})),Nne.and(P({sessionUpdate:M(`tool_call`)})),Df.and(P({sessionUpdate:M(`tool_call_update`)})),Ine.and(P({sessionUpdate:M(`plan`)})),Bne.and(P({sessionUpdate:M(`plan_update`)})),Vne.and(P({sessionUpdate:M(`plan_removed`)})),Une.and(P({sessionUpdate:M(`available_commands_update`)})),Wne.and(P({sessionUpdate:M(`current_mode_update`)})),Gne.and(P({sessionUpdate:M(`config_option_update`)})),Kne.and(P({sessionUpdate:M(`session_info_update`)})),Jne.and(P({sessionUpdate:M(`usage_update`)}))]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Op=P({elicitationId:$f,_meta:G(k(I(),j()).nullish(),()=>void 0)}),kp=P({connectionId:rp,method:I(),params:G(k(I(),j()).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ap=j();P({method:I(),params:ke([Dp,Op,kp,Ap]).nullish()});const Yne=P({readTextFile:G(A().optional().default(!1),()=>!1),writeTextFile:G(A().optional().default(!1),()=>!1),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Xne=P({configOptions:G(P({boolean:G(P({_meta:G(k(I(),j()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Zne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Qne=P({terminal:G(A().optional().default(!1),()=>!1),_meta:G(k(I(),j()).nullish(),()=>void 0)}),$ne=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),ere=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),tre=P({form:G($ne.nullish(),()=>void 0),url:G(ere.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),nre=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),rre=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),ire=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),are=P({jump:G(nre.nullish(),()=>void 0),rename:G(rre.nullish(),()=>void 0),searchAndReplace:G(ire.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),jp=P({protocolVersion:op,clientCapabilities:G(P({fs:G(Yne.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:G(A().optional().default(!1),()=>!1),session:G(Xne.nullish(),()=>void 0),plan:G(Zne.nullish(),()=>void 0),auth:G(Qne.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:G(tre.nullish(),()=>void 0),nes:G(are.nullish(),()=>void 0),positionEncodings:G(af(sp).optional(),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:G(lp.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Mp=P({methodId:cp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Np=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Pp=P({providerId:up,apiType:dp,baseUrl:I(),headers:k(I(),I()).optional(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Fp=P({providerId:up,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ip=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Lp=P({name:I(),value:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),ore=P({name:I(),url:I(),headers:N(Lp),_meta:G(k(I(),j()).nullish(),()=>void 0)}),sre=P({name:I(),url:I(),headers:N(Lp),_meta:G(k(I(),j()).nullish(),()=>void 0)}),cre=P({name:I(),serverId:np,_meta:G(k(I(),j()).nullish(),()=>void 0)}),lre=P({name:I(),command:I(),args:N(I()),env:N(jf),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Rp=ke([ore.and(P({type:M(`http`)})),sre.and(P({type:M(`sse`)})),cre.and(P({type:M(`acp`)})),lre]),zp=P({cwd:I(),additionalDirectories:G(af(I()).optional(),()=>[]),mcpServers:ef(af(Rp),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Bp=P({mcpServers:ef(af(Rp),()=>[]),cwd:I(),additionalDirectories:G(af(I()).optional(),()=>[]),sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Vp=P({cwd:I().nullish(),cursor:I().nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Hp=P({sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Up=P({sessionId:sf,cwd:I(),additionalDirectories:G(af(I()).optional(),()=>[]),mcpServers:G(af(Rp).optional(),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Wp=P({sessionId:sf,cwd:I(),additionalDirectories:G(af(I()).optional(),()=>[]),mcpServers:G(af(Rp).optional(),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Gp=P({sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Kp=P({sessionId:sf,modeId:fp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),qp=he(ke([P({value:A(),type:M(`boolean`)}),P({value:hp})]),P({sessionId:sf,configId:mp,_meta:G(k(I(),j()).nullish(),()=>void 0)})),Jp=P({sessionId:sf,prompt:N(bf),_meta:G(k(I(),j()).nullish(),()=>void 0)}),ure=P({uri:I(),name:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),dre=P({name:I(),owner:I(),remoteUrl:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Yp=P({workspaceUri:G(I().nullish(),()=>void 0),workspaceFolders:N(ure).nullish(),repository:G(dre.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),fre=ke([M(`automatic`),M(`diagnostic`),M(`manual`)]),pre=P({uri:I(),languageId:I(),text:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),mre=P({startLine:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),hre=P({uri:I(),excerpts:N(mre),_meta:G(k(I(),j()).nullish(),()=>void 0)}),gre=P({uri:I(),diff:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),_re=P({action:I(),uri:I(),position:yp,timestampMs:F(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),vre=P({uri:I(),languageId:I(),visibleRange:G(bp.nullish(),()=>void 0),lastFocusedMs:G(F().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),yre=ke([M(`error`),M(`warning`),M(`information`),M(`hint`)]),bre=P({uri:I(),range:bp,severity:yre,message:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),xre=P({recentFiles:N(pre).nullish(),relatedSnippets:N(hre).nullish(),editHistory:N(gre).nullish(),userActions:N(_re).nullish(),openFiles:N(vre).nullish(),diagnostics:N(bre).nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Xp=P({sessionId:sf,uri:I(),version:F(),position:yp,selection:bp.nullish(),triggerKind:fre,context:xre.nullish(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Zp=P({sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)});P({id:of,method:I(),params:ke([jp,Mp,Np,Pp,Fp,Ip,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,ip,ap]).nullish()});const Sre=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Cre=P({content:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),wre=P({optionId:Of,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Tre=P({outcome:ke([P({outcome:M(`cancelled`)}),wre.and(P({outcome:M(`selected`)}))]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ere=P({terminalId:Cf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Dre=P({exitCode:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Ore=P({output:I(),truncated:A(),exitStatus:G(Dre.nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),kre=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Are=P({exitCode:G(re().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:G(I().nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)}),jre=P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Mre=ke([I(),F(),F(),A(),N(I())]),Qp=P({content:k(I(),Mre).nullish()});ke([P({id:of,result:ke([Sre,Cre,Tre,Ere,Ore,kre,Are,jre,rf(he(ke([Qp.and(P({action:M(`accept`)})),P({action:M(`decline`)}),P({action:M(`cancel`)}),nf(P({action:I()}),`action`,[`accept`,`cancel`,`decline`])]),P({_meta:G(k(I(),j()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),P({connectionId:rp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),P({_meta:G(k(I(),j()).nullish(),()=>void 0)}),Sp,xp])}),P({id:of,error:Cp})]);const $p=P({sessionId:sf,_meta:G(k(I(),j()).nullish(),()=>void 0)}),em=P({sessionId:sf,uri:I(),languageId:I(),version:F(),text:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),Nre=P({range:bp.nullish(),text:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),tm=P({sessionId:sf,uri:I(),version:F(),contentChanges:ef(af(Nre),()=>[]),_meta:G(k(I(),j()).nullish(),()=>void 0)}),nm=P({sessionId:sf,uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),rm=P({sessionId:sf,uri:I(),_meta:G(k(I(),j()).nullish(),()=>void 0)}),im=P({sessionId:sf,uri:I(),version:F(),position:yp,visibleRange:bp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),am=P({sessionId:sf,id:vp,_meta:G(k(I(),j()).nullish(),()=>void 0)}),om=P({sessionId:sf,id:vp,reason:G(ke([M(`rejected`),M(`ignored`),M(`replaced`),M(`cancelled`)]).nullish(),()=>void 0),_meta:G(k(I(),j()).nullish(),()=>void 0)});P({method:I(),params:ke([$p,em,tm,nm,rm,im,am,om,kp,Ap]).nullish()}),P({requestId:of,_meta:G(k(I(),j()).nullish(),()=>void 0)}),Qf.and(P({mode:M(`form`)})).and(P({message:I()})),ep.and(P({mode:M(`url`)})).and(P({message:I()})),ke([Lf,Rf]).and(P({message:I()})),Hf.and(P({type:M(`string`)})),Uf.and(P({type:M(`number`)})),Wf.and(P({type:M(`integer`)})),Gf.and(P({type:M(`boolean`)})),Yf.and(P({type:M(`array`)})),Kf.and(P({type:M(`string`)})),Qp.and(P({action:M(`accept`)})),P({action:M(`decline`)}),P({action:M(`cancel`)});const sm=`$/cancel_request`;function cm(e){return typeof e==`object`&&!!e}function Pre(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Fre(e){if(!(!cm(e)||!Pre(e.requestId)))return e.requestId}const lm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function um(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Ire(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Lre(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 dm(e){if(e instanceof mm)return e.toResult();if(Lre(e))return mm.invalidParams(e.format()).toResult();let t=Ire(e);try{return mm.internalError(t?JSON.parse(t):{}).toResult()}catch{return mm.internalError({details:t}).toResult()}}function Rre(e){return e instanceof mm&&e.code===-32800?e:mm.requestCancelled(e)}function zre(e,t){let n=Bre(e,t);return n?n.toResult():dm(e)}function Bre(e,t){if(!(!t.aborted||!Vre(e)))return Rre(t.reason)}function Vre(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Hre=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 mm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?um(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},fm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Ure=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}},pm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Ure(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 Wre}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 fm(()=>{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 um(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(sm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?um(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 lm.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(!cm(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(mm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(zre(n,t.responder.signal));else{let t=dm(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 Hre(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&&cm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new mm(n,r,i))}else t.reject(mm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==sm)return;let t=Fre(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(mm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?um(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)}},Wre=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)??lm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?lm.no(r):await n(t(r.params),r.responder,i)??lm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?lm.no(r):await n(t(r.params),i)??lm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new pm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},mm=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}}},Gre=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 Kre(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Gre,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);cm(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)+`
@@ -1214,7 +1214,7 @@ tags: [lore, history]
1214
1214
  `:``)+t).md;Tb(b.dc.document,i,`agent`,void 0,S),hS(`mcp-write`),E=!0}T=!0},b.origin)})}finally{k?.touchMode(l,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}q(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(T&&ee.length>0){if(Wj(c,l,u,d,void 0,bn({clientName:f,clientVersion:p,label:m}),y),Wb(),wn(_),E){let e=await vt(c);if(e?.kind===`failure`){bt(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){xt(r,`frontmatter-patch`);return}}_t(c,`frontmatter-patch`)}te?.setFocus(l,{agentName:u,currentDoc:c,writeKind:`write`,ts:Date.now()}),ne?.();let D=dt(c),O=ft();O===0&&kZ().add(1,{"shadow.writer":`agent`,"agent.type":$m(f)});let A=St(x);Nt(c,b.dc.document.getText(`source`).toString());let j=await Tt();j.add(c);let re=AL(b.dc.document.getText(`source`).toString(),c,j,Mt);Y(r,200,Kee,{timestamp:C,subscriberCount:D,systemSubscriberCount:O,appliedKeys:ee,...v?{summary:v}:{},...A?{warning:A,warnings:[A]}:{},brokenLinks:re},{handler:`frontmatter-patch`})}catch(e){if(e instanceof Gw){q(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e,requestId:Qx(n)},`[frontmatter-patch] handler failed`),q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`}),In=J(lo,async(e,t)=>{try{let e=Fd(M??s),n=tk({projectDir:e}),r=new Set(BI(s).map(e=>e.name)),i=new Set(VI(ao).map(e=>e.name));Y(t,200,Fi,{...n,skills:n.skills.filter(t=>Xe(t.provenance,e)&&!(t.provenance.scope===`project`?r.has(t.name):i.has(t.name))).map(e=>io(e.provenance,e.home,M??s)?{...e,outsideProject:!0}:e)},{handler:`skills-installed`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to enumerate installed skills.`,{handler:`skills-installed`,cause:e})}},{handler:`skills-installed`,method:`GET`,skipBodyParse:!0}),Rn=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`prefix`),i=n.searchParams.get(`docNames`);if(r===null&&i===null){q(t,400,`urn:ok:error:invalid-request`,`Missing docNames or prefix parameter.`,{handler:`comment-counts`});return}let a={};if(r!==null){let e=r.trim();if(e!==``&&!hQ(e)){q(t,400,`urn:ok:error:invalid-request`,`Invalid prefix parameter.`,{handler:`comment-counts`});return}a=Object.fromEntries(await Qe.countThreads({prefix:e}))}else{let e=(i??``).split(`,`).map(e=>e.trim()).filter(e=>e!==``&&hQ(e));a=Object.fromEntries(await Qe.countThreads({docNames:e}))}Y(t,200,Dee,{counts:a},{handler:`comment-counts`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read comment counts.`,{handler:`comment-counts`,cause:e})}},{handler:`comment-counts`,method:`GET`,skipBodyParse:!0}),Vn=J(eee,async(n,r,i)=>{try{let{find:n,replace:c,offset:l}=i,u=ZZ(i.docName,r,`agent-patch`);if(u===null)return;let d=ut(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=yn(i);if(vpe(n)){jZ().add(1,{result:`rejected`}),q(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(Vx(d)||Hx(d)){q(r,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=Mk(i.summary),y=await o.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),b=_R(t,a,d,s,e.resolveEmbed,ae?.()),x=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,S;{let{frontmatter:e,body:t}=eo(y.dc.document.getText(`source`).toString()),r=jr(e,t),i=l==null?r.indexOf(n):r.slice(l,l+n.length)===n?l:-1;if(i!==-1&&i>=e.length){let e=r.slice(0,i)+c+r.slice(i+n.length);S=await jw(y.dc.document,eo(e).body,`patch`,x)}}let C=new Date().toISOString(),w=!1,T=!1,E=!1,ee,D;try{let e=Yr(h),t=Wr[e]??Hi(m??f);if(k?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),D=jk(y.dc.document.getText(`source`),f,y.origin,m,h),y.dc.document.transact(()=>{let{frontmatter:e,body:t}=eo(y.dc.document.getText(`source`).toString()),r=jr(e,t),i=l==null?r.indexOf(n):r.slice(l,l+n.length)===n?l:-1;if(i===-1){l==null?w=!0:T=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:n.length,replaceLength:c.length,hadOffset:l!=null})),aoe();return}if(i<e.length){E=!0;return}let{body:a}=eo(r.slice(0,i)+c+r.slice(i+n.length)),o=Iw(y.dc.document);ee=Fw(y.dc.document,a,`patch`,x,S,Nw(y));let s=Bn(o,Iw(y.dc.document))??void 0;y.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${n.slice(0,50)}`,...s===void 0?{}:{changedBlocks:s}})},y.origin),ee!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:ee.intendedBytes,actualBytes:ee.actualBytes,byteDelta:ee.byteDelta,"agent.id":f,"agent.client_name":h})),!w&&!T&&!E){let{stored:e}=xn(v);Wj(d,f,p,m,void 0,bn({clientName:h,clientVersion:g,label:_}),e),Wb(),wn(v),IZ(`agent-patch`,ee)}}finally{D?.(),k?.touchMode(f,`idle`)}if(T){q(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(w){q(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(E){jZ().add(1,{result:`rejected`}),q(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let O=await vt(d);if(O?.kind===`failure`){bt(r,O.failure,`agent-patch`);return}if(O?.kind===`divergence`){xt(r,`agent-patch`);return}_t(d,`agent-patch`),te?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),ne?.();let A=dt(d),j=ft();j===0&&kZ().add(1,{"shadow.writer":`agent`,"agent.type":$m(h)});let{response:re}=xn(v),ie=y.dc.document.getText(`source`).toString();Nt(d,ie);let M=await aF(ie,d),oe=await Tt();oe.add(d);let se=AL(ie,d,oe,Mt),ce=St(b),le=ee===void 0?void 0:uS(ee),ue=[...le?[le]:[],...ce?[ce]:[],...M??[],...await Tc(y.dc.document.getText(`source`).toString(),d)];Y(r,200,Ft,{timestamp:C,subscriberCount:A,systemSubscriberCount:j,...re?{summary:re}:{},...le?{warning:le}:ce?{warning:ce}:{},...ue.length>0?{warnings:ue}:{},brokenLinks:se},{handler:`agent-patch`})}catch(e){if(e instanceof oS){sS(r,e,`agent-patch`);return}if(e instanceof dS){pS(r,e,`agent-patch`);return}if(e instanceof Gw){q(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e,requestId:Qx(n)},`[agent-patch] handler failed`),q(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),Hn=J(lee,async(t,n,r)=>{try{let t=ZZ(r.docName,n,`agent-undo`);if(t===null)return;let i=ut(t),{agentId:a,agentName:s,colorSeed:c,clientName:l,clientVersion:u,label:d}=yn(r);if(Vx(i)||Hx(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=r,p,m;if(r.scope===`count`?(p=`count`,m=r.count):p=r.scope===`session`||r.scope===`file`?`session`:`last`,!o.hasSession(i,f)){q(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await o.getSession(i,f),g=!1;try{let t=Yr(l),n=Wr[t]??Hi(c??a);k?.setPresence(a,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=zw(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&Wj(i,f,s,c,void 0,bn({clientName:l,clientVersion:u,label:d}))}finally{k?.touchMode(a,`idle`)}if(g){let e=await vt(i);if(e?.kind===`failure`){bt(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){xt(n,`agent-undo`);return}ht(i,`agent-undo`)}te?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),Y(n,200,kn,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof oS){sS(n,e,`agent-undo`);return}Z.error({err:e,requestId:Qx(t)},`[agent-undo] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),Un=J(lo,async(e,t)=>{try{let n=Xm(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}Y(t,200,dn,jC(o,n),{handler:`agent-activity`})}catch(n){Z.error({err:n,requestId:Qx(e)},`[agent-activity] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),Wn=J(lo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Xm(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){q(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){q(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!hQ(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let s=ut(i);if(Vx(s)||Hx(s)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${s}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!a||Number.isNaN(Number(a))){q(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(a);if(!Number.isInteger(c)||c<0){q(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=o.getLiveSession(s,r);if(!l){q(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){q(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=l.dc.document.getText(`source`),{diff:f,before:p,after:m}=OC(u.undoStack,c,d,s);Y(t,200,mee,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Z.error({err:n,requestId:Qx(e)},`[agent-burst-diff] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),Gn=J(lo,async(e,t)=>{try{await C?.(),Y(t,200,iee,{},{handler:`test-flush-git`})}catch(n){Z.error({err:n,requestId:Qx(e)},`[test-flush-git] flush failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),Kn=J(lo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=ut(n.searchParams.get(`docName`)??`test-doc`),i;try{i=iN(r,s)}catch(e){Z.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),q(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await o.closeAll(r),a.closeConnections(r);let c=`onStoreDocument-${r}`;a.debouncer.isDebounced(c)&&await a.debouncer.executeNow(c);let l=a.documents.get(r);if(l&&await(pe??a.unloadDocument.bind(a))(l),du(i,``,`utf-8`),await D?.testOnly?.resetDocumentForTest(r),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=V(s,`.okignore`),t=a.documents.get(ja);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},cA)}H(e)&&du(e,``,`utf-8`),de&&await de.rebuildIgnorePatterns()}catch(e){Z.warn({err:e},`[test-reset] okignore reset partial failure`)}O?.(`files`),Y(t,200,tee,{},{handler:`test-reset`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),qn=J(lo,async(e,t)=>{try{if(!D?.testOnly){q(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await D.testOnly.rescanBacklinksForTest(),Y(t,200,yee,{},{handler:`test-rescan-backlinks`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),Jn=J(lo,async(e,t)=>{try{if(!y){q(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await y(),O?.(`files`),Y(t,200,or,{},{handler:`test-rescan-files`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),Xn=Qfe({getCurrentBranch:T,contentRoot:ee}),Zn=aZ(),Qn=J(Zi,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=yn(n),o=S?.current;if(!o){q(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let s=/^[a-zA-Z0-9_-]+$/,c=[];if(Array.isArray(n.writers))try{c=n.writers.map(e=>{let t=e.id??`unknown`;if(!s.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){q(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let l=e===void 0?void 0:{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`},u=Mk(typeof n.summary==`string`?n.summary:void 0);Y(t,200,gi,{checkpointRef:(await Xn.saveCheckpoint(o,{explicitWriters:c,agentWriter:l,summary:u.kind===`value`?u.value:void 0})).checkpointRef},{handler:`save-version`})}catch(n){Z.error({err:n,requestId:Qx(e)},`[save-version] handler failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),$n=J(lo,async(e,t)=>{let n=S?.current;if(!n){q(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await C?.();let t=performance.now()-e;t>1e3&&Z.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){Z.warn({err:e},`[history] pre-read commit flush failed`)}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`folder`),o=r.searchParams.get(`branch`)??T?.()??`main`;if(!i&&a===null){q(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(o.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(o)){q(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=Na(a,t,`folder`,`history`);if(!e)return;let i=Number(r.searchParams.get(`limit`)??`50`),s=Math.min(200,Number.isFinite(i)?i:50),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.max(0,Number.isFinite(c)?c:0),u=`folder\0${o}\0${e.folderRel}\0${s}\0${l}`,{promise:d,coalesced:f}=Me.run(u,()=>gpe(n,e.folderRel,ee??`.`,{branch:o,limit:s,offset:l}));f&&_Z(`folder`),Y(t,200,Zr,{...await d},{handler:`history`});return}let s=ee??`.`,c=BZ(i,s);if(`error`in c){q(t,400,`urn:ok:error:invalid-request`,c.error,{handler:`history`});return}let l=Number(r.searchParams.get(`limit`)??`50`),u=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(l)?l:50),f=Number.isFinite(u)?u:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=r.searchParams.get(`includeAutoCheckpoints`)===`true`,_=`doc\0${o}\0${i}\0${d}\0${f}\0${p??``}\0${m??``}\0${h??``}\0${g?`1`:`0`}`,v=Date.now();try{let{promise:e,coalesced:r}=Me.run(_,()=>hpe(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&_Z(`doc`);let a=await e,c=Date.now()-v;L(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),Y(t,200,Zr,{...a},{handler:`history`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function er(e,t,n){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=S?.current;if(!r){q(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,a=ee??`.`,o=BZ(i,a);if(`error`in o){q(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=ox(r),c=T?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){q(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await cq(r,i,n,c,zK(r.gitDir),e=>VZ(e,a),UK());if(e===null){q(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let o=await s.raw(`show`,`${n}:${e}`),[l=``,u=``]=(await s.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);Y(t,200,Ree,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let tr=J(Bi,async(t,n,r)=>{let i=Nk(r,oe);if(i.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=a.documents.get(r.docName);if(o&&iS(o)){sS(n,new oS({file:Rx(r.docName)}),`rollback`);return}let s=S?.current;if(!s){q(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=ee??`.`,d=BZ(c,u);if(`error`in d){q(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=ox(s),p=Date.now();try{let t=zK(s.gitDir),r=UK(),o=await cq(s,c,l,T?.()??`main`,t,e=>VZ(e,u),r);if(o===null){q(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${o}`),m=new Date().toISOString();await xx(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=a.documents.get(c);if(!h){q(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await HS(d,g),v;h.transact(()=>{Eb(h,d,g,_),v=lS(h.getText(`source`).toString(),d,`rollback`)},RZ),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":i.kind,...i.kind===`agent`||i.kind===`principal`?{"actor.writer_id":i.writerId}:{}})),IZ(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:Mk(`Restored to ${e}`),r=xn(n);y=t||!r.response?r.response:Sn(r.response),Wj(c,i.writerId,i.displayName,i.colorSeed,Ed(c,l),i.actor,r.stored),Wb(),wn(n,!t);break}case`principal`:{let e=xn(i.summary);y=e.response,Wj(c,i.writerId,i.displayName,i.colorSeed,Ed(c,l),i.actor,e.stored),wn(i.summary,!1);break}case`anonymous`:Z.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(i.kind)}`)}NZ().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await vt(c);if(b?.kind===`failure`){bt(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){xt(n,`rollback`);return}ht(c,`rollback`);let x=Date.now()-p;L(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&te?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:uS(v);Y(n,200,He,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){q(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),nr=J(lo,async(e,n)=>{try{he&&await he.catch(e=>{Z.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=E?.(),i=HL();Y(n,200,_ee,{serverInstanceId:c,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),rr=P({agents:N(P({id:I(),name:I(),version:I(),description:I().optional(),license:I().optional(),iconUrl:I().optional(),website:I().optional(),source:Ce([`registry`,`custom`]),supported:A(),featured:A(),harness:P({cli:Ce([`claude`,`codex`,`cursor`,`gemini`,`opencode`,`pi`]),availability:Ce([`present`,`not-found`,`unknown`])}).optional()})),stale:A(),maxThreads:F()}),ar=J(lo,async(e,t)=>{if(ce===void 0){q(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=Ud(),{agents:n,stale:r}=await ce.getCatalog(),i=await le?.()??[],a=await ue();Y(t,200,rr,{agents:[...n.map(t=>{let n=Ak[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:zd.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))],stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function sr(e,t){if(!kz(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=oe?.()??null;if(!n){q(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}Y(t,200,bee,n,{handler:`principal`})}async function cr(e,t){if(!kz(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=Yj.read();Y(t,200,kr,{entries:n,count:n.length,detection:ple(n[0])},{handler:`embed-detect`})}async function ur(e,t){if(!kz(e.socket.remoteAddress)){q(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){q(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=V(s),r=n,a=!0;try{r=W(n)}catch(e){let r=Us(e);if(r===`ENOENT`)Z.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{Z.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),q(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}Y(t,200,ci,{contentDir:r,pathSeparator:ql,symlinkResolved:a},{handler:`workspace`})}let fr=CX({contentDir:s,isPathIgnored:e=>de?.isPathIgnored(e)??!1,getAttachmentFolderPath:d}),gr={"missing-path":[400,`urn:ok:error:invalid-request`,`Missing asset path.`],"unsupported-type":[415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`],"not-found":[404,`urn:ok:error:asset-not-found`,`Asset not found.`],"invalid-path":[400,`urn:ok:error:invalid-request`,`Invalid asset path.`]},Sr=J(lo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),r=fr.resolveServableAsset(n);if(!r.ok){let[e,n,i]=gr[r.reason];q(t,e,n,i,{handler:`asset`,...r.cause===void 0?{}:{cause:r.cause}});return}let{asset:i}=r,a={"Content-Type":i.contentType,"Content-Length":String(i.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":i.disposition,"Cache-Control":`no-store`};i.csp!==null&&(a[`Content-Security-Policy`]=i.csp);let o=i.canonicalPath;t.writeHead(200,a);try{await ju(Ql(o),t)}catch(e){Z.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:n,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),wr=1048576,Nr=J(lo,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`),r=fr.resolveTextAsset(n);if(!r.ok){let[e,n,i]=gr[r.reason];q(t,e,n,i,{handler:`asset-text`,...r.cause===void 0?{}:{cause:r.cause}});return}if(r.size>wr){q(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${wr}-byte text-viewer cap.`,{handler:`asset-text`});return}let i=(await bu(r.canonicalPath)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(i)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Pr=J(lo,async(e,t)=>{try{if(!S?.current){Y(t,200,_a,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=V(S.current.gitDir,`rescue`);if(H(r))try{let t=iu(r).filter(e=>kx(e));for(let i of t){let t=V(r,i),a=lu(t);if(e-a.mtimeMs>864e5){try{uu(t)}catch(e){Z.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:jx(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){Z.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=T?.()??`main`,t=await Cx(S.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){Z.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}Y(t,200,_a,n,{handler:`rescue-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Fr=J(to,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!kx(r)){q(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(r.includes(`..`)||r.startsWith(`/`)||r.includes(`\0`)||r.includes(`\\`)){q(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=V(s),a=V(i,r);if(!rN(a,i)){q(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=jx(r);if(Vx(o)||Hx(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(UL(r)||ba(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let c=typeof n.template==`string`?n.template.trim():``,l=``,u;if(c.length>0){if(!/^[A-Za-z0-9_-]+$/.test(c)){q(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,a=tj(i,n),o=a.find(e=>e.name===c);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);q(t,400,`urn:ok:error:invalid-request`,`Template "${c}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let s=V(i,o.path),d;try{d=U(s,`utf-8`)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=oi(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;l=Nj(f,{date:Fj(),user:p}),u=o.scope}let d=jx(r),f=Ir.createPage({fullPath:a,docName:d,initialContent:l});if(!f.ok){q(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:f.cause});return}switch(e.kind){case`agent`:case`principal`:Wj(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}await Dt(d,l,`create-page`),O?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:c,templateScope:u,docName:d})),Y(t,200,Eo,{docName:d},{handler:`create-page`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Ir=TX({contentDir:s,resolveContentEntryPath:QZ,docNameForPath:e=>aQ(s,e),docNameToRelativePath:Rx,listManagedDocNamesUnderFolder:e=>un(e),listAffectedDocNames:(e,t,n)=>kpe(e,t,n),getFileIndex:l,getConflictedFiles:()=>new Set(j?.()?.getConflicts().map(e=>e.file)??[]),isDocNameInLifecycleConflict:e=>{let t=a.documents.get(e);return t!==void 0&&iS(t)},captureAndCloseDocuments:Bt,markRecentlyRemoved:_e?e=>_e.setDeleted(e):void 0,mutateFileIndexDelete:p?({path:e,docName:t})=>p({kind:`delete`,path:e,docName:t}):void 0,removeFolderIndexEntries:Ue,upsertFolderIndexPathSegments:Ve,deleteDerivedDocumentsBestEffort:jt,invalidateReferencedAssetsCache:Le,signalFiles:()=>O?.(`files`),nextAvailableDuplicateDocName:e=>Ppe(s,e),nextAvailableDuplicateFolderPath:e=>Fpe(s,e),resolveDuplicateDocPath:(e,t)=>Npe(s,e,t),collectMarkdownCopies:e=>Ipe(s,e),collectFolderPaths:e=>Lpe(s,e),contentFilter:de??void 0,unmarkRecentlyRemoved:_e?e=>_e.delete(e):void 0,mutateFileIndexCreate:p?({path:e,docName:t,content:n})=>p({kind:`create`,path:e,docName:t,content:n}):void 0,recordDerivedDocumentBestEffort:Dt,recordDerivedMutationsBestEffort:Et}),Lr=J(di,async(e,t,n)=>{try{if(Nk(n,oe).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!YZ(e)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(UL(e)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(de?.isDirExcluded(e)){q(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}if(!Ir.createFolder(e).ok){q(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Y(t,200,Mr,{path:e},{handler:`create-folder`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),Rr=J(zn,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:r}=n,i=n.path,a=r===`file`?jx(i):i;if(!YZ(i)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(UL(i)||r===`file`&&(Vx(a)||Hx(a))||r===`folder`&&XZ(i)){q(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&oQ(s,i);let o=await Ir.duplicatePath(r,i,a);if(!o.ok)switch(o.kind){case`not-found`:q(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return;case`type-mismatch`:q(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return;case`conflict`:sS(t,new oS({file:o.file}),`duplicate-path`);return;case`destination-excluded`:q(t,400,`urn:ok:error:invalid-request`,r===`file`?`Duplicated document destination is excluded by the project content config.`:`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return;case`already-exists`:q(t,409,`urn:ok:error:doc-already-exists`,`A ${r} at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:o.cause});return;default:throw Error(`Unhandled duplicate outcome: ${String(o.kind)}`)}let{duplicatedPath:c,duplicatedDocNames:l}=o;switch(e.kind){case`agent`:case`principal`:for(let t of l)Wj(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}O?.(`files`),Y(t,200,et,{kind:r,path:c,duplicatedDocNames:l},{handler:`duplicate-path`})}catch(e){if(e instanceof nQ){q(t,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let n=jpe(e);if(n){q(t,n.status,n.type,n.title,{handler:`duplicate-path`,cause:e});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),zr=J(ct,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:r,fromPath:i,toPath:o}=n;if(!YZ(i)||!YZ(o)){q(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(Vx(i)||Vx(o)||Hx(i)||Hx(o))){q(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(UL(i)||UL(o)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===o){Y(t,200,_n,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let c=r===`asset`&&kx(i)&&kx(o)?`file`:r;if(c===`asset`){let n;try{n=kx(i)&&!kx(o)?await hn(i,o):await mn(i,o)}catch(e){if(e instanceof oS){sS(t,e,`rename-path`);return}let{status:n,type:r,error:i}=zt(e);q(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&Le();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${o}`;r=Tn(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Z.debug({kind:`asset`,fromPath:i,toPath:o,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(NZ().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),w)try{await w()}catch(e){Z.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}Y(t,200,_n,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}c===`file`&&oQ(s,i);let l=c===`file`?[aQ(s,i)]:un(QZ(s,`folder`,i)),u=j?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of l){let n=e,r=a.documents.get(n),i=Rx(n),o=r!==void 0&&iS(r),s=d.has(i);if(o||s){sS(t,new oS({file:i}),`rename-path`);return}}if(de){let e=kx(i)?Ul(i):Ix(i);if(c===`file`?de.isExcluded(kx(o)?o:`${o}${e}`):de.isDirExcluded(o)){q(t,400,`urn:ok:error:invalid-request`,`Destination ${c===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await vn(i,o,c,f?{actor:f}:{})}catch(e){if(e instanceof GM){q(t,409,`urn:ok:error:doc-already-exists`,Lt(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){Y(t,200,_n,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&Le();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=Tn(e,`Renamed ${i} → ${o}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Od(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Z.debug({kind:r,fromPath:i,toPath:o,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),NZ().add(1,{kind:`rename-${c}`,attribution_kind:e.kind}),w)try{await w()}catch(e){Z.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}Y(t,200,_n,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=zt(e);q(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),Br=J(Oee,async(e,t,n)=>{try{yn(n);let{kind:e,path:r}=n;if(!YZ(r)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?sn(r):{path:r,ambiguous:!1};if(i.ambiguous){q(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let a=i.path,o=e===`asset`&&kx(a)?`file`:e;if(o===`file`&&oQ(s,a),UL(a)){q(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=await Ir.deletePath(o,a);if(!c.ok){c.kind===`not-found`?q(t,404,`urn:ok:error:doc-not-found`,`${o} does not exist.`,{handler:`delete-path`}):c.kind===`type-mismatch`?q(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${o}.`,{handler:`delete-path`}):sS(t,new oS({file:c.file}),`delete-path`);return}Y(t,200,vo,{deletedDocNames:c.deletedDocNames},{handler:`delete-path`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ur=J(Ni,async(e,t,n)=>Zo(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":ds(n.path),"ok.cleanup.path.role":gs(n.path)}},async()=>{try{if(Nk(n,oe).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!YZ(r)){q(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&kx(r)?`file`:e,a=jx(r);i===`file`&&oQ(s,r);let o=i===`folder`&&XZ(r);if(i===`file`&&(Vx(a)||Hx(a))||o||UL(r)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}let{deletedDocNames:c}=await Ir.trashCleanup(i,r,a,`handleTrashCleanup`);Y(t,200,rn,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`});async function Gr(e,t){if(e.method!==`POST`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await Cpe(e,M??s)}catch(e){if(e instanceof XI){q(t,ZI(e.reason),e.reason,$I(e.reason),{handler:`upload-asset`,cause:e});return}q(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:i,sha:a,byteLength:o,parentDocName:c,placement:l}=n,u=()=>{if(H(i))try{uu(i)}catch{}},d=Lk(Wt,{parentDocName:c,placement:l||void 0},t,{handler:`upload-asset`});if(!d.ok){u();return}let{parentDocName:f,placement:p}=d.value,{agentId:m,agentName:h}=yn(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(o===0){u(),q(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(f.includes(`\0`)||f.includes(`..`)||f.startsWith(`/`)){u(),q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let g=await fr.storeUpload({tempPath:i,sha:a,byteLength:o,filename:r,parentDocName:f,placement:p});if(g.ok){Z.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:h,dedup:g.deduped,mime:g.mime,size:o,destPath:g.path,httpStatus:200},g.deduped?`[upload] dedup hit`:`[upload] write ok`),Y(t,200,wt,{src:g.src,path:g.path,deduped:g.deduped},{handler:`upload-asset`});return}switch(g.kind){case`config-error`:Z.error({err:g.cause},`[upload] project config has invalid content.attachmentFolderPath`),q(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:g.cause});return;case`invalid-attachment-folder`:q(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return;case`path-escape`:q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,...g.cause===void 0?{}:{cause:g.cause}});return;case`dest-validation-error`:Z.error({err:g.cause,destDir:g.destDir},`[upload] failed to validate destination directory`),q(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:g.cause});return;case`mkdir-failed`:q(t,ZI(g.reason),g.reason,$I(g.reason),{handler:`upload-asset`,cause:g.cause,detail:`failed to create attachment directory`});return;case`write-failed`:Z.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:Qx(e),agentId:m,agentName:h,filename:g.filename,size:o,reason:g.reason,httpStatus:ZI(g.reason),err:g.cause},`[upload] write failed`),q(t,ZI(g.reason),g.reason,$I(g.reason),{handler:`upload-asset`,cause:g.cause});return}}let Kr=`/api/local-op/clone`,Jr=`/api/local-op/ok-init`,Xr=600*1e3,Qr={stdio:[`ignore`,`ignore`,`pipe`]},$r={stdio:[`ignore`,`pipe`,`pipe`]},ei={stdio:`ignore`},ti=`local-op-clone`,ri=J(Ge,ii,{handler:ti,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ti})});async function ii(e,t,n){let{url:r,dir:i,branch:a}=n;if(!FW(r)){q(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ti,cause:Error(`url=${r}`)});return}if(!zW(i)){q(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ti,cause:Error(`dir=${i}`)});return}if(!je.tryAcquire(Kr)){q(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ti,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let o=rS(t,ti),s=null,c=DG({cliArgs:re,url:r,dir:i,branch:a,timeoutMs:Xr,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&Z.warn({stderr:SF(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=QW(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(SF(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await c.done,s&&!t.writableEnded&&!t.destroyed){let e=await ai(s);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:s})}\n`):o(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?o(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):Z.error({err:e,handler:ti},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),je.release(Kr)}})(),t.on(`close`,()=>{c.cancel()})}async function ai(e,t){let n=V(IW(e)),r=oA(n),i=JI(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=re,s=e=>{let n=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...o,e,...n]},c=async e=>{let t=Rl(a,s(e),cN({...Qr,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),Z.warn({cwd:n,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let o=null,c=null,l=null;t.on(`exit`,(e,t)=>{o=e??-1,c=t??null}),t.on(`error`,t=>{l=t.message,o=-1,Z.error({cwd:n,cliCmd:e,err:t},`[local-op/clone] failed to spawn child`)}),t.unref();let u=Date.now()+45e3;for(;Date.now()<u;){await Mu(500);let t=JI(r);if(t&&t.port>0)return{port:t.port};if(o!==null){let t=Buffer.concat(i).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${l?`spawn failed: ${l}`:c?`killed by ${c}`:`code ${o}`})${t?` — ${t}`:``}`,exited:!0}}}let d=Buffer.concat(i).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${d?` — ${d}`:``}`,exited:!1}},l=Js(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=Js(r);if(e&&e.port>0){let e=await c(`ui`);return`port`in e?e:{error:`${d.error}; connect fallback failed: ${e.error}`}}}return`port`in d?d:{error:d.error}}let ui=`local-op-ok-init`,fi=J(ia,async(e,t,n)=>{let{projectPath:r}=n;if(!Wl(r)){q(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:ui,cause:Error(`projectPath=${r}`)});return}let i;try{i=W(r)}catch(e){Y(t,200,ka,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:ui});return}if(!zW(i)){q(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:ui,cause:Error(`projectPath=${r}`)});return}let a=ad(i).kind;if(a!==`directory`&&a!==`linked`){Z.warn({project:Vl(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${Vl(i)} result=not-a-git-worktree kind=${a}`),Y(t,200,ka,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:ui});return}if(uz(i)){Z.warn({project:Vl(i),result:`already-initialized`},`[ok-init] action=init project=${Vl(i)} result=already-initialized`),Y(t,200,ka,{ok:!0,projectPath:i},{handler:ui});return}if(!je.tryAcquire(Jr)){q(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:ui,extraHeaders:{"Retry-After":`2`}});return}try{await Ps(async()=>{MU(i)}),Z.warn({project:Vl(i),result:`success`},`[ok-init] action=init project=${Vl(i)} result=success`),Y(t,200,ka,{ok:!0,projectPath:i},{handler:ui})}catch(e){let n=e instanceof Error?e.message:String(e);Z.warn({project:Vl(i),result:`failed`,reason:n},`[ok-init] action=init project=${Vl(i)} result=failed reason=${n}`),Y(t,200,ka,{ok:!1,reason:`init-failed`,message:n},{handler:ui})}finally{je.release(Jr)}},{handler:ui,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ui})}),pi=`/api/local-op/auth/login`,mi=`/api/local-op/auth/status`,yi=`/api/local-op/auth/repos`,bi=`/api/local-op/auth/signout`,xi=`/api/local-op/auth/pat`,Si=`/api/local-op/auth/gh-login`,Ci=ie??15e3,Di=960*1e3,Oi=()=>fF(M??s),ki={current:null},Ai={current:null};function ji(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!je.tryAcquire(r)){let e=i.current;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-flow-slot-no-controller`,channel:`auth`,transport:`http`,handler:n})),q(t,429,`urn:ok:error:concurrent-operation`,a,{handler:n,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),i.current=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`,handler:n}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let c=rS(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},Ci);u.unref();let d=()=>{u!==null&&(clearInterval(u),u=null)},f=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}xpe(e,j),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,je.release(r))})}let Pi=`local-op-auth-login`,Ii=J(Vt,Li,{handler:Pi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Pi})});async function Li(e,t,n){let r=n.host??Oi();ji({res:t,handler:Pi,guardKey:pi,inFlight:ki,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>KW({cliArgs:re,host:r,timeoutMs:Di,onEvent:e})})}let zi=`local-op-auth-gh-login`,Vi=J(Vt,async(e,t,n)=>{let r=n.host??Oi(),i=await FG();if(i===null){q(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:zi});return}ji({res:t,handler:zi,guardKey:Si,inFlight:Ai,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>RG({host:r,ghPath:i,timeoutMs:Di,onEvent:e})})},{handler:zi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:zi})}),Ji=`local-op-auth-cancel`,Yi=J(cee,Wz(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:Ai,guardKey:Si}:{inFlight:ki,guardKey:pi},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,je.release(r.guardKey)),Y(t,200,Ta,{},{handler:Ji})},{handler:Ji,title:`Failed to cancel the sign-in.`}),{handler:Ji,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ji})}),Qi=`local-op-auth-status`,ea=J(Vt,async(e,t,n)=>{let r=n.host??Oi();if(!je.tryAcquire(mi)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Qi,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=re,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=Rl(e,i,cN({...$r,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,r.kill(`SIGTERM`)},3e4),s=[];r.stdout.on(`data`,e=>s.push(e)),r.on(`close`,()=>{if(clearTimeout(o),a){n(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(s).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
1215
1215
  `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await FG()!==null;o===null?Y(t,200,En,{authenticated:!1,ghAvailable:s},{handler:Qi}):Y(t,200,En,{...o,ghAvailable:s},{handler:Qi})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Qi,cause:e})}finally{je.release(mi)}},{handler:Qi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Qi})}),ta=`local-op-auth-pat`,na=J(yr,async(e,t,n)=>{let r=n.host??Oi();if(!je.tryAcquire(xi)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:ta,extraHeaders:{"Retry-After":`5`}});return}try{let e=await qW({cliArgs:re,host:r,token:n.token});e.ok?(LZ(j),Y(t,200,pr,{host:e.host,login:e.login},{handler:ta})):q(t,400,`urn:ok:error:auth-failed`,e.error,{handler:ta})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:ta,cause:e})}finally{je.release(xi)}},{handler:ta,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ta})}),ca=`local-op-auth-repos`,la=J(Vt,ua,{handler:ca,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ca})});async function ua(e,t,n){let r=n.host??Oi();if(!je.tryAcquire(yi)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:ca,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=rS(t,ca),[a,...o]=re,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=Rl(a,s,cN({...$r,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},Xr);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1216
1216
  `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Z.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(),je.release(yi))}),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()),je.release(yi))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),je.release(yi))})}let da=`local-op-auth-signout`,fa=J(Vt,async(e,t,n)=>{let r=n.host??Oi();if(!je.tryAcquire(bi)){q(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:da,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=re,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=Rl(e,i,cN({...ei,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),Y(t,200,Ta,{},{handler:da})}catch(e){q(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:da,cause:e})}finally{je.release(bi)}},{handler:da,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:da})}),pa=`/api/local-op/auth/set-identity`,ma=`local-op-auth-set-identity`,ha=J(Tr,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!M){q(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ma});return}if(!je.tryAcquire(pa)){q(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ma,extraHeaders:{"Retry-After":`5`}});return}try{Oz(M,r,i),j?.()?.refreshIdentity().catch(()=>{}),Y(t,200,Ta,{},{handler:ma})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ma,cause:e})}finally{je.release(pa)}},{handler:ma,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ma})});async function ga(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=j?.();if(!e){Y(t,200,ya,{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(),Y(t,200,ya,e.getStatus(),{handler:`sync-status`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let va=J($i,async(e,t,n)=>{let r=j?.();if(!r){q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;Y(t,202,vi,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?j?.()?!0:(q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function xa(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=j?.();Y(t,200,tte,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Sa=J(Mee,async(e,t,n)=>{let r=j?.();if(!r){q(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),Y(t,200,Bee,{},{handler:`sync-resolve-conflict`})}catch(e){q(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:(q(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Ca(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!M){q(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){q(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=jx(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=j?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){q(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=Ns({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),o=jx(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=ve?ve(o):null;t!==null&&(c=t,l=!0)}else{WI(z(M,i),M);try{c=U(z(M,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;Y(t,200,qi,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=jx(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=ve?ve(e):null;t!==null&&!Spe(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Z.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}Y(t,200,qi,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function wa(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){q(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=Iq(a);if(a!==null&&a!==``&&o===void 0){q(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{Y(t,200,Aee,{plan:await Qq({projectDir:s,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof wq){q(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof Tq){q(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}q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Ea=J(Tee,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){q(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=Iq(a);if(typeof a==`string`&&a.length>0&&o===void 0){q(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{Y(t,200,Uee,{result:await qq(i,{projectDir:s,packId:o})},{handler:`seed-apply`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function Da(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}Y(t,200,Zee,{packs:Rq()},{handler:`seed-packs`})}}let Oa=J(Yee,async(e,t,n)=>{if(n.out!==void 0&&!zW(n.out)){q(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{Y(t,200,Ei,await rI({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Ma(e,t){if(r(e,t,{handler:`installed-agents`}))try{await Sue(e,t,Je.probeAll)}catch(n){t.headersSent||(Z.error({err:n,requestId:Qx(e)},`[installed-agents] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Na(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return q(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=V(s),o=i===``?a:V(a,i);return o!==a&&!o.startsWith(`${a}${ql}`)?(q(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function Pa(e,t,n=`template`){return!e||!Yn.test(e)?(q(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Fa(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:V(e,i);if(a!==e&&!a.startsWith(`${e}${ql}`))continue;let o=V(a,`.ok`,`templates`,`${n}.md`);if(H(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ia(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 Ra=bU({GET:J(lo,async(e,t)=>{try{let n=Na(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await pj(n.folderRel,{projectDir:n.resolvedContentDir}),i=V(V(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(H(i))try{let e=(0,Dk.parse)(await bu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Z.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}Y(t,200,br,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){q(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:J(mr,async(e,t,n)=>{try{if(De){q(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Na(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=Hce({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;q(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`&&(On(e,Dn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await jn(`folder-config-put`))}Y(t,200,Er,{applied:i},{handler:`folder-config-put`})}catch(e){q(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 za(e,t,n){let r=a.documents.get(e);return r&&iS(r)?(sS(n,new oS({file:`${e}.md`}),t),!0):!1}function Ba(e,t,n){let r=a.documents.get(e);return r&&iS(r)?(sS(n,new oS({file:`${e}.md`}),t),!0):!1}let Ha=J(lo,Wz(async(e,t)=>{let n=await Sce(V(s));Y(t,200,Iee,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),Ua=e=>{let{body:t}=eo(e);return{frontmatter:Rt(e)??{},body:t}},Wa=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Pa(r,t,`template-get`))return;let i=Na(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Fa(o,a,r);if(!s){q(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=Dr(await bu(c,`utf-8`)),f=d.identity,p=d.starterContent;Y(t,200,qee,{template:{name:r,folder:l,scope:u,path:B(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ga=J(hee,async(e,t,n)=>{try{if(De){q(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Pa(r,t,`template-put`))return;let i=Na(n.folder,t,`folder`,`template-put`);if(!i||za(Ro(i.folderRel,r),`template-put`,t))return;let a=Lj({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Ia(n.frontmatter)});if(!a.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let s=V(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!H(s),l=B(i.resolvedContentDir,s).split(/[\\/]/).filter(Boolean).join(`/`),u=Ro(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=yn(n),h=await o.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Tb(h.dc.document,a.content,`agent`)},h.origin);let g=await vt(u);if(g?.kind===`failure`){bt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){xt(t,`template-put`);return}Nt(u,a.content),On(e,Dn(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await jn(`template-put`),Y(t,200,Ne,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ja=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Pa(r,t,`template-delete`))return;let i=Na(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=po(n,oe);if(a.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(za(Ro(i.folderRel,r),`template-delete`,t))return;await Bt([Ro(i.folderRel,r)],`deleted-upstream`);let o=$ce({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;q(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&&(On(a,Dn(`template`,i.folderRel,r),`template-delete: ${o.path}`),await jn(`template-delete`),_e?.setDeleted(Ro(i.folderRel,r))),Y(t,200,Kt,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ya=bU({GET:Wa,PUT:Ga,POST:J(dr,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Pa(n.fromName,t,`template-move`)||!Pa(n.toName,t,`template-move`))return;let r=Na(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Na(n.toFolder,t,`folder`,`template-move`);if(!i||za(Ro(r.folderRel,n.fromName),`template-move`,t))return;await Bt([Ro(r.folderRel,n.fromName)],`renamed`);let a=await ele({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await pQ(M,e,t);return n||fQ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Fa(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){q(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}q(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`){q(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;q(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}_e?.setDeleted(Ro(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=oi(U(V(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=Qce({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ia(n.frontmatter)});t.ok||(o=t.error)}}try{Nt(Ro(i.folderRel,n.toName),U(V(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(On(e,Dn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await jn(`template-move`),O?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;q(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}Y(t,200,Cr,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ja},{handler:`template`}),Xa=J(see,async(e,t,n)=>{try{if(De){q(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!hQ(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=ut(r);if(Vx(i)||Hx(i)){q(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let c=QZ(s,`file`,i);if(!H(c)){q(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let l=a.documents.get(i);if(n.deleteSource){let e=j?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=l!==void 0&&iS(l),a=n.has(r);if(i||a){sS(t,new oS({file:r}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){q(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}=$Z(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Pa(d,t,`template-import`))return;let f=Na(n.targetFolder,t,`folder`,`template-import`);if(!f||za(Ro(f.folderRel,d),`template-import`,t))return;let{frontmatter:m,body:h}=eo(u),g=To(m),_={};try{g.trim()&&(_=(0,Dk.parse)(g))}catch{}let v=n.title||_?.title||YA(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,Dk.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${h}`:h;let C=Lj({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){q(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=V(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!H(w),E=B(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ee=Ro(f.folderRel,d),{agentId:D,agentName:te,colorSeed:k,clientName:A}=yn(n),ne=await o.getSession(ee,D,{displayName:te,colorSeed:k,clientName:A});ne.dc.document.transact(()=>{Tb(ne.dc.document,C.content,`agent`)},ne.origin);let re=await vt(ee);if(re?.kind===`failure`){bt(t,re.failure,`template-import`);return}if(re?.kind===`divergence`){xt(t,`template-import`);return}Nt(ee,C.content),On(e,Dn(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await Bt([i],`deleted-upstream`),_e&&_e.setDeleted(i),is(c),p?.({kind:`delete`,path:c,docName:i})),await jn(`template-import`),O?.(`files`),Y(t,200,_r,{path:E,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Qa(e,t,n){return!e||e.length>64||!Ie.test(e)?(q(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function ro(e,t,n){let r=pee.safeParse(e??`project`);return r.success?r.data:(q(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let ao=se??pu(),oo=iZ({contentDir:s,skillsHome:ao});function uo(e){return V(e===`global`?ao:s,`.ok`,`skills`)}function fo(e,t,n){let r=V(uo(e),t);if(e===`global`){if(n!==void 0){let e=VI(ao).find(e=>e.name===t&&e.hosts.includes(n));return e?V(ao,e.dir):null}let e=HI(ao,t);return e===null?H(z(r,`SKILL.md`))?r:null:e}let i=BI(s).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?V(s,i.dir):n===void 0&&H(z(r,`SKILL.md`))?r:null}function po(e,t){let n=e.searchParams;return Nk({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 ho(e,t){let n=e===`project`?M:ao;if(!n)return`symlink`;try{return bs(z(n,...PD)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function go(e){let t=e===`project`?M:ao;return t?z(t,...PD):null}function _o(e,t,n,r={}){let i=go(e);return i?hq(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 bo(e,t,n){let r=go(e),i=go(t);if(!r||!i)return!1;let a=pq(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await hq(i,e=>({...e,skills:{...e.skills,[n]:o}})),await hq(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function xo(e,t,n){let r=go(e);return r?hq(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Co(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];q(e,r,i,t.error,{handler:n,detail:t.code})}function Do(e,t,n){let r=e===`project`?M:ao;return(r?QX(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Oo(e){let t=fo(`project`,e);return t?B(s,t).split(ql).join(`/`):`${La}/${e}`}let ko=wF.project;function No(e,t,n){let r=[],i=null,a=[...vr.map(e=>({id:e,root:qt[e]??``})),{id:`agents`,root:`.agents/skills`}];for(let{id:o,root:s}of a){if(!s)continue;let a=V(e,...s.split(`/`),t);H(V(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=V(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:B(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function Po(e){let t=WO(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 Fo(e,t){if(!EF(t))return null;let n=No(e,t);if(!n)return null;let r=XD(n.dir)?.contentHash??``,i;try{i=lu(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:co,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function Io(e,t,n){let r=No(e,t);if(!r)return null;let i;try{let{frontmatter:e}=Ua(U(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=Fo(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:Po(a)}:{}}}function Lo(e,t,n){return EF(e)?(q(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 Ro(e,t){return yo(e,t)}function zo(e){return e===`navigation`||e===`relevance`?e:void 0}function Bo(e,t){return B(t===`global`?ao:s,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Vo(e){return e===`global`?ao:M}async function Ho(e,t,n){let r=await LN(e,t);if(!H(V(uo(n),t,`SKILL.md`))){let i=(n===`project`?BI(s):VI(ao)).find(e=>e.name===t);if(i){let a=n===`project`?s:ao,o=V(a,i.dir),c=V(a,`.agents`,`skills`),l=z(c,t);if(H(c)&&!H(z(l,`SKILL.md`))){let e=!1;try{e=W(o)===W(l)}catch{e=!1}e||fs(o,l,{recursive:!0,dereference:!0})}return bI({canonicalAbs:H(z(l,`SKILL.md`))?l:o,canonicalHash:i.contentHash,name:t,cwd:e,targets:[...vr],roots:lI(n)}),r!==null}}return xI(t,e,vr,lI(n)),r!==null}function Uo(e,t){let n=[];if(!H(e))return{skills:n,truncated:!1};let r;try{r=iu(e,{withFileTypes:!0})}catch(r){return L(`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()||!Ie.test(a.name))continue;if(n.length>=500){i=!0;break}let r=V(e,a.name,`SKILL.md`);if(!H(r))continue;let o;try{let{frontmatter:e}=Ua(U(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Bo(r,t),absolutePath:r})}return{skills:n,truncated:i}}let Wo=J(lo,Wz(async(e,t)=>{let n=uo(`project`),r=Uo(n,`project`),i=Uo(uo(`global`),`global`),a=[...vr],o=nI(ao).map(e=>e.editorId),c=M?PN(M).skills:{},l=PN(ao).skills,u=M?RD(H(z(M,...PD))?U(z(M,...PD),`utf-8`):``)??null:null,d=Po,f=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?u?.skills[e.name]:void 0,o=a?d(a):void 0,s=a?.localHash!==void 0&&xs(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=M?$X(M):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=V(e,i.path);if(n!==void 0&&t===V(n))continue;let a=!1;try{a=eu(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(W(t)===W(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=M?MI(s,`project`):{},g=II(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=FI(`project`),y=FI(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=M?BI(s).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??Fo(s,e.name):void 0,r=n?d(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:V(s,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(M,b(t?p[e.name]:void 0,g),V(s,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...Do(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...EF(e.name)?{managed:!0}:{}}}):[],C=$X(ao),w=bs(z(ao,...PD)),T=MI(ao,`global`),E=II(T,`global`),ee=new Set(VI(ao).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let D=new Set,O=VI(ao).map(e=>{let t=!D.has(e.name);D.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:V(ao,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(ao,b(n,E),V(ao,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,E).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...Do(`global`,e.name,e)===`link`?{linkMode:!0}:{},...EF(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??Fo(ao,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),te=new Set(S.map(e=>e.name)),k=M&&!r.skills.some(e=>e.name===ko)&&!te.has(ko)?Io(M,ko,`project`):null,A=new Set(O.map(e=>e.name)),ne=kF.map(e=>wF[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!A.has(e)).map(e=>Io(ao,e,`global`)).filter(e=>e!==null),j=new Set(S.map(e=>e.name));Y(t,200,ree,{skills:[...f(r,c,!0).filter(e=>!j.has(e.name)),...S,...f(i,l,!1),...O,...k?[k]:[],...ne],truncated:r.truncated||i.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Go=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Qa(r,t,`skill-get`))return;let i=ro(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(EF(r)){let e=i===`global`?ao:M,a=e?No(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=Ua(await bu(a.skillMd,`utf-8`));Y(t,200,_i,{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:CI(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=fo(i,r,a);if(o===null){q(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=V(o,`SKILL.md`),{frontmatter:c,body:l}=Ua(await bu(s,`utf-8`));Y(t,200,_i,{skill:{name:r,scope:i,path:Bo(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:CI(o)}},{handler:`skill-get`})}catch(e){q(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 qo(e,t){if(!(!D||qx(e))){if(de)try{await de.rebuildIgnorePatterns()}catch{}await Dt(e,t,`skill-put`)}}let Jo=J(pt,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Qa(n.name,t,`skill-put`)||Lo(n.name,t,`skill-put`))return;let r=bj({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?s:ao,a=fo(n.scope,n.name);if(a===null){let a=LI(i,n.scope),o=xj({skillsRoot:V(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){q(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`&&(On(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await jn(`skill-put`)),await qo(n.scope===`project`?`${a}/${n.name}/SKILL`:Hr(`global`,n.name),r.content),O?.(`files`),Y(t,200,ot,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let c=B(i,a).split(ql).join(`/`),l=`${c}/SKILL.md`,u=n.scope===`project`?`${c}/SKILL`:Hr(n.scope,n.name);if(Ba(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=yn(n),h=await o.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Tb(h.dc.document,r.content,`agent`)},h.origin);let g=await vt(u);if(g?.kind===`failure`){bt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){xt(t,`skill-put`);return}n.scope===`project`&&(On(e,Dn(`skill`,``,n.name),`skill-edit: ${l}`),await jn(`skill-put`)),await qo(u,r.content),O?.(`files`),Y(t,200,ot,{path:l,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function Yo(e,t){let n=e===`project`?s:ao,r=fo(e,t);return{root:r===null?uo(e):R(r),dirRel:r===null?`.ok/skills/${t}`:B(n,r).split(ql).join(`/`),realDir:r}}function Xo(e,t){let n=e===`project`?s:ao,r=(e===`project`?BI(s):VI(ao)).find(e=>e.name===t);r&&bI({canonicalAbs:V(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>sa(e)),roots:lI(e)})}let Qo=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Qa(r,t,`skill-delete`))return;let i=ro(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=Yo(i,r),s=po(n,oe);if(s.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Bt(i===`project`?[...new Set([`${o}/SKILL`,Hr(i,r)])]:[Hr(i,r)],`deleted-upstream`),Xo(i,r);let c=Ej({skillsRoot:a,name:r}),l=uo(i);if(c.ok&&l!==a&&H(V(l,r,`SKILL.md`))){let e=Ej({skillsRoot:l,name:r});e.ok||Z.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;q(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(On(s,o,`skill-delete: ${o}`),await jn(`skill-delete`)),O?.(`files`));let u=Vo(i);u&&await Ho(u,r,i),Y(t,200,Jee,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),$o=J(Ln,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Qa(n.fromName,t,`skill-move`)||!Qa(n.toName,t,`skill-move`)||Lo(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=Yo(n.scope,n.fromName);if(fo(n.scope,n.toName)!==null){q(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=Vo(n.scope),o=a?PN(a).skills[n.fromName]:void 0,c=n.scope===`project`?s:ao,l=(n.scope===`project`?BI(s):VI(ao)).find(e=>e.name===n.fromName),u=l?R(l.dir):null,d=u===null?[]:Object.entries(MI(c,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?aI(o.hosts):[],...l?aI(l.hosts):[],...aI(d)])];await Bt(n.scope===`project`?[...new Set([`${i}/SKILL`,Hr(n.scope,n.fromName)])]:[Hr(n.scope,n.fromName)],`renamed`),Xo(n.scope,n.fromName);let p=await Kce({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await pQ(M,e,t);return n||fQ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){q(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;q(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=V(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=Ua(U(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=xj({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=Wfe({base:n.scope===`project`?s:ao,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){L(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await de?.rebuildIgnorePatterns(),await us(r,n.fromName,n.toName),await ms(x,n.toName)}catch(e){L(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=Bo(V(r,n.fromName),n.scope),C=Bo(V(r,n.toName),n.scope);n.scope===`project`&&(On(e,Dn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await jn(`skill-move`));let w=xs(r,n.toName),T=n.scope===`project`?await Ss(Cs(e),C):void 0;if(await _o(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await LN(a,n.fromName),xI(n.fromName,a,f,lI(n.scope));let e=V(r,n.toName);if(f.length>0){let t=mI(e,n.toName,a,f,ho(n.scope,n.toName),lI(n.scope));await IN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??sI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(O?.(`files`),m){let e=m.code===`WRITE_ERROR`;q(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}Y(t,200,gee,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),es=J(Hee,async(e,t,n)=>{let{name:r,home:i}=n;if(!Qa(r,t,`skill-edit-external`))return;let a;try{a=W(i)}catch{q(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!lu(a).isDirectory()||!H(V(a,`SKILL.md`))){q(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}yR(r,a),Y(t,200,Xee,{docName:Vee(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),ts=J($e,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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(!Qa(r,t,`skill-move-scope`))return;if(i===a){q(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!M){q(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:c,realDir:l}=Yo(i,r),u=V(o,r),d=(()=>{try{return W(u)}catch{return u}})(),f=a===`project`?s:ao,p=V(f,LI(f,a)),m=V(p,r);if(l===null||!H(u)){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(V(l)===V(m)||H(m)&&W(l)===W(m)){q(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(fo(a,r)!==null||H(m)){q(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let h=Vo(i),g=Vo(a),_=h?PN(h).skills[r]:void 0,v=i===`project`?s:ao,y=(i===`project`?BI(s):VI(ao)).find(e=>e.name===r),b=y?R(y.dir):null,x=b===null?[]:Object.entries(MI(v,i)).filter(([,e])=>e===b).map(([e])=>e),S=[...new Set([..._?aI(_.hosts):[],...y?aI(y.hosts):[],...aI(x)])];await Bt([...new Set([...i===`project`?[`${c}/SKILL`]:[],Hr(i,r),Hr(a,r)])],`renamed`),ls(p,{recursive:!0}),fs(d,m,{recursive:!0,dereference:!0}),Xo(i,r);let C=Ej({skillsRoot:o,name:r});if(C.ok&&d!==u){let e=B((()=>{try{return W(v)}catch{return v}})(),d);e!==``&&!e.startsWith(`..`)&&!Wl(e)&&ps(d,{recursive:!0,force:!0})}if(!C.ok){Ej({skillsRoot:p,name:r}),q(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:C.error.code,cause:Error(C.error.message)});return}let w=await bo(i,a,r);if(h&&await Ho(h,r,i),g&&S.length>0){let e=mI(m,r,g,S,ho(a,n.name),lI(a));await IN(g,r,{..._,scope:a,hosts:e,scripts:_?.scripts??sI(m,r).hasScripts,installedAt:_?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(On(e,i===`project`?c:B(s,m).split(ql).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await jn(`skill-move-scope`)),w){let t=xs(p,r),n=a===`project`?await Ss(Cs(e),B(s,m).split(ql).join(`/`)):void 0;await xo(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!H(z(m,`SKILL.md`))){q(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:B(f,m).split(ql).join(`/`)});return}O?.(`files`),Y(t,200,so,{scope:a,path:B(f,m).split(ql).join(`/`)},{handler:`skill-move-scope`})}catch(e){q(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`}),ns=J(wi,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!Qa(n.name,t,`skill-duplicate`)||!Qa(n.toName,t,`skill-duplicate`)||Lo(n.toName,t,`skill-duplicate`))return;let r=fo(n.scope,n.name);if(r===null||!H(z(r,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?s:ao,a=V(i,LI(i,n.scope)),o=V(a,n.toName);if(fo(n.scope,n.toName)!==null||H(o)){q(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let c=XD(r);if(!c){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}ls(a,{recursive:!0}),fs(r,o,{recursive:!0,dereference:!0});let{fenced:l,body:u}=lt(c.skillMd),d=gt(l,{name:n.toName});if(!d.ok){Ej({skillsRoot:a,name:n.toName}),q(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:d.error.kind});return}try{vs(z(o,`SKILL.md`),`${d.nextFenced}${u}`)}catch(e){throw Ej({skillsRoot:a,name:n.toName}),e}if(n.scope===`project`){let t=B(s,o).split(ql).join(`/`);On(e,Dn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await jn(`skill-duplicate`)}O?.(`files`),Y(t,200,Cee,{name:n.toName},{handler:`skill-duplicate`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),rs=bU({GET:Go,PUT:Jo,POST:$o,DELETE:Qo},{handler:`skill`});function as(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 os(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function ss(e,t){let n=t.replace(/\.md$/i,``);return`${no(e).replace(/\/SKILL$/,``)}/${n}`}function cs(e,t){let n=V(e,t,`references`);if(!H(n))return[];let r=[],i=(e,t)=>{for(let n of iu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(V(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function us(e,t,n){if(!D){L(`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=U(n,`utf-8`)}catch(i){L(`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=B(s,e).split(ql).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),V(e,n,`SKILL.md`));for(let r of cs(e,n))i(o(t,r),o(n,r),V(e,n,r));await D.recordDirectMutations(r)}async function ms(e,t){if(!D||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 D.recordDirectMutations(n)}let hs=bU({GET:J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Qa(r,t,`skill-file-get`))return;let i=ro(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=EF(r)?i===`global`?ao:M:void 0,s=n.searchParams.get(`host`)??void 0,c=o?No(o,r,s):null;if(a===``||a.includes(`\0`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:as(a))??`reference`,u=s,d=o?c?.dir??null:fo(i,r,u);if(d===null&&u!==void 0){q(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??V(uo(i),r),p=V(f,a);if(p!==f&&!p.startsWith(`${f}${ql}`)){q(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(!H(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?ni.map(t=>`${e[1]}${t}`).find(e=>e!==a&&H(V(f,e))):void 0;if(n===void 0){q(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=V(f,n)}let g=await bu(m);if(g.includes(0)){q(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}Y(t,200,Gi,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){q(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:J(ete,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Qa(n.name,t,`skill-file-put`)||Lo(n.name,t,`skill-file-put`))return;let r=as(n.path);if(r===null){q(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){q(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=fo(n.scope,n.name);if(i===null||!H(z(i,`SKILL.md`))){q(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=B(n.scope===`project`?s:ao,i).split(ql).join(`/`),c=n.path.replace(/\\/g,`/`),l=os(n.scope,r,c),u;if(l){let e=`${a}/${c.replace(/\.mdx?$/i,``)}`;if(Ba(e,`skill-file-put`,t))return;if(u=!H(V(i,c)),u&&Cj(i)>=50){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:s,colorSeed:l,clientName:d}=yn(n),f=await o.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Tb(f.dc.document,n.content,`agent`)},f.origin);let p=await vt(e);if(p?.kind===`failure`){bt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){xt(t,`skill-file-put`);return}}else{let e=wj({skillsRoot:R(i),name:n.name,relPath:c,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;q(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`&&(On(e,Dn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${c}`),await jn(`skill-file-put`)),O?.(`files`),Y(t,200,jee,{path:c,created:u,kind:r,content:l},{handler:`skill-file-put`})}catch(e){q(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:J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!Qa(i,t,`skill-file-delete`)||Lo(i,t,`skill-file-delete`))return;let a=ro(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),c=as(o);if(c===null){q(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=po(n,oe);if(l.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=fo(a,i),d=u===null?uo(a):R(u);if(H(V(u??z(d,i),o))&&os(a,c,o)){let e=o.replace(/\.md$/i,``);await Bt([u===null?ss(i,o):`${B(s,u).split(ql).join(`/`)}/${e}`],`deleted-upstream`)}let f=Tj({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;q(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(On(l,Dn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${B(s,u).split(ql).join(`/`)}/${o}`}`),await jn(`skill-file-delete`)),f.existed&&O?.(`files`),Y(t,200,kee,{path:o,existed:f.existed,kind:c},{handler:`skill-file-delete`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),_s=J(zee,async(e,t,n)=>{try{if(!Qa(n.name,t,`skill-file-rename`)||Lo(n.name,t,`skill-file-rename`))return;let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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=as(r),o=as(i);if(a===null||o===null){q(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let c=fo(n.scope,n.name);if(c===null){q(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let l=R(c),u=os(n.scope,a,r),d=os(n.scope,o,i),f=B(s,c).split(ql).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Ba(p,`skill-file-rename`,t))return;p!==null&&await Bt([p],`deleted-upstream`);let h=Gce({skillsRoot:l,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;q(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(D){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:U(V(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:U(V(l,n.name,i),`utf-8`)})}catch{}await Et(e,`skill-file-rename`)}n.scope===`project`&&(On(e,Dn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await jn(`skill-file-rename`)),O?.(`files`),Y(t,200,Gee,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){Z.error({err:e},`[skill-file-rename] failed`),t.headersSent||q(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function ys(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let bs=pq;function xs(e,t){return XD(V(e,t))?.contentHash}async function Ss(e,t){let n=S?.current;if(!(!n||!e))try{let r=ox(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1217
- `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await jn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Cs=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function ws(e){try{let t=Vo(e.scope);if(!t)return;let n=cI(t);if(n.length===0)return;let r=mI(V(e.skillsRoot,e.name),e.name,t,n,`copy`,lI(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){Z.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Ts(e,t){if(t.ok){Y(e,200,Ar,t.body,{handler:`skill-import`});return}q(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 Es=BX({contentDir:s,skillsHome:ao,...M===void 0?{}:{projectDir:M},resolveSkillDirForRead:fo,parseFrontmatterDoc:Ua,attributeOkArtifactWrite:On,commitOkArtifactWrite:jn,shadowHeadSha:Ss,artifactWriterId:Cs,effectiveInstallMode:Do,signalFiles:()=>O?.(`files`)}),Ds=J(li,async(e,t,n)=>{let r=()=>{};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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 oO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??jD(d);if(!p){q(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(cZ(t,p,`skill-import`))return;let m=await ND(p);r=m.cleanup,s=m.ref;let h=ZD(m.dir);if(h.length===0){q(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=>JD(e.dir)?.name===f)??h.find(e=>e.name===mt[f]);if(!e){q(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){q(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??ys(d)}catch(e){if(e instanceof gD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Es.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||gn(u))&&$F({source:u,skills:[d.body.name]},RF()),Ts(t,d)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Os=J(qe,async(e,t,n)=>{let r=()=>{};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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 oO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??jD(d);if(!f){q(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(cZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??ys(d),f.kind===`well-known`)a=f,o=await ED(f.origin);else{let e=await ND(f);r=e.cleanup,c=e.ref,s=ZD(e.dir)}}catch(e){if(e instanceof gD){q(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){q(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 ND({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof gD?`not-found`:`failed`,warnings:[],...e instanceof gD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>XD(e.dir)?.name===t)??s.find(e=>e.name===mt[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Es.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){L(`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){L(`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||gn(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&$F({source:u,skills:e},RF())}Y(t,200,See,{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){q(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`}),ks=8*1024*1024,As=32*1024*1024;function js(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=V(e,n);return r!==e&&!r.startsWith(e+ql)?null:r}function Ms(e){return new Promise((t,n)=>{let r;try{r=(0,Ok.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:ks}})}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>As){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 Fs(e,t){return new Promise((n,r)=>{(0,kk.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=js(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>ks){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>As){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(R(n),{recursive:!0}),vs(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 Is(e,t){let n=nu(z(gu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){q(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=ro(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=Nk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},oe);if(o.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Ms(e)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){q(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 Fs(c.data,n)}catch(e){q(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=js(n,e.relPath);if(!r){q(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(R(r),{recursive:!0}),vs(r,e.data)}let u=ZD(n);if(u.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){q(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];Ts(t,await Es.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Ls=J($a,async(e,t,n)=>{try{let e=uo(n.scope);if(!Qa(n.name,t,`skill-install`))return;if(n.scope===`project`&&!M){q(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=Vo(n.scope),i=V(e,n.name),a=n.scope===`project`?s:ao,o=(n.scope===`project`?BI(s):VI(ao)).find(e=>e.name===n.name),c=o?V(a,o.dir):i;if(!H(c)){q(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 vt(n.scope===`project`?`${B(a,c).split(ql).join(`/`)}/SKILL`:Hr(n.scope,n.name));let l=sI(c,n.name);if(!l.ok){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){q(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=oo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:q(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:q(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:q(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`:q(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o.hosts.filter(sa),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){q(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 oo.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`?q(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`}):q(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(sa),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await oo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:u});if(!e.ok){q(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}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?M:ao;if(!e){q(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 Zn.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?q(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):q(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||O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?M:ao;if(!e){q(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 Zn.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:q(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:q(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:q(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`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){q(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:ao,s=await Zn.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:c,canonicalHash:o.contentHash});if(!s.ok)switch(s.kind){case`invalid-location`:q(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:q(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`:q(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`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?vr.filter(e=>f?.some(t=>t===e)):[...vr]:f===void 0?cI(r):vr.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?M:ao,s=d===void 0?Do(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await oo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?q(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}):q(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}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await oo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:s,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=aI(PN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&xI(n.name,r,v,lI(n.scope));let y=z(r,...PD),b=H(y)?U(y,`utf-8`):null,x=b===null?null:RD(b);b!==null&&x===null&&Z.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=mI(c,n.name,r,h,C,lI(n.scope));w.length===0?await LN(r,n.name):await IN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Rs=J(An,async(e,t,n)=>{try{if(!Qa(n.name,t,`skill-uninstall`))return;let e=Vo(n.scope);if(!e){q(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 Ho(e,n.name,n.scope);O?.(`files`),Y(t,200,Mo,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),zs=bU({GET:J(lo,async(e,t)=>{try{let e=cI(M??``),n=(e,t)=>{let n=XX(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Y(t,200,yt,{targets:e,configured:!1,folders:[...M?VX(s,PI(s,`project`)).map(e=>({...e,scope:`project`,...n(s,e)})):[],...VX(ao,PI(ao,`global`)).map(e=>({...e,scope:`global`,...n(ao,e)}))]},{handler:`skill-targets-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(aee,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?s:ao;if(e.scope===`project`&&!M){q(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await ZX(r,i.join(`/`)),O?.(`files`),Y(t,200,Zt,{targets:cI(M??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(PI(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){q(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?GX({base:r,folderRel:e.root,targetRootRel:a}):KX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){q(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await YX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),O?.(`files`),Y(t,200,Zt,{targets:cI(M??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Bs=J(Be,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Qa(n.name,t,`skill-restore`)||Lo(n.name,t,`skill-restore`))return;if(n.scope===`global`){q(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=S?.current;if(!r){q(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 uZ({shadow:r,contentDir:s,contentRoot:ee??`.`,name:n.name,version:n.version,skillDirRel:Oo(n.name)});if(!i.ok){Co(t,i,`skill-restore`);return}let a=[],o=sI(V(s,Oo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),On(e,Dn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await jn(`skill-restore`),O?.(`files`),Y(t,200,Mi,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Vs=J(dee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Qa(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?ao:s,{root:a,dirRel:o,realDir:c}=Yo(n.scope,n.name),l=!o.startsWith(`${La}/`);if(c===null||!H(V(i,o,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=z(n.scope===`global`?ao:M,...PD),d=bs(u).skills[n.name];if(!d){let e=VD(n.name,XD(V(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:_pe(V(a,n.name))})??Fo(i,n.name);e&&(d=e)}if(!d){q(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 hq(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),Y(t,200,Ri,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=mt[e],a=await oO(d.source,e).catch(async e=>{if(i===void 0)throw e;return oO(d.source,i)}),o=a?.source??GO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??jD(o);if(!c){q(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(cZ(t,c,`skill-reimport`))return;let l=await ND(c);r=l.cleanup,f=l.ref;let u=ZD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>XD(e.dir)?.name===n.name)??u.find(e=>e.name===mt[s??n.name])??(u.length===1?u[0]:void 0);if(!m){q(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=YD(m.dir);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=XD(m.dir)}catch(e){if(e instanceof gD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=zX(p);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=XD(V(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){Y(t,200,Ri,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Ua(p.skillMd).body;if(n.dryRun){let e=XD(V(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&M)try{let e=Ns({baseDir:M,timeout:{block:15e3}}),t=B(M,V(a,n.name)).split(ql).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}Y(t,200,Ri,{name:n.name,updated:!0,source:d.source,localBody:Ua(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await Bt(e,`deleted-upstream`)}let x=xj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){q(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=wj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:RX});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Tj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(On(e,Dn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await jn(`skill-reimport`));let C=xs(a,n.name),w=n.scope===`project`?await Ss(Cs(e),o):void 0;await hq(u,e=>zD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await ws({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),O?.(`files`),Y(t,200,Ri,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Hs=J(tn,async(e,t,n)=>{try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Qa(n.name,t,`skill-revert`)||Lo(n.name,t,`skill-revert`))return;if(n.scope===`global`){q(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=z(M,...PD),i=bs(r).skills[n.name];if(!i?.baselineRef){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=S?.current;if(!a){q(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 uZ({shadow:a,contentDir:s,contentRoot:ee??`.`,name:n.name,version:i.baselineRef,skillDirRel:Oo(n.name)});if(!o.ok){Co(t,o,`skill-revert`);return}On(e,Dn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await jn(`skill-revert`);let c=V(s,Oo(n.name),`..`),l=xs(c,n.name);await hq(r,e=>zD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),c===uo(`project`)&&await ws({skillsRoot:c,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),O?.(`files`),Y(t,200,ln,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Ws(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Gs(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Ks(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function qs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Ys=IX({contentDir:s,projectDir:M,getAllFilesIndex:f,getFileIndexGeneration:m,getSearchMaxEntries:Tpe,semanticSearch:be,getSemanticSimilarityFloor:xe,ready:he,getProjectSkillsRoot:()=>uo(`project`),parseFrontmatterDoc:Ua});Ys.prewarm();let Xs=bU({GET:J(lo,Wz(async(e,t)=>{let n=nte(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Ws(n.get(`intent`)),o=zo(n.get(`ranking`)),s=Gs(n.get(`scope`)??n.get(`scopes`)),c=Ks(n.get(`semantic`)),l=qs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}Y(t,200,Va,await Ys.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Pee,Wz(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Ws(n.intent),a=zo(n.ranking),o=Gs(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Ks(n.semantic),l=qs(n.source);if(r.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}Y(t,200,Va,await Ys.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),Zs=J(lo,Wz(async(e,t)=>{Y(t,200,wo,{...await XF(pu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Qs(e,t){if(r(e,t,{handler:`handoff`}))try{await kue(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:Je.probeWithCache})}catch(n){t.headersSent||(Z.error({err:n,requestId:Qx(e)},`[handoff] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function $s(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await gN(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(Z.error({err:n,requestId:Qx(e)},`[spawn-cursor] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let ec=J(xr,async(e,t,n)=>{try{if(!M){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Rde(e,n.kind)){sF(`invalid-path`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`invalid-path`},{handler:oF});return}let r=Ude(M);if(r===null){if(dF(M).kind===`no-remote`){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}sF(`detached-head`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`detached-head`},{handler:oF});return}let i=dF(M);if(i.kind===`no-remote`){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}if(i.kind===`non-github`){sF(`non-github-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`non-github-remote`},{handler:oF});return}if(!Jde(M,r)){sF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:oF});return}let a=sQ(M,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&L(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=zde(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=Bde(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Wu(c)}`,u=await Vde(M,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);sF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),Y(t,200,Cn,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:oF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:oF,cause:e})}},{handler:oF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oF})}),tc=J(lo,async(e,t)=>{try{if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:hz});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(!Ki(r)){q(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:hz});return}if(!pz(i,a)){q(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:hz});return}Y(t,200,oee,await mz(M,r,i,a),{handler:hz})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hz,cause:e})}},{handler:hz,method:`GET`,skipBodyParse:!0}),nc=J(Ti,async(e,t,n)=>{try{if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CF});return}if(!pz(n.path,n.kind)){q(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:CF});return}let e=sQ(M,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;Y(t,200,wee,await nfe(M,n.branch,r,n.kind),{handler:CF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CF,cause:e})}},{handler:CF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:CF})}),rc=J(hr,async(e,t,n)=>{if(Nk(n,oe).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:bz});return}if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:bz});return}try{Y(t,200,lr,await Ps(()=>Sz(M,n.branch,{fastForward:n.fastForward===!0})),{handler:bz})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bz,cause:e})}},{handler:bz,method:`POST`});async function ic(e){let[t,...n]=re,r=[...n,...e];return await new Promise((e,n)=>{let i=Rl(t,r,cN({...$r,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},gF),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 ${gF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=SF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Z.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 ac=J(lo,async(e,t)=>{if(!je.tryAcquire(`/api/share/publish/owners`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:pF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ic([`share`,`owners`,`--json`]),n=Yde(yF(e));xF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),Y(t,200,$ee,n,{handler:pF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:pF,cause:e})}finally{je.release(`/api/share/publish/owners`)}},{handler:pF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:pF})}),oc=J(lo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!vF(r)||!_F(i)){q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:mF});return}if(!je.tryAcquire(`/api/share/publish/name-check`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:mF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ic([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Xde(yF(e));xF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),Y(t,200,Fee,n,{handler:mF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mF,cause:e})}finally{je.release(`/api/share/publish/name-check`)}},{handler:mF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:mF})}),sc=J(oa,async(e,t,n)=>{if(!M){xF(`publish-create`,`no-project`),Y(t,200,Aa,{ok:!1,error:`no-project`},{handler:hF});return}if(!vF(n.owner)||!_F(n.name)){q(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:hF});return}if(!je.tryAcquire(`/api/share/publish`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:hF,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 ic(e),i=$de(yF(r));xF(`publish-create`,i.ok?`ok`:i.error),i.ok&&j?.()?.refreshRemote().catch(()=>{}),Y(t,200,Aa,i,{handler:hF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hF,cause:e})}finally{je.release(`/api/share/publish`)}},{handler:hF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:hF})}),cc=J(uee,async(e,t,n)=>{try{let e=L(`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{}Y(t,200,cn,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){q(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`})}),lc=M?oA(M):null;async function uc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Ise(e.headers),previewUrl:null,port:lc?Js(lc)?.port??0:0,singleFile:De};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}Y(t,200,Ao,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function dc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Ae?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}Y(t,200,me,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let fc=`local-op-embeddings-set-key`,pc=`local-op-embeddings-clear-key`,mc=`/api/local-op/embeddings`;function hc(){let e=we?.();return{projectDir:M??s,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let gc=J(Nee,async(e,t,n)=>{if(!je.tryAcquire(mc)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:fc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=hc();await new gM(Se).setForProject(e,r,n.key),be?.reloadCredential(),Y(t,200,Fe,{keyPresent:!0},{handler:fc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:fc,cause:e})}finally{je.release(mc)}},{handler:fc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:fc})}),_c=J(lo,async(e,t)=>{if(!je.tryAcquire(mc)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:pc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=hc();await new gM(Se).clearForProject(e,n),be?.reloadCredential(),Y(t,200,Fe,{keyPresent:!1},{handler:pc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:pc,cause:e})}finally{je.release(mc)}},{handler:pc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:pc})}),vc=`local-op-embeddings-test`,yc=`/api/local-op/embeddings/test`,bc=J(lo,async(e,t)=>{if(!je.tryAcquire(yc)){q(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:vc,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 lM(new gM(Se),M??s,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Mle({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};Y(t,200,Qee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:vc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:vc,cause:e})}finally{je.release(yc)}},{handler:vc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vc})}),xc=J(lo,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(be){let t=be.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=we?.()?.baseUrl??`https://api.openai.com/v1`,o=await lM(new gM(Se),M??s,a),c=o.apiKey!==null,u=!c&&o.keyless,d=c?o.source:null,f=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of l())!Vx(e)&&!Hx(e)&&!qa(e)&&(p+=1);Y(t,200,aa,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Sc=0;function Cc(){Sc+=1,O?.(`lint-config`)}let wc=()=>`${Sc} ${t.getActiveBranch()}`;async function Tc(e,t){let n=Te?.()??Ze;try{let r=await ra(e,UP(s,n,{docName:t,projectDir:M??s,onProblem:e=>Z.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ee?.()??`warning`;if(D&&a!==`off`&&!qx(t)){await Ot(t,e,`lint-validation`);let r=nF({projectDir:M??s,contentDir:s,baseConfig:n,derivedDocumentIndex:D,linksValidation:a,admittedDocNames:Tt,docFilePathFor:e=>iQ(s,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:iQ(s,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Z.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ec(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=KP({projectDir:M??s,contentDir:s});return hP(t.schemas,n)}let Dc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!hQ(n))){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Te?.()??Ze,i=[],a=BP(s,n??void 0,e=>i.push(e)),o=HP(M??s,VP(r,a),e=>i.push(e));n===null&&i.push(...Ec(o)),Y(t,200,hi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Oc=J(So,async(e,t,n)=>{let r;try{r=tF(V(s),n.ruleId,n.value)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){q(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}Cc();try{let e=Te?.()??Ze,n=[],r=BP(s,void 0,e=>n.push(e)),i=HP(M??s,VP(e,r),e=>n.push(e));n.push(...Ec(i)),Y(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){q(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`}),kc=J(Lee,async(e,t,n)=>{let r;try{let e=V(M??s),t=n.parentPath??[];r=n.delete?Tde(e,n.file):n.field!==void 0&&n.removeField?Cde(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?wde(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?xde(e,n.file,n.field,n.constraint,t):Sde(e,n.file)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){q(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`)&&O?.(`files`),Cc();try{let e=Te?.()??Ze,n=[],r=BP(s,void 0,e=>n.push(e)),i=HP(M??s,VP(e,r),e=>n.push(e));n.push(...Ec(i)),Y(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){q(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`}),Ac=J(lo,async(e,t)=>{try{let e=V(M??s),{schemas:n,truncated:r}=Xue(e),i=new Set(n),a=!1;if(de!==void 0){let t=JZ({contentDir:s,contentFilter:de,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Ui(a)){let t=B(e,V(s,a));!t.startsWith(`..`)&&!Wl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));Y(t,200,Wee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),jc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Mc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!hQ(n)){q(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=iQ(s,n);if(r===null){q(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Te?.()??Ze,a=[],o=await GP({projectDir:M??s,contentDir:s,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:jc});Y(t,200,si,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof ZM){q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Nc=new dP,Pc=sZ();function Fc(e,t,n){let r=`${n} ${wc()} ${t??``}`;return Pc.run(r,()=>kde(e,{targetPath:t})).promise}function Ic(e,t){q(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Lc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!YZ(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Te?.()??Ze;Y(t,200,Xi,await qP({projectDir:M??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:jc,cache:Nc,auditGeneration:wc}),{handler:`lint-audit`})}catch(e){if(e instanceof WP){Ic(t,`lint-audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Rc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YZ(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YZ(o)){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=iQ(s,o)??`${o}.md`}let c=Te?.()??Ze,l=await Fc(nF({projectDir:M??s,contentDir:s,baseConfig:c,liveSourceFor:jc,derivedDocumentIndex:D??null,linksValidation:Ee?.(),admittedDocNames:Tt,docFilePathFor:e=>iQ(s,e),cache:Nc,auditGeneration:wc}),i,dP.fingerprintConfig(c));if(n.searchParams.get(`counts`)===`1`){Y(t,200,Eee,Ode(l),{handler:`audit`});return}Y(t,200,mo,l,{handler:`audit`})}catch(e){if(e instanceof WP){Ic(t,`audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),zc=J(Or,async(t,n,r)=>{try{let t=ZZ(r.docName,n,`lint-fix`);if(t===null)return;let i=ut(t),a=Nk(r,oe);if(a.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?c:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Vx(i)||Hx(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=iQ(s,i);if(f===null){q(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}oN(V(s,f),s);let p=Te?.()??Ze,{stored:m}=xn(a.summary),h=await o.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await _de({projectDir:M??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Yr(d),n=Wr[t]??Hi(u??c);k?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{Fw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,Nw(h))},h.origin),a.kind!==`anonymous`&&Wj(i,c,l,u,void 0,a.kind===`agent`?bn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{k?.touchMode(c,`idle`)}let t=await vt(i);if(t?.kind===`failure`){bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){xt(n,`lint-fix`);return}_t(i,`lint-fix`);try{b=await ra(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Z.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;Y(n,200,Za,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof ZM){q(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof oS){sS(n,e,`lint-fix`);return}if(e instanceof dS){pS(n,e,`lint-fix`);return}if(e instanceof Gw){q(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e},`[lint-fix] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Bc=`link-preview`,Vc=new OW({cacheDir:De?null:V(M??s,`.ok`,`local`,`link-previews`)}),Hc=null,Uc=()=>(Hc??=Vc.init(),Hc),Wc=Oe??yW;async function Gc(e){let t=await Wc(e);return t.ok?{ok:!0,metadata:await wW({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Wc})}:{ok:!1,reason:t.reason}}let Kc=()=>{try{return ke?.()===!0}catch{return!1}},qc=J(Wi,async(e,t,n)=>{try{if(!Kc()){Z.debug({outcome:`disabled`},`[link-preview] request outcome`),Y(t,200,Ka,{ok:!1,reason:`disabled`},{handler:Bc});return}await Uc();let e=!1,r=await Vc.load(n.url,()=>(e=!0,Gc(n.url)));Vc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Z.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Y(t,200,Ka,i,{handler:Bc})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Bc,cause:e})}},{handler:Bc,method:`POST`,preBodyGate:(e,t)=>{let n=jW({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Bc}):q(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Bc}),!1)}}),Jc=qse({service:Qe,getPrincipal:oe,onChanged:()=>O?.(`comments`)}),Yc=bU({GET:Jc.list,POST:Jc.create},{handler:`comments`}),Xc=bU({GET:Jc.read,POST:Jc.mutate,DELETE:Jc.remove},{handler:`comment`}),{handleSkillsSearch:Zc,handleSkillsPopular:Qc,handleSkillsPublisher:$c,handleSkillsDetail:el,handleSkillsPreview:tl,handleSkillsDiscover:nl,handleSkillsResolveRef:rl}=npe({log:Z,skillsHome:ao,projectDir:M,contentDir:s,resolveSkillDirForRead:fo}),il={"/api/config":uc,"/api/config/diagnostics":dc,"/api/comments":Yc,"/api/comment":Xc,"/api/asset":Sr,"/api/asset-text":Nr,"/api/comment-counts":Rn,"/api/link-preview":qc,"/api/folder-config":Ra,"/api/template":Ya,"/api/template/import":Xa,"/api/templates":Ha,"/api/skill":rs,"/api/skill-file":hs,"/api/skill-file/rename":_s,"/api/skills":Wo,"/api/skills/installed":In,"/api/skills/search":Zc,"/api/skills/popular":Qc,"/api/skills/publisher":$c,"/api/skills/detail":el,"/api/skills/preview":tl,"/api/skills/discover":nl,"/api/skills/resolve-ref":rl,"/api/skill/import":Ds,"/api/skills/import-bulk":Os,"/api/skill/edit-external":es,"/api/skill/duplicate":ns,"/api/skill/move-scope":ts,"/api/skill-upload":Is,"/api/skill/install":Ls,"/api/skill/uninstall":Rs,"/api/skill/restore":Bs,"/api/skill/reimport":Vs,"/api/skill/revert":Hs,"/api/skill-targets":zs,"/api/search":Xs,"/api/semantic-status":xc,"/api/lint/config":Dc,"/api/lint/markdownlint-config":Oc,"/api/lint/frontmatter-schema":kc,"/api/lint/frontmatter-schemas":Ac,"/api/lint":Mc,"/api/lint/audit":Lc,"/api/lint/fix":zc,"/api/audit":Rc,"/api/create-page":Fr,"/api/create-folder":Lr,"/api/duplicate-path":Rr,"/api/rename-path":zr,"/api/delete-path":Br,"/api/trash/cleanup":Ur,"/api/upload":Gr,"/api/agent-write":Mn,"/api/agent-write-md":Nn,"/api/agent-write-batch":Pn,"/api/frontmatter-patch":Fn,"/api/agent-patch":Vn,"/api/agent-undo":Hn,"/api/agent-activity":Un,"/api/agent-burst-diff":Wn,"/api/save-version":Qn,"/api/history":$n,"/api/rollback":tr,"/api/__embed-detect":cr,"/api/server-info":nr,"/api/acp/catalog":ar,"/api/share/construct-url":ec,"/api/share/target-status":nc,"/api/git/branch-info":tc,"/api/git/checkout":rc,"/api/share/publish/owners":ac,"/api/share/publish/name-check":oc,"/api/share/publish":sc,"/api/principal":sr,"/api/rescue":Pr,"/api/workspace":ur,"/api/sync/status":ga,"/api/sync/trigger":va,"/api/sync/conflicts":xa,"/api/sync/conflict-content":Ca,"/api/sync/resolve-conflict":Sa,"/api/local-op/clone":ri,"/api/local-op/ok-init":fi,"/api/local-op/auth/login":Ii,"/api/local-op/auth/status":ea,"/api/local-op/auth/pat":na,"/api/local-op/auth/gh-login":Vi,"/api/local-op/auth/cancel":Yi,"/api/local-op/auth/repos":la,"/api/local-op/auth/signout":fa,"/api/local-op/auth/set-identity":ha,"/api/local-op/embeddings/set-key":gc,"/api/local-op/embeddings/clear-key":_c,"/api/local-op/embeddings/test":bc,"/api/installed-agents":Ma,"/api/spawn-cursor":$s,"/api/handoff":Qs,"/api/install-skill":Oa,"/api/skill/install-state":Zs,"/api/seed/plan":wa,"/api/seed/apply":Ea,"/api/seed/packs":Da,"/api/client-logs":cc};x&&(il[`/api/test-reset`]=Kn,il[`/api/test-flush-git`]=Gn,il[`/api/test-rescan-backlinks`]=qn,il[`/api/test-rescan-files`]=Jn);let al=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),ol=[`/api/local-op/`],sl=Uz({log:Z,remotePublicHost:n,ephemeral:De,table:{resolve(e){let t=il[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await er(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>al.has(e)||ol.some(t=>e.startsWith(t))}}),cl=gU({hocuspocus:a,derivedDocumentIndex:D,getFileIndex:l,isSafeDocName:hQ,readPageTitleForDocName:tt,readPageTitleForLinkedDocName:nt,readFrontmatterMetadataForLinkedDocName:at,collectAdmittedDocNames:Tt,resolveAlias:ut,respondToDerivedIndexQueryFailure:At}),ll=[cl,xU({hocuspocus:a,agentPresenceBroadcaster:k,isAllowedWorkspaceHostHeader:i,log:Z}),Pe],ul=ll.flatMap(e=>[...e.paths]);UH(ul,il);let dl=ll.map(e=>Uz({log:Z,remotePublicHost:n,ephemeral:De,table:e.table})),fl={paths:ul,dispatch:async(e,t)=>{for(let n of dl)if(await n(e,t))return!0;return!1}},pl=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`]);for(let e of pl)if(il[e]===void 0&&cl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await sl(e,t)},nativeApi:fl,localApi:yU({resolve:e=>{if(!pl.has(e))return;let t=il[e];return t===void 0?cl.table.resolve(e)?.dispatch:t}})}}function _Q(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a}=e;return(e,o,s)=>{let c;try{c=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return s()}let l=Ul(c).slice(1).toLowerCase(),u=l===`md`||l===`mdx`;if(!c||t.isPathIgnored(c)||!u&&!i.has(l))return s();o.setHeader(`X-Content-Type-Options`,`nosniff`);let d=hX(l,r);u||o.setHeader(`Content-Disposition`,d.disposition),d.csp!==null&&o.setHeader(`Content-Security-Policy`,d.csp),d.sandboxedHtml&&o.setHeader(`Cache-Control`,`no-store`),n(e,o,()=>{if(o.headersSent)return;let e=ee.has(l);if(!e&&(i.has(l)||a.has(l))){o.statusCode=404,o.end();return}e&&(o.removeHeader(`Content-Security-Policy`),o.removeHeader(`Content-Disposition`),o.removeHeader(`X-Content-Type-Options`),o.removeHeader(`Cache-Control`)),s()})}}function vQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Bpe(e){let t;try{t=iu(e.contentDir,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ax(n.name,c)&&e.basenameIndex.add(n.name)}async function yQ(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=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=nN(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await yu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Su(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!rN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Cu(i)}catch(t){let n=vQ(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()&&Ax(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Ax(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const bQ=P({principalId:I().optional(),tabSessionId:I().optional(),expectedServerInstanceId:I().optional(),expectedBranch:I().optional(),expectedDocLineageEpoch:I().optional(),clientProtocolVersion:F().optional(),clientRuntimeVersion:I().optional(),clientKind:I().optional()}).loose(),xQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function SQ(e){return xQ.includes(e)}function CQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Vpe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!SQ(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 wQ=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=CQ(e,this.payload)}};function TQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=bQ.safeParse(t);return n.success?n.data:void 0}var EQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const DQ=L(`conflict-storage`);var OQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(oA(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!H(this.storePath)){this.conflicts=[];return}try{let e=U(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){DQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){DQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);H(e)||tu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return du(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return DQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-Rma56ZDs.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!rN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);WI(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),DQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Pb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){DQ.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}),DQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=V(this.projectDir),a=V(i,e.file);if(!rN(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(WI(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-Rma56ZDs.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);WI(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:H(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Hpe(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 Upe(e,t){let n=oA(e);try{tu(n,{recursive:!0}),du(z(n,cr),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Os(e);tu(R(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`};du(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const kQ=new Map;let AQ=!1;function Wpe(e,t){try{let n=Hpe(e,t);for(let e of kQ.keys())Upe(e,n)}catch{}}function Gpe(e){kQ.set(e,(kQ.get(e)??0)+1),AQ||(AQ=!0,process.on(`uncaughtExceptionMonitor`,Wpe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=kQ.get(e)??0;n<=1?kQ.delete(e):kQ.set(e,n-1)}}}function jQ(e){let t=e.scheduler??Ra,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function MQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NQ(e){if(!H(e))return{};let t;try{t=(0,Dk.parse)(U(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(!MQ(t))return{};let n=t.telemetry;if(!MQ(n))return{};let r=n.localSink;return MQ(r)?r:{}}function PQ(e){return typeof e==`boolean`?e:void 0}function Kpe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function FQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function IQ(e){if(MQ(e))return Kpe(e.maxBytes)}function qpe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=NQ(Yo(`project`,e.projectDir)),n=NQ(Yo(`project-local`,e.projectDir));if((PQ(n.enabled)??PQ(t.enabled)??!0)===!1)return null;let r=IQ(n.spans)??IQ(t.spans)??52428800,i=IQ(n.logs)??IQ(t.logs)??26214400,a=FQ(n.attributeDenylist)??FQ(t.attributeDenylist)??Te;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var LQ;(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})(LQ||={});var Jpe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Jpe||={});const RQ=LQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),zQ=e=>{switch(typeof e){case`undefined`:return RQ.undefined;case`string`:return RQ.string;case`number`:return Number.isNaN(e)?RQ.nan:RQ.number;case`boolean`:return RQ.boolean;case`function`:return RQ.function;case`bigint`:return RQ.bigint;case`symbol`:return RQ.symbol;case`object`:return Array.isArray(e)?RQ.array:e===null?RQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?RQ.promise:typeof Map<`u`&&e instanceof Map?RQ.map:typeof Set<`u`&&e instanceof Set?RQ.set:typeof Date<`u`&&e instanceof Date?RQ.date:RQ.object;default:return RQ.unknown}},Q=LQ.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 BQ=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,LQ.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()}};BQ.create=e=>new BQ(e);const VQ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===RQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,LQ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${LQ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${LQ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${LQ.joinValues(e.options)}, received '${e.received}'`;break;case Q.invalid_arguments:n=`Invalid function arguments`;break;case Q.invalid_return_type:n=`Invalid function return type`;break;case Q.invalid_date:n=`Invalid date`;break;case Q.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}"`:LQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Q.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 Q.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 Q.custom:n=`Invalid input`;break;case Q.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Q.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Q.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,LQ.assertNever(e)}return{message:n}};let Ype=VQ;function HQ(){return Ype}const UQ=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 WQ(e,t){let n=HQ(),r=UQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===VQ?void 0:VQ].filter(e=>!!e)});e.common.issues.push(r)}var GQ=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 KQ;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 KQ;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 KQ=Object.freeze({status:`aborted`}),qQ=e=>({status:`dirty`,value:e}),JQ=e=>({status:`valid`,value:e}),YQ=e=>e.status===`aborted`,XQ=e=>e.status===`dirty`,ZQ=e=>e.status===`valid`,QQ=e=>typeof Promise<`u`&&e instanceof Promise;var $Q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})($Q||={});var e$=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 t$=(e,t)=>{if(ZQ(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 BQ(e.common.issues);return this._error=t,this._error}}};function n$(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 r$=class{get description(){return this._def.description}_getType(e){return zQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new GQ,ctx:{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(QQ(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:zQ(e)};return t$(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:zQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ZQ(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=>ZQ(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:zQ(e)},r=this._parse({data:e,path:n.path,parent:n});return t$(n,await(QQ(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:Q.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 F$({schema:this,typeName:$.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 I$.create(this,this._def)}nullable(){return L$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return y$.create(this)}promise(){return P$.create(this,this._def)}or(e){return S$.create([this,e],this._def)}and(e){return T$.create(this,e,this._def)}transform(e){return new F$({...n$(this._def),schema:this,typeName:$.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new R$({...n$(this._def),innerType:this,defaultValue:t,typeName:$.ZodDefault})}brand(){return new V$({typeName:$.ZodBranded,type:this,...n$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new z$({...n$(this._def),innerType:this,catchValue:t,typeName:$.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return H$.create(this,e)}readonly(){return U$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Xpe=/^c[^\s-]{8,}$/i,Zpe=/^[0-9a-z]+$/,Qpe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$pe=/^[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,eme=/^[a-z0-9_-]{21}$/i,tme=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nme=/^[-+]?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)?)??$/,rme=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let i$;const ime=/^(?:(?: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])$/,ame=/^(?:(?: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])$/,ome=/^(([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]))$/,sme=/^(([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])$/,cme=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lme=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a$=`((\\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])))`,ume=RegExp(`^${a$}$`);function o$(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 dme(e){return RegExp(`^${o$(e)}$`)}function fme(e){let t=`${a$}T${o$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function pme(e,t){return!!((t===`v4`||!t)&&ime.test(e)||(t===`v6`||!t)&&ome.test(e))}function mme(e,t){if(!tme.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 hme(e,t){return!!((t===`v4`||!t)&&ame.test(e)||(t===`v6`||!t)&&sme.test(e))}var s$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==RQ.string){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.string,received:t.parsedType}),KQ}let t=new GQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.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),WQ(n,{code:Q.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?WQ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&WQ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)rme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)i$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),i$.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)$pe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)eme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Xpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Zpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Qpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ulid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),WQ(n,{validation:`url`,code:Q.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),WQ(n,{validation:`regex`,code:Q.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),WQ(n,{code:Q.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),WQ(n,{code:Q.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?fme(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ume.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?dme(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?nme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?pme(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?mme(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?hme(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?cme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?lme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Q.invalid_string,...$Q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...$Q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...$Q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...$Q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...$Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...$Q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...$Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...$Q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...$Q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...$Q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...$Q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...$Q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...$Q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...$Q.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,...$Q.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,...$Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...$Q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...$Q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...$Q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...$Q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...$Q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...$Q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...$Q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...$Q.errToObj(t)})}nonempty(e){return this.min(1,$Q.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}};s$.create=e=>new s$({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...n$(e)});function gme(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 c$=class e extends r${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)!==RQ.number){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.number,received:t.parsedType}),KQ}let t,n=new GQ;for(let r of this._def.checks)r.kind===`int`?LQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.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),WQ(t,{code:Q.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),WQ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?gme(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.not_finite,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:$Q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:$Q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:$Q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:$Q.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`&&LQ.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)}};c$.create=e=>new c$({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...n$(e)});var l$=class e extends r${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)!==RQ.bigint)return this._getInvalidInput(e);let t,n=new GQ;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),WQ(t,{code:Q.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),WQ(t,{code:Q.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),WQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.bigint,received:t.parsedType}),KQ}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.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:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.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}};l$.create=e=>new l$({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...n$(e)});var u$=class extends r${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==RQ.boolean){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.boolean,received:t.parsedType}),KQ}return JQ(e.data)}};u$.create=e=>new u$({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...n$(e)});var d$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==RQ.date){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.date,received:t.parsedType}),KQ}if(Number.isNaN(e.data.getTime()))return WQ(this._getOrReturnCtx(e),{code:Q.invalid_date}),KQ;let t=new GQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.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),WQ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):LQ.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:$Q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:$Q.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)}};d$.create=e=>new d$({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...n$(e)});var f$=class extends r${_parse(e){if(this._getType(e)!==RQ.symbol){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.symbol,received:t.parsedType}),KQ}return JQ(e.data)}};f$.create=e=>new f$({typeName:$.ZodSymbol,...n$(e)});var p$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.undefined,received:t.parsedType}),KQ}return JQ(e.data)}};p$.create=e=>new p$({typeName:$.ZodUndefined,...n$(e)});var m$=class extends r${_parse(e){if(this._getType(e)!==RQ.null){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.null,received:t.parsedType}),KQ}return JQ(e.data)}};m$.create=e=>new m$({typeName:$.ZodNull,...n$(e)});var h$=class extends r${constructor(){super(...arguments),this._any=!0}_parse(e){return JQ(e.data)}};h$.create=e=>new h$({typeName:$.ZodAny,...n$(e)});var g$=class extends r${constructor(){super(...arguments),this._unknown=!0}_parse(e){return JQ(e.data)}};g$.create=e=>new g$({typeName:$.ZodUnknown,...n$(e)});var _$=class extends r${_parse(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.never,received:t.parsedType}),KQ}};_$.create=e=>new _$({typeName:$.ZodNever,...n$(e)});var v$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.void,received:t.parsedType}),KQ}return JQ(e.data)}};v$.create=e=>new v$({typeName:$.ZodVoid,...n$(e)});var y$=class e extends r${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==RQ.array)return WQ(t,{code:Q.invalid_type,expected:RQ.array,received:t.parsedType}),KQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(WQ(t,{code:e?Q.too_big:Q.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&&(WQ(t,{code:Q.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&&(WQ(t,{code:Q.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 e$(t,e,t.path,n)))).then(e=>GQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new e$(t,e,t.path,n)));return GQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:$Q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:$Q.toString(n)}})}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...n$(t)});function b$(e){if(e instanceof x$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=I$.create(b$(r))}return new x$({...e._def,shape:()=>t})}else if(e instanceof y$)return new y$({...e._def,type:b$(e.element)});else if(e instanceof I$)return I$.create(b$(e.unwrap()));else if(e instanceof L$)return L$.create(b$(e.unwrap()));else if(e instanceof E$)return E$.create(e.items.map(e=>b$(e)));else return e}var x$=class e extends r${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=LQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==RQ.object){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.object,received:t.parsedType}),KQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _$&&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 e$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof _$){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&&(WQ(n,{code:Q.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 e$(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=>GQ.mergeObjectSync(t,e)):GQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return $Q.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:$Q.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:$.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 LQ.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 LQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return b$(this)}partial(t){let n={};for(let e of LQ.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 LQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof I$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return j$(LQ.objectKeys(this.shape))}};x$.create=(e,t)=>new x$({shape:()=>e,unknownKeys:`strip`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)}),x$.strictCreate=(e,t)=>new x$({shape:()=>e,unknownKeys:`strict`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)}),x$.lazycreate=(e,t)=>new x$({shape:e,unknownKeys:`strip`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)});var S$=class extends r${_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 BQ(e.ctx.common.issues));return WQ(t,{code:Q.invalid_union,unionErrors:n}),KQ}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 BQ(e));return WQ(t,{code:Q.invalid_union,unionErrors:i}),KQ}}get options(){return this._def.options}};S$.create=(e,t)=>new S$({options:e,typeName:$.ZodUnion,...n$(t)});const C$=e=>e instanceof k$?C$(e.schema):e instanceof F$?C$(e.innerType()):e instanceof A$?[e.value]:e instanceof M$?e.options:e instanceof N$?LQ.objectValues(e.enum):e instanceof R$?C$(e._def.innerType):e instanceof p$?[void 0]:e instanceof m$?[null]:e instanceof I$?[void 0,...C$(e.unwrap())]:e instanceof L$?[null,...C$(e.unwrap())]:e instanceof V$||e instanceof U$?C$(e.unwrap()):e instanceof z$?C$(e._def.innerType):[];var _me=class e extends r${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.object)return WQ(t,{code:Q.invalid_type,expected:RQ.object,received:t.parsedType}),KQ;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}):(WQ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),KQ)}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=C$(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...n$(r)})}};function w$(e,t){let n=zQ(e),r=zQ(t);if(e===t)return{valid:!0,data:e};if(n===RQ.object&&r===RQ.object){let n=LQ.objectKeys(t),r=LQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=w$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===RQ.array&&r===RQ.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=w$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===RQ.date&&r===RQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var T$=class extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(YQ(e)||YQ(r))return KQ;let i=w$(e.value,r.value);return i.valid?((XQ(e)||XQ(r))&&t.dirty(),{status:t.value,value:i.data}):(WQ(n,{code:Q.invalid_intersection_types}),KQ)};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}))}};T$.create=(e,t,n)=>new T$({left:e,right:t,typeName:$.ZodIntersection,...n$(n)});var E$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.array)return WQ(n,{code:Q.invalid_type,expected:RQ.array,received:n.parsedType}),KQ;if(n.data.length<this._def.items.length)return WQ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),KQ;!this._def.rest&&n.data.length>this._def.items.length&&(WQ(n,{code:Q.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 e$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>GQ.mergeArray(t,e)):GQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};E$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new E$({items:e,typeName:$.ZodTuple,rest:null,...n$(t)})};var vme=class e extends r${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!==RQ.object)return WQ(n,{code:Q.invalid_type,expected:RQ.object,received:n.parsedType}),KQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new e$(n,e,n.path,e)),value:a._parse(new e$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?GQ.mergeObjectAsync(t,r):GQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof r$?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...n$(r)}):new e({keyType:s$.create(),valueType:t,typeName:$.ZodRecord,...n$(n)})}},D$=class extends r${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!==RQ.map)return WQ(n,{code:Q.invalid_type,expected:RQ.map,received:n.parsedType}),KQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new e$(n,e,n.path,[a,`key`])),value:i._parse(new e$(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 KQ;(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 KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};D$.create=(e,t,n)=>new D$({valueType:t,keyType:e,typeName:$.ZodMap,...n$(n)});var O$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.set)return WQ(n,{code:Q.invalid_type,expected:RQ.set,received:n.parsedType}),KQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(WQ(n,{code:Q.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&&(WQ(n,{code:Q.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 KQ;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 e$(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:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:$Q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};O$.create=(e,t)=>new O$({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...n$(t)});var yme=class e extends r${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.function)return WQ(t,{code:Q.invalid_type,expected:RQ.function,received:t.parsedType}),KQ;function n(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Q.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof P$){let e=this;return JQ(async function(...t){let o=new BQ([]),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 JQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new BQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new BQ([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:E$.create(t).rest(g$.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||E$.create([]).rest(g$.create()),returns:n||g$.create(),typeName:$.ZodFunction,...n$(r)})}},k$=class extends r${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})}};k$.create=(e,t)=>new k$({getter:e,typeName:$.ZodLazy,...n$(t)});var A$=class extends r${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return WQ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),KQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};A$.create=(e,t)=>new A$({value:e,typeName:$.ZodLiteral,...n$(t)});function j$(e,t){return new M$({values:e,typeName:$.ZodEnum,...n$(t)})}var M$=class e extends r${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{expected:LQ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),KQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),KQ}return JQ(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})}};M$.create=j$;var N$=class extends r${_parse(e){let t=LQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==RQ.string&&n.parsedType!==RQ.number){let e=LQ.objectValues(t);return WQ(n,{expected:LQ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),KQ}if(this._cache||=new Set(LQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=LQ.objectValues(t);return WQ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),KQ}return JQ(e.data)}get enum(){return this._def.values}};N$.create=(e,t)=>new N$({values:e,typeName:$.ZodNativeEnum,...n$(t)});var P$=class extends r${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==RQ.promise&&t.common.async===!1?(WQ(t,{code:Q.invalid_type,expected:RQ.promise,received:t.parsedType}),KQ):JQ((t.parsedType===RQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};P$.create=(e,t)=>new P$({type:e,typeName:$.ZodPromise,...n$(t)});var F$=class extends r${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{WQ(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 KQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r});{if(t.value===`aborted`)return KQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(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`?KQ:(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`?KQ:(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(!ZQ(e))return KQ;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=>ZQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):KQ);LQ.assertNever(r)}};F$.create=(e,t,n)=>new F$({schema:e,typeName:$.ZodEffects,effect:t,...n$(n)}),F$.createWithPreprocess=(e,t,n)=>new F$({schema:t,effect:{type:`preprocess`,transform:e},typeName:$.ZodEffects,...n$(n)});var I$=class extends r${_parse(e){return this._getType(e)===RQ.undefined?JQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I$.create=(e,t)=>new I$({innerType:e,typeName:$.ZodOptional,...n$(t)});var L$=class extends r${_parse(e){return this._getType(e)===RQ.null?JQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:$.ZodNullable,...n$(t)});var R$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===RQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...n$(t)});var z$=class extends r${_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 QQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...n$(t)});var B$=class extends r${_parse(e){if(this._getType(e)!==RQ.nan){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.nan,received:t.parsedType}),KQ}return{status:`valid`,value:e.data}}};B$.create=e=>new B$({typeName:$.ZodNaN,...n$(e)});var V$=class extends r${_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}},H$=class e extends r${_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`?KQ:e.status===`dirty`?(t.dirty(),qQ(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`?KQ: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:$.ZodPipeline})}},U$=class extends r${_parse(e){let t=this._def.innerType._parse(e),n=e=>(ZQ(e)&&(e.value=Object.freeze(e.value)),e);return QQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};U$.create=(e,t)=>new U$({innerType:e,typeName:$.ZodReadonly,...n$(t)}),x$.lazycreate;var $;(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`})($||={}),s$.create,c$.create,B$.create,l$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create;const bme=x$.create;x$.strictCreate,S$.create,_me.create,T$.create,E$.create,vme.create,D$.create,O$.create,yme.create,k$.create,A$.create,M$.create,N$.create,P$.create,F$.create,I$.create,L$.create,F$.createWithPreprocess,H$.create;const xme=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>pe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>fe(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Sme=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),xme.init(e,t),l(e,`shape`,()=>t.shape)});function W$(e,t){return new Sme({type:`object`,shape:e??{},...d(t)})}function G$(e){return!!e._zod}function K$(e){let t=Object.values(e);if(t.length===0)return W$({});let n=t.every(G$),r=t.every(e=>!G$(e));if(n)return W$(e);if(r)return bme(e);throw Error(`Mixed Zod versions detected in object shape.`)}function q$(e,t){return G$(e)?fe(e,t):e.safeParse(t)}async function J$(e,t){return G$(e)?await h(e,t):await e.safeParseAsync(t)}function Y$(e){if(!e)return;let t;if(t=G$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function X$(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 K$(e)}}if(G$(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 Z$(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 Cme(e){return e.description}function wme(e){if(G$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Q$(e){if(G$(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 $$=`2025-11-25`,e1=[$$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],t1=`io.modelcontextprotocol/related-task`,n1=ve(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),r1=ke([I(),F().int()]),i1=I();se({ttl:F().optional(),pollInterval:F().optional()});const Tme=P({ttl:F().optional()}),Eme=P({taskId:I()}),a1=se({progressToken:r1.optional(),[t1]:Eme.optional()}),o1=P({_meta:a1.optional()}),s1=o1.extend({task:Tme.optional()}),Dme=e=>s1.safeParse(e).success,c1=P({method:I(),params:o1.loose().optional()}),l1=P({_meta:a1.optional()}),u1=P({method:I(),params:l1.loose().optional()}),d1=se({_meta:a1.optional()}),f1=ke([I(),F().int()]),p1=P({jsonrpc:M(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=P({jsonrpc:M(`2.0`),...u1.shape}).strict(),Ome=e=>h1.safeParse(e).success,g1=P({jsonrpc:M(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(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`})(v1||={});const y1=P({jsonrpc:M(`2.0`),id:f1.optional(),error:P({code:F().int(),message:I(),data:j().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=ke([p1,h1,g1,y1]);ke([g1,y1]);const S1=d1.strict(),kme=l1.extend({requestId:f1.optional(),reason:I().optional()}),C1=u1.extend({method:M(`notifications/cancelled`),params:kme}),w1=P({icons:N(P({src:I(),mimeType:I().optional(),sizes:N(I()).optional(),theme:Ce([`light`,`dark`]).optional()})).optional()}),T1=P({name:I(),title:I().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),Ame=le(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,he(P({form:he(P({applyDefaults:A().optional()}),k(I(),j())).optional(),url:n1.optional()}),k(I(),j()).optional())),jme=se({list:n1.optional(),cancel:n1.optional(),requests:se({sampling:se({createMessage:n1.optional()}).optional(),elicitation:se({create:n1.optional()}).optional()}).optional()}),Mme=se({list:n1.optional(),cancel:n1.optional(),requests:se({tools:se({call:n1.optional()}).optional()}).optional()}),Nme=P({experimental:k(I(),n1).optional(),sampling:P({context:n1.optional(),tools:n1.optional()}).optional(),elicitation:Ame.optional(),roots:P({listChanged:A().optional()}).optional(),tasks:jme.optional(),extensions:k(I(),n1).optional()}),Pme=o1.extend({protocolVersion:I(),capabilities:Nme,clientInfo:E1}),D1=c1.extend({method:M(`initialize`),params:Pme}),O1=e=>D1.safeParse(e).success,Fme=P({experimental:k(I(),n1).optional(),logging:n1.optional(),completions:n1.optional(),prompts:P({listChanged:A().optional()}).optional(),resources:P({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:P({listChanged:A().optional()}).optional(),tasks:Mme.optional(),extensions:k(I(),n1).optional()}),Ime=d1.extend({protocolVersion:I(),capabilities:Fme,serverInfo:E1,instructions:I().optional()}),k1=u1.extend({method:M(`notifications/initialized`),params:l1.optional()}),Lme=e=>k1.safeParse(e).success,A1=c1.extend({method:M(`ping`),params:o1.optional()}),Rme=P({progress:F(),total:ue(F()),message:ue(I())}),zme=P({...l1.shape,...Rme.shape,progressToken:r1}),j1=u1.extend({method:M(`notifications/progress`),params:zme}),Bme=o1.extend({cursor:i1.optional()}),M1=c1.extend({params:Bme.optional()}),N1=d1.extend({nextCursor:i1.optional()}),Vme=Ce([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=P({taskId:I(),status:Vme,ttl:ke([F(),_e()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:ue(F()),statusMessage:ue(I())}),F1=d1.extend({task:P1}),Hme=l1.merge(P1),I1=u1.extend({method:M(`notifications/tasks/status`),params:Hme}),L1=c1.extend({method:M(`tasks/get`),params:o1.extend({taskId:I()})}),R1=d1.merge(P1),z1=c1.extend({method:M(`tasks/result`),params:o1.extend({taskId:I()})});d1.loose();const B1=M1.extend({method:M(`tasks/list`)}),V1=N1.extend({tasks:N(P1)}),H1=c1.extend({method:M(`tasks/cancel`),params:o1.extend({taskId:I()})}),Ume=d1.merge(P1),U1=P({uri:I(),mimeType:ue(I()),_meta:k(I(),j()).optional()}),W1=U1.extend({text:I()}),G1=I().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=Ce([`user`,`assistant`]),J1=P({audience:N(q1).optional(),priority:F().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),Y1=P({...T1.shape,...w1.shape,uri:I(),description:ue(I()),mimeType:ue(I()),size:ue(F()),annotations:J1.optional(),_meta:ue(se({}))}),Wme=P({...T1.shape,...w1.shape,uriTemplate:I(),description:ue(I()),mimeType:ue(I()),annotations:J1.optional(),_meta:ue(se({}))}),X1=M1.extend({method:M(`resources/list`)}),Gme=N1.extend({resources:N(Y1)}),Z1=M1.extend({method:M(`resources/templates/list`)}),Kme=N1.extend({resourceTemplates:N(Wme)}),Q1=o1.extend({uri:I()}),qme=Q1,$1=c1.extend({method:M(`resources/read`),params:qme}),Jme=d1.extend({contents:N(ke([W1,K1]))}),Yme=u1.extend({method:M(`notifications/resources/list_changed`),params:l1.optional()}),Xme=Q1,Zme=c1.extend({method:M(`resources/subscribe`),params:Xme}),Qme=Q1,$me=c1.extend({method:M(`resources/unsubscribe`),params:Qme}),ehe=l1.extend({uri:I()}),the=u1.extend({method:M(`notifications/resources/updated`),params:ehe}),nhe=P({name:I(),description:ue(I()),required:ue(A())}),rhe=P({...T1.shape,...w1.shape,description:ue(I()),arguments:ue(N(nhe)),_meta:ue(se({}))}),e0=M1.extend({method:M(`prompts/list`)}),ihe=N1.extend({prompts:N(rhe)}),ahe=o1.extend({name:I(),arguments:k(I(),I()).optional()}),t0=c1.extend({method:M(`prompts/get`),params:ahe}),n0=P({type:M(`text`),text:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),r0=P({type:M(`image`),data:G1,mimeType:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),i0=P({type:M(`audio`),data:G1,mimeType:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),ohe=P({type:M(`tool_use`),name:I(),id:I(),input:k(I(),j()),_meta:k(I(),j()).optional()}),she=P({type:M(`resource`),resource:ke([W1,K1]),annotations:J1.optional(),_meta:k(I(),j()).optional()}),a0=ke([n0,r0,i0,Y1.extend({type:M(`resource_link`)}),she]),che=P({role:q1,content:a0}),lhe=d1.extend({description:I().optional(),messages:N(che)}),uhe=u1.extend({method:M(`notifications/prompts/list_changed`),params:l1.optional()}),dhe=P({title:I().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),fhe=P({taskSupport:Ce([`required`,`optional`,`forbidden`]).optional()}),o0=P({...T1.shape,...w1.shape,description:I().optional(),inputSchema:P({type:M(`object`),properties:k(I(),n1).optional(),required:N(I()).optional()}).catchall(j()),outputSchema:P({type:M(`object`),properties:k(I(),n1).optional(),required:N(I()).optional()}).catchall(j()).optional(),annotations:dhe.optional(),execution:fhe.optional(),_meta:k(I(),j()).optional()}),s0=M1.extend({method:M(`tools/list`)}),phe=N1.extend({tools:N(o0)}),c0=d1.extend({content:N(a0).default([]),structuredContent:k(I(),j()).optional(),isError:A().optional()});c0.or(d1.extend({toolResult:j()}));const mhe=s1.extend({name:I(),arguments:k(I(),j()).optional()}),l0=c1.extend({method:M(`tools/call`),params:mhe}),hhe=u1.extend({method:M(`notifications/tools/list_changed`),params:l1.optional()});P({autoRefresh:A().default(!0),debounceMs:F().int().nonnegative().default(300)});const u0=Ce([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ghe=o1.extend({level:u0}),d0=c1.extend({method:M(`logging/setLevel`),params:ghe}),_he=l1.extend({level:u0,logger:I().optional(),data:j()}),vhe=u1.extend({method:M(`notifications/message`),params:_he}),yhe=P({hints:N(P({name:I().optional()})).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),bhe=P({mode:Ce([`auto`,`required`,`none`]).optional()}),xhe=P({type:M(`tool_result`),toolUseId:I().describe(`The unique identifier for the corresponding tool call.`),content:N(a0).default([]),structuredContent:P({}).loose().optional(),isError:A().optional(),_meta:k(I(),j()).optional()}),She=xe(`type`,[n0,r0,i0]),f0=xe(`type`,[n0,r0,i0,ohe,xhe]),Che=P({role:q1,content:ke([f0,N(f0)]),_meta:k(I(),j()).optional()}),whe=s1.extend({messages:N(Che),modelPreferences:yhe.optional(),systemPrompt:I().optional(),includeContext:Ce([`none`,`thisServer`,`allServers`]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(I()).optional(),metadata:n1.optional(),tools:N(o0).optional(),toolChoice:bhe.optional()}),The=c1.extend({method:M(`sampling/createMessage`),params:whe}),p0=d1.extend({model:I(),stopReason:ue(Ce([`endTurn`,`stopSequence`,`maxTokens`]).or(I())),role:q1,content:She}),m0=d1.extend({model:I(),stopReason:ue(Ce([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(I())),role:q1,content:ke([f0,N(f0)])}),Ehe=P({type:M(`boolean`),title:I().optional(),description:I().optional(),default:A().optional()}),Dhe=P({type:M(`string`),title:I().optional(),description:I().optional(),minLength:F().optional(),maxLength:F().optional(),format:Ce([`email`,`uri`,`date`,`date-time`]).optional(),default:I().optional()}),Ohe=P({type:Ce([`number`,`integer`]),title:I().optional(),description:I().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),khe=P({type:M(`string`),title:I().optional(),description:I().optional(),enum:N(I()),default:I().optional()}),Ahe=P({type:M(`string`),title:I().optional(),description:I().optional(),oneOf:N(P({const:I(),title:I()})),default:I().optional()}),jhe=ke([ke([P({type:M(`string`),title:I().optional(),description:I().optional(),enum:N(I()),enumNames:N(I()).optional(),default:I().optional()}),ke([khe,Ahe]),ke([P({type:M(`array`),title:I().optional(),description:I().optional(),minItems:F().optional(),maxItems:F().optional(),items:P({type:M(`string`),enum:N(I())}),default:N(I()).optional()}),P({type:M(`array`),title:I().optional(),description:I().optional(),minItems:F().optional(),maxItems:F().optional(),items:P({anyOf:N(P({const:I(),title:I()}))}),default:N(I()).optional()})])]),Ehe,Dhe,Ohe]),Mhe=ke([s1.extend({mode:M(`form`).optional(),message:I(),requestedSchema:P({type:M(`object`),properties:k(I(),jhe),required:N(I()).optional()})}),s1.extend({mode:M(`url`),message:I(),elicitationId:I(),url:I().url()})]),Nhe=c1.extend({method:M(`elicitation/create`),params:Mhe}),Phe=l1.extend({elicitationId:I()}),Fhe=u1.extend({method:M(`notifications/elicitation/complete`),params:Phe}),h0=d1.extend({action:Ce([`accept`,`decline`,`cancel`]),content:le(e=>e===null?void 0:e,k(I(),ke([I(),F(),A(),N(I())])).optional())}),Ihe=P({type:M(`ref/resource`),uri:I()}),Lhe=P({type:M(`ref/prompt`),name:I()}),Rhe=o1.extend({ref:ke([Lhe,Ihe]),argument:P({name:I(),value:I()}),context:P({arguments:k(I(),I()).optional()}).optional()}),g0=c1.extend({method:M(`completion/complete`),params:Rhe});function zhe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Bhe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Vhe=d1.extend({completion:se({values:N(I()).max(100),total:ue(F().int()),hasMore:ue(A())})}),Hhe=P({uri:I().startsWith(`file://`),name:I().optional(),_meta:k(I(),j()).optional()}),Uhe=c1.extend({method:M(`roots/list`),params:o1.optional()}),_0=d1.extend({roots:N(Hhe)}),Whe=u1.extend({method:M(`notifications/roots/list_changed`),params:l1.optional()});ke([A1,D1,g0,d0,t0,e0,X1,Z1,$1,Zme,$me,l0,s0,L1,z1,B1,H1]),ke([C1,j1,k1,Whe,I1]),ke([S1,p0,m0,h0,_0,R1,V1,F1]),ke([A1,The,Nhe,Uhe,L1,z1,B1,H1]),ke([C1,j1,vhe,the,Yme,hhe,uhe,I1,Fhe]),ke([S1,Ime,Vhe,lhe,ihe,Gme,Kme,Jme,c0,phe,R1,V1,F1]);var v0=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===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ghe(e.elicitations,n)}return new e(t,n,r)}},Ghe=class extends v0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function y0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Khe=Symbol(`Let zodToJsonSchema decide on which parser to use`),b0={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`},qhe=e=>typeof e==`string`?{...b0,name:e}:{...b0,...e},Jhe=e=>{let t=qhe(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 x0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function S0(e,t,n,r,i){e[t]=n,x0(e,t,r,i)}const C0=(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 w0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?C0(t,e.currentPath):t.join(`/`)}}function Yhe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==$.ZodAny&&(n.items=L0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&S0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&S0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(S0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),S0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Xhe(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?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function Zhe(){return{type:`boolean`}}function T0(e,t){return L0(e.type._def,t)}const Qhe=(e,t)=>L0(e.innerType._def,t);function E0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E0(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 $he(e,t)}}const $he=(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`:S0(n,`minimum`,r.value,r.message,t);break;case`max`:S0(n,`maximum`,r.value,r.message,t);break}return n};function ege(e,t){return{...L0(e.innerType._def,t),default:e.defaultValue()}}function tge(e,t){return t.effectStrategy===`input`?L0(e.schema._def,t):w0(t)}function nge(e){return{type:`string`,enum:Array.from(e.values)}}const rge=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function ige(e,t){let n=[L0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L0(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(rge(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 age(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 D0;const O0={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:()=>(D0===void 0&&(D0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),D0),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 k0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:S0(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`:j0(n,`email`,r.message,t);break;case`format:idn-email`:j0(n,`idn-email`,r.message,t);break;case`pattern:zod`:M0(n,O0.email,r.message,t);break}break;case`url`:j0(n,`uri`,r.message,t);break;case`uuid`:j0(n,`uuid`,r.message,t);break;case`regex`:M0(n,r.regex,r.message,t);break;case`cuid`:M0(n,O0.cuid,r.message,t);break;case`cuid2`:M0(n,O0.cuid2,r.message,t);break;case`startsWith`:M0(n,RegExp(`^${A0(r.value,t)}`),r.message,t);break;case`endsWith`:M0(n,RegExp(`${A0(r.value,t)}$`),r.message,t);break;case`datetime`:j0(n,`date-time`,r.message,t);break;case`date`:j0(n,`date`,r.message,t);break;case`time`:j0(n,`time`,r.message,t);break;case`duration`:j0(n,`duration`,r.message,t);break;case`length`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:M0(n,RegExp(A0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&j0(n,`ipv4`,r.message,t),r.version!==`v4`&&j0(n,`ipv6`,r.message,t);break;case`base64url`:M0(n,O0.base64url,r.message,t);break;case`jwt`:M0(n,O0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&M0(n,O0.ipv4Cidr,r.message,t),r.version!==`v4`&&M0(n,O0.ipv6Cidr,r.message,t);break;case`emoji`:M0(n,O0.emoji(),r.message,t);break;case`ulid`:M0(n,O0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:j0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:S0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:M0(n,O0.base64,r.message,t);break}break;case`nanoid`:M0(n,O0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function A0(e,t){return t.patternStrategy===`escape`?sge(e):e}const oge=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function sge(e){let t=``;for(let n=0;n<e.length;n++)oge.has(e[n])||(t+=`\\`),t+=e[n];return t}function j0(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}}})):S0(e,`format`,t,n,r)}function M0(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:N0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):S0(e,`pattern`,N0(t,r),n,r)}function N0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1217
+ `).filter(Boolean).find(t=>t.endsWith(`/${e}`));if(t)return(await r.raw(`rev-parse`,t)).trim()},a=async(e,t)=>(await r.raw(`ls-tree`,`-r`,`--name-only`,e,`--`,t)).trim().length>0,o=await i();return o!==void 0&&t!==void 0&&!await a(o,t)&&(await jn(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Cs=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function ws(e){try{let t=Vo(e.scope);if(!t)return;let n=cI(t);if(n.length===0)return;let r=mI(V(e.skillsRoot,e.name),e.name,t,n,`copy`,lI(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){Z.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Ts(e,t){if(t.ok){Y(e,200,Ar,t.body,{handler:`skill-import`});return}q(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 Es=BX({contentDir:s,skillsHome:ao,...M===void 0?{}:{projectDir:M},resolveSkillDirForRead:fo,parseFrontmatterDoc:Ua,attributeOkArtifactWrite:On,commitOkArtifactWrite:jn,shadowHeadSha:Ss,artifactWriterId:Cs,effectiveInstallMode:Do,signalFiles:()=>O?.(`files`)}),Ds=J(li,async(e,t,n)=>{let r=()=>{};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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 oO(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??jD(d);if(!p){q(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(cZ(t,p,`skill-import`))return;let m=await ND(p);r=m.cleanup,s=m.ref;let h=ZD(m.dir);if(h.length===0){q(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=>JD(e.dir)?.name===f)??h.find(e=>e.name===mt[f]);if(!e){q(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){q(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??ys(d)}catch(e){if(e instanceof gD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Es.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||gn(u))&&$F({source:u,skills:[d.body.name]},RF()),Ts(t,d)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Os=J(qe,async(e,t,n)=>{let r=()=>{};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(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 oO(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??jD(d);if(!f){q(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(cZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??ys(d),f.kind===`well-known`)a=f,o=await ED(f.origin);else{let e=await ND(f);r=e.cleanup,c=e.ref,s=ZD(e.dir)}}catch(e){if(e instanceof gD){q(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){q(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 ND({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof gD?`not-found`:`failed`,warnings:[],...e instanceof gD?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>XD(e.dir)?.name===t)??s.find(e=>e.name===mt[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Es.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){L(`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){L(`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||gn(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&$F({source:u,skills:e},RF())}Y(t,200,See,{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){q(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`}),ks=8*1024*1024,As=32*1024*1024;function js(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=V(e,n);return r!==e&&!r.startsWith(e+ql)?null:r}function Ms(e){return new Promise((t,n)=>{let r;try{r=(0,Ok.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:ks}})}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>As){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 Fs(e,t){return new Promise((n,r)=>{(0,kk.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=js(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>ks){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>As){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(R(n),{recursive:!0}),vs(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 Is(e,t){let n=nu(z(gu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){q(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=ro(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=Nk({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},oe);if(o.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Ms(e)}catch(e){q(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){q(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 Fs(c.data,n)}catch(e){q(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=js(n,e.relPath);if(!r){q(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(R(r),{recursive:!0}),vs(r,e.data)}let u=ZD(n);if(u.length===0){q(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){q(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];Ts(t,await Es.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Ls=J($a,async(e,t,n)=>{try{let e=uo(n.scope);if(!Qa(n.name,t,`skill-install`))return;if(n.scope===`project`&&!M){q(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=Vo(n.scope),i=V(e,n.name),a=n.scope===`project`?s:ao,o=(n.scope===`project`?BI(s):VI(ao)).find(e=>e.name===n.name),c=o?V(a,o.dir):i;if(!H(c)){q(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 vt(n.scope===`project`?`${B(a,c).split(ql).join(`/`)}/SKILL`:Hr(n.scope,n.name));let l=sI(c,n.name);if(!l.ok){q(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){q(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=oo.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:q(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:q(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:q(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`:q(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o.hosts.filter(sa),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){q(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 oo.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`?q(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`}):q(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(sa),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await oo.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:u});if(!e.ok){q(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}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?M:ao;if(!e){q(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 Zn.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?q(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):q(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||O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?M:ao;if(!e){q(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 Zn.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:q(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:q(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:q(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`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){q(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:ao,s=await Zn.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:c,canonicalHash:o.contentHash});if(!s.ok)switch(s.kind){case`invalid-location`:q(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:q(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`:q(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`:q(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)}`)}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?vr.filter(e=>f?.some(t=>t===e)):[...vr]:f===void 0?cI(r):vr.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?M:ao,s=d===void 0?Do(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await oo.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?q(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}):q(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}O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await oo.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:s,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){q(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=aI(PN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&xI(n.name,r,v,lI(n.scope));let y=z(r,...PD),b=H(y)?U(y,`utf-8`):null,x=b===null?null:RD(b);b!==null&&x===null&&Z.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=mI(c,n.name,r,h,C,lI(n.scope));w.length===0?await LN(r,n.name):await IN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),O?.(`files`),Y(t,200,Vr,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Rs=J(An,async(e,t,n)=>{try{if(!Qa(n.name,t,`skill-uninstall`))return;let e=Vo(n.scope);if(!e){q(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 Ho(e,n.name,n.scope);O?.(`files`),Y(t,200,Mo,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),zs=bU({GET:J(lo,async(e,t)=>{try{let e=cI(M??``),n=(e,t)=>{let n=XX(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};Y(t,200,yt,{targets:e,configured:!1,folders:[...M?VX(s,PI(s,`project`)).map(e=>({...e,scope:`project`,...n(s,e)})):[],...VX(ao,PI(ao,`global`)).map(e=>({...e,scope:`global`,...n(ao,e)}))]},{handler:`skill-targets-get`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(aee,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?s:ao;if(e.scope===`project`&&!M){q(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){q(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await ZX(r,i.join(`/`)),O?.(`files`),Y(t,200,Zt,{targets:cI(M??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(PI(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){q(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?GX({base:r,folderRel:e.root,targetRootRel:a}):KX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){q(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await YX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),O?.(`files`),Y(t,200,Zt,{targets:cI(M??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Bs=J(Be,async(e,t,n)=>{try{let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Qa(n.name,t,`skill-restore`)||Lo(n.name,t,`skill-restore`))return;if(n.scope===`global`){q(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=S?.current;if(!r){q(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 uZ({shadow:r,contentDir:s,contentRoot:ee??`.`,name:n.name,version:n.version,skillDirRel:Oo(n.name)});if(!i.ok){Co(t,i,`skill-restore`);return}let a=[],o=sI(V(s,Oo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),On(e,Dn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await jn(`skill-restore`),O?.(`files`),Y(t,200,Mi,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Vs=J(dee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!Qa(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?ao:s,{root:a,dirRel:o,realDir:c}=Yo(n.scope,n.name),l=!o.startsWith(`${La}/`);if(c===null||!H(V(i,o,`SKILL.md`))){q(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=z(n.scope===`global`?ao:M,...PD),d=bs(u).skills[n.name];if(!d){let e=VD(n.name,XD(V(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:_pe(V(a,n.name))})??Fo(i,n.name);e&&(d=e)}if(!d){q(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 hq(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),Y(t,200,Ri,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=mt[e],a=await oO(d.source,e).catch(async e=>{if(i===void 0)throw e;return oO(d.source,i)}),o=a?.source??GO(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??jD(o);if(!c){q(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(cZ(t,c,`skill-reimport`))return;let l=await ND(c);r=l.cleanup,f=l.ref;let u=ZD(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>XD(e.dir)?.name===n.name)??u.find(e=>e.name===mt[s??n.name])??(u.length===1?u[0]:void 0);if(!m){q(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=YD(m.dir);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=XD(m.dir)}catch(e){if(e instanceof gD){q(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){q(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=zX(p);if(h){q(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=XD(V(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){Y(t,200,Ri,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Ua(p.skillMd).body;if(n.dryRun){let e=XD(V(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&M)try{let e=Ns({baseDir:M,timeout:{block:15e3}}),t=B(M,V(a,n.name)).split(ql).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}Y(t,200,Ri,{name:n.name,updated:!0,source:d.source,localBody:Ua(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await Bt(e,`deleted-upstream`)}let x=xj({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){q(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=wj({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:RX});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Tj({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(On(e,Dn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await jn(`skill-reimport`));let C=xs(a,n.name),w=n.scope===`project`?await Ss(Cs(e),o):void 0;await hq(u,e=>zD(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await ws({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),O?.(`files`),Y(t,200,Ri,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Hs=J(tn,async(e,t,n)=>{try{if(!M){q(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=Nk(n,oe);if(e.kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!Qa(n.name,t,`skill-revert`)||Lo(n.name,t,`skill-revert`))return;if(n.scope===`global`){q(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=z(M,...PD),i=bs(r).skills[n.name];if(!i?.baselineRef){q(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=S?.current;if(!a){q(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 uZ({shadow:a,contentDir:s,contentRoot:ee??`.`,name:n.name,version:i.baselineRef,skillDirRel:Oo(n.name)});if(!o.ok){Co(t,o,`skill-revert`);return}On(e,Dn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await jn(`skill-revert`);let c=V(s,Oo(n.name),`..`),l=xs(c,n.name);await hq(r,e=>zD(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),c===uo(`project`)&&await ws({skillsRoot:c,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),O?.(`files`),Y(t,200,ln,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Ws(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Gs(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Ks(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function qs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Ys=IX({contentDir:s,projectDir:M,getAllFilesIndex:f,getFileIndexGeneration:m,getSearchMaxEntries:Tpe,semanticSearch:be,getSemanticSimilarityFloor:xe,ready:he,getProjectSkillsRoot:()=>uo(`project`),parseFrontmatterDoc:Ua});Ys.prewarm();let Xs=bU({GET:J(lo,Wz(async(e,t)=>{let n=nte(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Ws(n.get(`intent`)),o=zo(n.get(`ranking`)),s=Gs(n.get(`scope`)??n.get(`scopes`)),c=Ks(n.get(`semantic`)),l=qs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}Y(t,200,Va,await Ys.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Pee,Wz(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Ws(n.intent),a=zo(n.ranking),o=Gs(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Ks(n.semantic),l=qs(n.source);if(r.length>200){q(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}Y(t,200,Va,await Ys.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),Zs=J(lo,Wz(async(e,t)=>{Y(t,200,wo,{...await XF(pu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function Qs(e,t){if(r(e,t,{handler:`handoff`}))try{await kue(e,t,{contentDir:s,platform:process.platform,isSchemeRegistered:Je.probeWithCache})}catch(n){t.headersSent||(Z.error({err:n,requestId:Qx(e)},`[handoff] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function $s(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await gN(e,t,{contentDir:s,platform:process.platform})}catch(n){t.headersSent||(Z.error({err:n,requestId:Qx(e)},`[spawn-cursor] route wrapper failed`),q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let ec=J(xr,async(e,t,n)=>{try{if(!M){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Rde(e,n.kind)){sF(`invalid-path`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`invalid-path`},{handler:oF});return}let r=Ude(M);if(r===null){if(dF(M).kind===`no-remote`){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}sF(`detached-head`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`detached-head`},{handler:oF});return}let i=dF(M);if(i.kind===`no-remote`){sF(`no-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`no-remote`},{handler:oF});return}if(i.kind===`non-github`){sF(`non-github-remote`,{kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`non-github-remote`},{handler:oF});return}if(!Jde(M,r)){sF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),Y(t,200,Cn,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:oF});return}let a=sQ(M,s);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&L(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let c;if(n.kind===`doc`)c=zde(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;c=Bde(i.host,i.owner,i.repo,r,e)}let l=`https://openknowledge.ai/d/${Wu(c)}`,u=await Vde(M,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);sF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),Y(t,200,Cn,{ok:!0,shareUrl:l,sharedUrl:c,branch:r,freshness:u},{handler:oF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:oF,cause:e})}},{handler:oF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oF})}),tc=J(lo,async(e,t)=>{try{if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:hz});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(!Ki(r)){q(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:hz});return}if(!pz(i,a)){q(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:hz});return}Y(t,200,oee,await mz(M,r,i,a),{handler:hz})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hz,cause:e})}},{handler:hz,method:`GET`,skipBodyParse:!0}),nc=J(Ti,async(e,t,n)=>{try{if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:CF});return}if(!pz(n.path,n.kind)){q(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:CF});return}let e=sQ(M,s);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;Y(t,200,wee,await nfe(M,n.branch,r,n.kind),{handler:CF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:CF,cause:e})}},{handler:CF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:CF})}),rc=J(hr,async(e,t,n)=>{if(Nk(n,oe).kind===`invalid-summary`){q(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:bz});return}if(!M){q(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:bz});return}try{Y(t,200,lr,await Ps(()=>Sz(M,n.branch,{fastForward:n.fastForward===!0})),{handler:bz})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:bz,cause:e})}},{handler:bz,method:`POST`});async function ic(e){let[t,...n]=re,r=[...n,...e];return await new Promise((e,n)=>{let i=Rl(t,r,cN({...$r,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},gF),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 ${gF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=SF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Z.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 ac=J(lo,async(e,t)=>{if(!je.tryAcquire(`/api/share/publish/owners`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:pF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ic([`share`,`owners`,`--json`]),n=Yde(yF(e));xF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),Y(t,200,$ee,n,{handler:pF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:pF,cause:e})}finally{je.release(`/api/share/publish/owners`)}},{handler:pF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:pF})}),oc=J(lo,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!vF(r)||!_F(i)){q(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:mF});return}if(!je.tryAcquire(`/api/share/publish/name-check`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:mF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await ic([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Xde(yF(e));xF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),Y(t,200,Fee,n,{handler:mF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:mF,cause:e})}finally{je.release(`/api/share/publish/name-check`)}},{handler:mF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:mF})}),sc=J(oa,async(e,t,n)=>{if(!M){xF(`publish-create`,`no-project`),Y(t,200,Aa,{ok:!1,error:`no-project`},{handler:hF});return}if(!vF(n.owner)||!_F(n.name)){q(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:hF});return}if(!je.tryAcquire(`/api/share/publish`)){q(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:hF,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 ic(e),i=$de(yF(r));xF(`publish-create`,i.ok?`ok`:i.error),i.ok&&j?.()?.refreshRemote().catch(()=>{}),Y(t,200,Aa,i,{handler:hF})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:hF,cause:e})}finally{je.release(`/api/share/publish`)}},{handler:hF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:hF})}),cc=J(uee,async(e,t,n)=>{try{let e=L(`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{}Y(t,200,cn,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){q(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`})}),lc=M?oA(M):null;async function uc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Ise(e.headers),previewUrl:null,port:lc?Js(lc)?.port??0:0,singleFile:De};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}Y(t,200,Ao,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function dc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Ae?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}Y(t,200,me,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}q(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let fc=`local-op-embeddings-set-key`,pc=`local-op-embeddings-clear-key`,mc=`/api/local-op/embeddings`;function hc(){let e=we?.();return{projectDir:M??s,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let gc=J(Nee,async(e,t,n)=>{if(!je.tryAcquire(mc)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:fc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=hc();await new gM(Se).setForProject(e,r,n.key),be?.reloadCredential(),Y(t,200,Fe,{keyPresent:!0},{handler:fc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:fc,cause:e})}finally{je.release(mc)}},{handler:fc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:fc})}),_c=J(lo,async(e,t)=>{if(!je.tryAcquire(mc)){q(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:pc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=hc();await new gM(Se).clearForProject(e,n),be?.reloadCredential(),Y(t,200,Fe,{keyPresent:!1},{handler:pc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:pc,cause:e})}finally{je.release(mc)}},{handler:pc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:pc})}),vc=`local-op-embeddings-test`,yc=`/api/local-op/embeddings/test`,bc=J(lo,async(e,t)=>{if(!je.tryAcquire(yc)){q(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:vc,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 lM(new gM(Se),M??s,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Mle({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};Y(t,200,Qee,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:vc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:vc,cause:e})}finally{je.release(yc)}},{handler:vc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vc})}),xc=J(lo,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(be){let t=be.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=we?.()?.baseUrl??`https://api.openai.com/v1`,o=await lM(new gM(Se),M??s,a),c=o.apiKey!==null,u=!c&&o.keyless,d=c?o.source:null,f=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of l())!Vx(e)&&!Hx(e)&&!qa(e)&&(p+=1);Y(t,200,aa,{enabled:e,keyPresent:c,keyNotRequired:u,keySource:d,keyHint:f,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Sc=0;function Cc(){Sc+=1,O?.(`lint-config`)}let wc=()=>`${Sc} ${t.getActiveBranch()}`;async function Tc(e,t){let n=Te?.()??Ze;try{let r=await ra(e,UP(s,n,{docName:t,projectDir:M??s,onProblem:e=>Z.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ee?.()??`warning`;if(D&&a!==`off`&&!qx(t)){await Ot(t,e,`lint-validation`);let r=nF({projectDir:M??s,contentDir:s,baseConfig:n,derivedDocumentIndex:D,linksValidation:a,admittedDocNames:Tt,docFilePathFor:e=>iQ(s,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:iQ(s,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{}}))}catch(e){return Z.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ec(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=KP({projectDir:M??s,contentDir:s});return hP(t.schemas,n)}let Dc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!hQ(n))){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Te?.()??Ze,i=[],a=BP(s,n??void 0,e=>i.push(e)),o=HP(M??s,VP(r,a),e=>i.push(e));n===null&&i.push(...Ec(o)),Y(t,200,hi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Oc=J(So,async(e,t,n)=>{let r;try{r=tF(V(s),n.ruleId,n.value)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){q(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}Cc();try{let e=Te?.()??Ze,n=[],r=BP(s,void 0,e=>n.push(e)),i=HP(M??s,VP(e,r),e=>n.push(e));n.push(...Ec(i)),Y(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){q(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`}),kc=J(Lee,async(e,t,n)=>{let r;try{let e=V(M??s),t=n.parentPath??[];r=n.delete?Tde(e,n.file):n.field!==void 0&&n.removeField?Cde(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?wde(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?xde(e,n.file,n.field,n.constraint,t):Sde(e,n.file)}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){q(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`)&&O?.(`files`),Cc();try{let e=Te?.()??Ze,n=[],r=BP(s,void 0,e=>n.push(e)),i=HP(M??s,VP(e,r),e=>n.push(e));n.push(...Ec(i)),Y(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){q(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`}),Ac=J(lo,async(e,t)=>{try{let e=V(M??s),{schemas:n,truncated:r}=Xue(e),i=new Set(n),a=!1;if(de!==void 0){let t=JZ({contentDir:s,contentFilter:de,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&Ui(a)){let t=B(e,V(s,a));!t.startsWith(`..`)&&!Wl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));Y(t,200,Wee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),jc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Mc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!hQ(n)){q(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=iQ(s,n);if(r===null){q(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Te?.()??Ze,a=[],o=await GP({projectDir:M??s,contentDir:s,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:jc});Y(t,200,si,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof ZM){q(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Nc=new dP,Pc=sZ();function Fc(e,t,n){let r=`${n} ${wc()} ${t??``}`;return Pc.run(r,()=>kde(e,{targetPath:t})).promise}function Ic(e,t){q(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Lc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!YZ(r)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Te?.()??Ze;Y(t,200,Xi,await qP({projectDir:M??s,contentDir:s,baseConfig:i,targetPath:r,liveSourceFor:jc,cache:Nc,auditGeneration:wc}),{handler:`lint-audit`})}catch(e){if(e instanceof WP){Ic(t,`lint-audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Rc=J(lo,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YZ(i)){q(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YZ(o)){q(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=iQ(s,o)??`${o}.md`}let c=Te?.()??Ze,l=await Fc(nF({projectDir:M??s,contentDir:s,baseConfig:c,liveSourceFor:jc,derivedDocumentIndex:D??null,linksValidation:Ee?.(),admittedDocNames:Tt,docFilePathFor:e=>iQ(s,e),cache:Nc,auditGeneration:wc}),i,dP.fingerprintConfig(c));if(n.searchParams.get(`counts`)===`1`){Y(t,200,Eee,Ode(l),{handler:`audit`});return}Y(t,200,mo,l,{handler:`audit`})}catch(e){if(e instanceof WP){Ic(t,`audit`);return}q(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),zc=J(Or,async(t,n,r)=>{try{let t=ZZ(r.docName,n,`lint-fix`);if(t===null)return;let i=ut(t),a=Nk(r,oe);if(a.kind===`invalid-summary`){q(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let c=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?c:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Vx(i)||Hx(i)){q(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=iQ(s,i);if(f===null){q(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}oN(V(s,f),s);let p=Te?.()??Ze,{stored:m}=xn(a.summary),h=await o.getSession(i,c,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await _de({projectDir:M??s,contentDir:s,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Yr(d),n=Wr[t]??Hi(u??c);k?.setPresence(c,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{Fw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,Nw(h))},h.origin),a.kind!==`anonymous`&&Wj(i,c,l,u,void 0,a.kind===`agent`?bn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{k?.touchMode(c,`idle`)}let t=await vt(i);if(t?.kind===`failure`){bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){xt(n,`lint-fix`);return}_t(i,`lint-fix`);try{b=await ra(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Z.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;Y(n,200,Za,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof ZM){q(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof oS){sS(n,e,`lint-fix`);return}if(e instanceof dS){pS(n,e,`lint-fix`);return}if(e instanceof Gw){q(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Z.error({err:e},`[lint-fix] handler failed`),q(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Bc=`link-preview`,Vc=new OW({cacheDir:De?null:V(M??s,`.ok`,`local`,`link-previews`)}),Hc=null,Uc=()=>(Hc??=Vc.init(),Hc),Wc=Oe??yW;async function Gc(e){let t=await Wc(e);return t.ok?{ok:!0,metadata:await wW({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Wc})}:{ok:!1,reason:t.reason}}let Kc=()=>{try{return ke?.()===!0}catch{return!1}},qc=J(Wi,async(e,t,n)=>{try{if(!Kc()){Z.debug({outcome:`disabled`},`[link-preview] request outcome`),Y(t,200,Ka,{ok:!1,reason:`disabled`},{handler:Bc});return}await Uc();let e=!1,r=await Vc.load(n.url,()=>(e=!0,Gc(n.url)));Vc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Z.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),Y(t,200,Ka,i,{handler:Bc})}catch(e){q(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Bc,cause:e})}},{handler:Bc,method:`POST`,preBodyGate:(e,t)=>{let n=jW({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?q(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Bc}):q(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Bc}),!1)}}),Jc=qse({service:Qe,getPrincipal:oe,onChanged:()=>O?.(`comments`)}),Yc=bU({GET:Jc.list,POST:Jc.create},{handler:`comments`}),Xc=bU({GET:Jc.read,POST:Jc.mutate,DELETE:Jc.remove},{handler:`comment`}),{handleSkillsSearch:Zc,handleSkillsPopular:Qc,handleSkillsPublisher:$c,handleSkillsDetail:el,handleSkillsPreview:tl,handleSkillsDiscover:nl,handleSkillsResolveRef:rl}=npe({log:Z,skillsHome:ao,projectDir:M,contentDir:s,resolveSkillDirForRead:fo}),il={"/api/config":uc,"/api/config/diagnostics":dc,"/api/comments":Yc,"/api/comment":Xc,"/api/asset":Sr,"/api/asset-text":Nr,"/api/comment-counts":Rn,"/api/link-preview":qc,"/api/folder-config":Ra,"/api/template":Ya,"/api/template/import":Xa,"/api/templates":Ha,"/api/skill":rs,"/api/skill-file":hs,"/api/skill-file/rename":_s,"/api/skills":Wo,"/api/skills/installed":In,"/api/skills/search":Zc,"/api/skills/popular":Qc,"/api/skills/publisher":$c,"/api/skills/detail":el,"/api/skills/preview":tl,"/api/skills/discover":nl,"/api/skills/resolve-ref":rl,"/api/skill/import":Ds,"/api/skills/import-bulk":Os,"/api/skill/edit-external":es,"/api/skill/duplicate":ns,"/api/skill/move-scope":ts,"/api/skill-upload":Is,"/api/skill/install":Ls,"/api/skill/uninstall":Rs,"/api/skill/restore":Bs,"/api/skill/reimport":Vs,"/api/skill/revert":Hs,"/api/skill-targets":zs,"/api/search":Xs,"/api/semantic-status":xc,"/api/lint/config":Dc,"/api/lint/markdownlint-config":Oc,"/api/lint/frontmatter-schema":kc,"/api/lint/frontmatter-schemas":Ac,"/api/lint":Mc,"/api/lint/audit":Lc,"/api/lint/fix":zc,"/api/audit":Rc,"/api/create-page":Fr,"/api/create-folder":Lr,"/api/duplicate-path":Rr,"/api/rename-path":zr,"/api/delete-path":Br,"/api/trash/cleanup":Ur,"/api/upload":Gr,"/api/agent-write":Mn,"/api/agent-write-md":Nn,"/api/agent-write-batch":Pn,"/api/frontmatter-patch":Fn,"/api/agent-patch":Vn,"/api/agent-undo":Hn,"/api/agent-activity":Un,"/api/agent-burst-diff":Wn,"/api/save-version":Qn,"/api/history":$n,"/api/rollback":tr,"/api/__embed-detect":cr,"/api/server-info":nr,"/api/acp/catalog":ar,"/api/share/construct-url":ec,"/api/share/target-status":nc,"/api/git/branch-info":tc,"/api/git/checkout":rc,"/api/share/publish/owners":ac,"/api/share/publish/name-check":oc,"/api/share/publish":sc,"/api/principal":sr,"/api/rescue":Pr,"/api/workspace":ur,"/api/sync/status":ga,"/api/sync/trigger":va,"/api/sync/conflicts":xa,"/api/sync/conflict-content":Ca,"/api/sync/resolve-conflict":Sa,"/api/local-op/clone":ri,"/api/local-op/ok-init":fi,"/api/local-op/auth/login":Ii,"/api/local-op/auth/status":ea,"/api/local-op/auth/pat":na,"/api/local-op/auth/gh-login":Vi,"/api/local-op/auth/cancel":Yi,"/api/local-op/auth/repos":la,"/api/local-op/auth/signout":fa,"/api/local-op/auth/set-identity":ha,"/api/local-op/embeddings/set-key":gc,"/api/local-op/embeddings/clear-key":_c,"/api/local-op/embeddings/test":bc,"/api/installed-agents":Ma,"/api/spawn-cursor":$s,"/api/handoff":Qs,"/api/install-skill":Oa,"/api/skill/install-state":Zs,"/api/seed/plan":wa,"/api/seed/apply":Ea,"/api/seed/packs":Da,"/api/client-logs":cc};x&&(il[`/api/test-reset`]=Kn,il[`/api/test-flush-git`]=Gn,il[`/api/test-rescan-backlinks`]=qn,il[`/api/test-rescan-files`]=Jn);let al=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),ol=[`/api/local-op/`],sl=Uz({log:Z,remotePublicHost:n,ephemeral:De,table:{resolve(e){let t=il[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await er(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>al.has(e)||ol.some(t=>e.startsWith(t))}}),cl=gU({hocuspocus:a,derivedDocumentIndex:D,getFileIndex:l,isSafeDocName:hQ,readPageTitleForDocName:tt,readPageTitleForLinkedDocName:nt,readFrontmatterMetadataForLinkedDocName:at,collectAdmittedDocNames:Tt,resolveAlias:ut,respondToDerivedIndexQueryFailure:At}),ll=[cl,xU({hocuspocus:a,agentPresenceBroadcaster:k,isAllowedWorkspaceHostHeader:i,log:Z}),Pe],ul=ll.flatMap(e=>[...e.paths]);UH(ul,il);let dl=ll.map(e=>Uz({log:Z,remotePublicHost:n,ephemeral:De,table:e.table})),fl={paths:ul,dispatch:async(e,t)=>{for(let n of dl)if(await n(e,t))return!0;return!1}},pl=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`]);for(let e of pl)if(il[e]===void 0&&cl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await sl(e,t)},nativeApi:fl,localApi:yU({resolve:e=>{if(!pl.has(e))return;let t=il[e];return t===void 0?cl.table.resolve(e)?.dispatch:t}})}}function _Q(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a}=e;return(e,o,s)=>{let c;try{c=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return s()}let l=Ul(c).slice(1).toLowerCase(),u=l===`md`||l===`mdx`;if(!c||t.isPathIgnored(c)||!u&&!i.has(l))return s();o.setHeader(`X-Content-Type-Options`,`nosniff`);let d=hX(l,r);u||o.setHeader(`Content-Disposition`,d.disposition),d.csp!==null&&o.setHeader(`Content-Security-Policy`,d.csp),d.sandboxedHtml&&o.setHeader(`Cache-Control`,`no-store`),n(e,o,()=>{if(o.headersSent)return;let e=ee.has(l);if(!e&&(i.has(l)||a.has(l))){o.statusCode=404,o.end();return}e&&(o.removeHeader(`Content-Security-Policy`),o.removeHeader(`Content-Disposition`),o.removeHeader(`X-Content-Type-Options`),o.removeHeader(`Cache-Control`)),s()})}}function vQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Bpe(e){let t;try{t=iu(e.contentDir,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ax(n.name,c)&&e.basenameIndex.add(n.name)}async function yQ(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=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=nN(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await yu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Su(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!rN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Cu(i)}catch(t){let n=vQ(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()&&Ax(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s);continue}if(c.isDirectory()){if(n.has(c.ino))continue;n.add(c.ino),await r(a);continue}c.isFile()&&Ax(a,u)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const bQ=P({principalId:I().optional(),tabSessionId:I().optional(),expectedServerInstanceId:I().optional(),expectedBranch:I().optional(),expectedDocLineageEpoch:I().optional(),clientProtocolVersion:F().optional(),clientRuntimeVersion:I().optional(),clientKind:I().optional()}).loose(),xQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function SQ(e){return xQ.includes(e)}function CQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Vpe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!SQ(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 wQ=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=CQ(e,this.payload)}};function TQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=bQ.safeParse(t);return n.success?n.data:void 0}var EQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const DQ=L(`conflict-storage`);var OQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(oA(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!H(this.storePath)){this.conflicts=[];return}try{let e=U(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){DQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){DQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);H(e)||tu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return du(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return DQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-B24ZRv9k.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!rN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);WI(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),DQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Pb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){DQ.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}),DQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=V(this.projectDir),a=V(i,e.file);if(!rN(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(WI(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-B24ZRv9k.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);WI(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:H(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Hpe(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 Upe(e,t){let n=oA(e);try{tu(n,{recursive:!0}),du(z(n,cr),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Os(e);tu(R(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`};du(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const kQ=new Map;let AQ=!1;function Wpe(e,t){try{let n=Hpe(e,t);for(let e of kQ.keys())Upe(e,n)}catch{}}function Gpe(e){kQ.set(e,(kQ.get(e)??0)+1),AQ||(AQ=!0,process.on(`uncaughtExceptionMonitor`,Wpe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=kQ.get(e)??0;n<=1?kQ.delete(e):kQ.set(e,n-1)}}}function jQ(e){let t=e.scheduler??Ra,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function MQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NQ(e){if(!H(e))return{};let t;try{t=(0,Dk.parse)(U(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(!MQ(t))return{};let n=t.telemetry;if(!MQ(n))return{};let r=n.localSink;return MQ(r)?r:{}}function PQ(e){return typeof e==`boolean`?e:void 0}function Kpe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function FQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function IQ(e){if(MQ(e))return Kpe(e.maxBytes)}function qpe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=NQ(Yo(`project`,e.projectDir)),n=NQ(Yo(`project-local`,e.projectDir));if((PQ(n.enabled)??PQ(t.enabled)??!0)===!1)return null;let r=IQ(n.spans)??IQ(t.spans)??52428800,i=IQ(n.logs)??IQ(t.logs)??26214400,a=FQ(n.attributeDenylist)??FQ(t.attributeDenylist)??Te;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var LQ;(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})(LQ||={});var Jpe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Jpe||={});const RQ=LQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),zQ=e=>{switch(typeof e){case`undefined`:return RQ.undefined;case`string`:return RQ.string;case`number`:return Number.isNaN(e)?RQ.nan:RQ.number;case`boolean`:return RQ.boolean;case`function`:return RQ.function;case`bigint`:return RQ.bigint;case`symbol`:return RQ.symbol;case`object`:return Array.isArray(e)?RQ.array:e===null?RQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?RQ.promise:typeof Map<`u`&&e instanceof Map?RQ.map:typeof Set<`u`&&e instanceof Set?RQ.set:typeof Date<`u`&&e instanceof Date?RQ.date:RQ.object;default:return RQ.unknown}},Q=LQ.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 BQ=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,LQ.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()}};BQ.create=e=>new BQ(e);const VQ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===RQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,LQ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${LQ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${LQ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${LQ.joinValues(e.options)}, received '${e.received}'`;break;case Q.invalid_arguments:n=`Invalid function arguments`;break;case Q.invalid_return_type:n=`Invalid function return type`;break;case Q.invalid_date:n=`Invalid date`;break;case Q.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}"`:LQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Q.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 Q.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 Q.custom:n=`Invalid input`;break;case Q.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Q.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Q.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,LQ.assertNever(e)}return{message:n}};let Ype=VQ;function HQ(){return Ype}const UQ=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 WQ(e,t){let n=HQ(),r=UQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===VQ?void 0:VQ].filter(e=>!!e)});e.common.issues.push(r)}var GQ=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 KQ;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 KQ;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 KQ=Object.freeze({status:`aborted`}),qQ=e=>({status:`dirty`,value:e}),JQ=e=>({status:`valid`,value:e}),YQ=e=>e.status===`aborted`,XQ=e=>e.status===`dirty`,ZQ=e=>e.status===`valid`,QQ=e=>typeof Promise<`u`&&e instanceof Promise;var $Q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})($Q||={});var e$=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 t$=(e,t)=>{if(ZQ(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 BQ(e.common.issues);return this._error=t,this._error}}};function n$(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 r$=class{get description(){return this._def.description}_getType(e){return zQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new GQ,ctx:{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(QQ(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:zQ(e)};return t$(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:zQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ZQ(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=>ZQ(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:zQ(e)},r=this._parse({data:e,path:n.path,parent:n});return t$(n,await(QQ(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:Q.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 F$({schema:this,typeName:$.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 I$.create(this,this._def)}nullable(){return L$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return y$.create(this)}promise(){return P$.create(this,this._def)}or(e){return S$.create([this,e],this._def)}and(e){return T$.create(this,e,this._def)}transform(e){return new F$({...n$(this._def),schema:this,typeName:$.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new R$({...n$(this._def),innerType:this,defaultValue:t,typeName:$.ZodDefault})}brand(){return new V$({typeName:$.ZodBranded,type:this,...n$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new z$({...n$(this._def),innerType:this,catchValue:t,typeName:$.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return H$.create(this,e)}readonly(){return U$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Xpe=/^c[^\s-]{8,}$/i,Zpe=/^[0-9a-z]+$/,Qpe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$pe=/^[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,eme=/^[a-z0-9_-]{21}$/i,tme=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nme=/^[-+]?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)?)??$/,rme=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let i$;const ime=/^(?:(?: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])$/,ame=/^(?:(?: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])$/,ome=/^(([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]))$/,sme=/^(([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])$/,cme=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,lme=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a$=`((\\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])))`,ume=RegExp(`^${a$}$`);function o$(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 dme(e){return RegExp(`^${o$(e)}$`)}function fme(e){let t=`${a$}T${o$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function pme(e,t){return!!((t===`v4`||!t)&&ime.test(e)||(t===`v6`||!t)&&ome.test(e))}function mme(e,t){if(!tme.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 hme(e,t){return!!((t===`v4`||!t)&&ame.test(e)||(t===`v6`||!t)&&sme.test(e))}var s$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==RQ.string){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.string,received:t.parsedType}),KQ}let t=new GQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.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),WQ(n,{code:Q.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?WQ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&WQ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)rme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)i$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),i$.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)$pe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)eme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Xpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Zpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Qpe.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ulid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),WQ(n,{validation:`url`,code:Q.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),WQ(n,{validation:`regex`,code:Q.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),WQ(n,{code:Q.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),WQ(n,{code:Q.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?fme(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?ume.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?dme(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?nme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?pme(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?mme(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?hme(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?cme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?lme.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Q.invalid_string,...$Q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...$Q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...$Q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...$Q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...$Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...$Q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...$Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...$Q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...$Q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...$Q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...$Q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...$Q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...$Q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...$Q.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,...$Q.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,...$Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...$Q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...$Q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...$Q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...$Q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...$Q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...$Q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...$Q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...$Q.errToObj(t)})}nonempty(e){return this.min(1,$Q.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}};s$.create=e=>new s$({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...n$(e)});function gme(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 c$=class e extends r${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)!==RQ.number){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.number,received:t.parsedType}),KQ}let t,n=new GQ;for(let r of this._def.checks)r.kind===`int`?LQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.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),WQ(t,{code:Q.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),WQ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?gme(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Q.not_finite,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:$Q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:$Q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:$Q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:$Q.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`&&LQ.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)}};c$.create=e=>new c$({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...n$(e)});var l$=class e extends r${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)!==RQ.bigint)return this._getInvalidInput(e);let t,n=new GQ;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),WQ(t,{code:Q.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),WQ(t,{code:Q.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),WQ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.bigint,received:t.parsedType}),KQ}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.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:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.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}};l$.create=e=>new l$({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...n$(e)});var u$=class extends r${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==RQ.boolean){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.boolean,received:t.parsedType}),KQ}return JQ(e.data)}};u$.create=e=>new u$({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...n$(e)});var d$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==RQ.date){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.date,received:t.parsedType}),KQ}if(Number.isNaN(e.data.getTime()))return WQ(this._getOrReturnCtx(e),{code:Q.invalid_date}),KQ;let t=new GQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Q.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),WQ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):LQ.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:$Q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:$Q.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)}};d$.create=e=>new d$({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...n$(e)});var f$=class extends r${_parse(e){if(this._getType(e)!==RQ.symbol){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.symbol,received:t.parsedType}),KQ}return JQ(e.data)}};f$.create=e=>new f$({typeName:$.ZodSymbol,...n$(e)});var p$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.undefined,received:t.parsedType}),KQ}return JQ(e.data)}};p$.create=e=>new p$({typeName:$.ZodUndefined,...n$(e)});var m$=class extends r${_parse(e){if(this._getType(e)!==RQ.null){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.null,received:t.parsedType}),KQ}return JQ(e.data)}};m$.create=e=>new m$({typeName:$.ZodNull,...n$(e)});var h$=class extends r${constructor(){super(...arguments),this._any=!0}_parse(e){return JQ(e.data)}};h$.create=e=>new h$({typeName:$.ZodAny,...n$(e)});var g$=class extends r${constructor(){super(...arguments),this._unknown=!0}_parse(e){return JQ(e.data)}};g$.create=e=>new g$({typeName:$.ZodUnknown,...n$(e)});var _$=class extends r${_parse(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.never,received:t.parsedType}),KQ}};_$.create=e=>new _$({typeName:$.ZodNever,...n$(e)});var v$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.void,received:t.parsedType}),KQ}return JQ(e.data)}};v$.create=e=>new v$({typeName:$.ZodVoid,...n$(e)});var y$=class e extends r${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==RQ.array)return WQ(t,{code:Q.invalid_type,expected:RQ.array,received:t.parsedType}),KQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(WQ(t,{code:e?Q.too_big:Q.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&&(WQ(t,{code:Q.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&&(WQ(t,{code:Q.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 e$(t,e,t.path,n)))).then(e=>GQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new e$(t,e,t.path,n)));return GQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:$Q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:$Q.toString(n)}})}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...n$(t)});function b$(e){if(e instanceof x$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=I$.create(b$(r))}return new x$({...e._def,shape:()=>t})}else if(e instanceof y$)return new y$({...e._def,type:b$(e.element)});else if(e instanceof I$)return I$.create(b$(e.unwrap()));else if(e instanceof L$)return L$.create(b$(e.unwrap()));else if(e instanceof E$)return E$.create(e.items.map(e=>b$(e)));else return e}var x$=class e extends r${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=LQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==RQ.object){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.object,received:t.parsedType}),KQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _$&&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 e$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof _$){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&&(WQ(n,{code:Q.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 e$(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=>GQ.mergeObjectSync(t,e)):GQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return $Q.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:$Q.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:$.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 LQ.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 LQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return b$(this)}partial(t){let n={};for(let e of LQ.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 LQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof I$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return j$(LQ.objectKeys(this.shape))}};x$.create=(e,t)=>new x$({shape:()=>e,unknownKeys:`strip`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)}),x$.strictCreate=(e,t)=>new x$({shape:()=>e,unknownKeys:`strict`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)}),x$.lazycreate=(e,t)=>new x$({shape:e,unknownKeys:`strip`,catchall:_$.create(),typeName:$.ZodObject,...n$(t)});var S$=class extends r${_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 BQ(e.ctx.common.issues));return WQ(t,{code:Q.invalid_union,unionErrors:n}),KQ}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 BQ(e));return WQ(t,{code:Q.invalid_union,unionErrors:i}),KQ}}get options(){return this._def.options}};S$.create=(e,t)=>new S$({options:e,typeName:$.ZodUnion,...n$(t)});const C$=e=>e instanceof k$?C$(e.schema):e instanceof F$?C$(e.innerType()):e instanceof A$?[e.value]:e instanceof M$?e.options:e instanceof N$?LQ.objectValues(e.enum):e instanceof R$?C$(e._def.innerType):e instanceof p$?[void 0]:e instanceof m$?[null]:e instanceof I$?[void 0,...C$(e.unwrap())]:e instanceof L$?[null,...C$(e.unwrap())]:e instanceof V$||e instanceof U$?C$(e.unwrap()):e instanceof z$?C$(e._def.innerType):[];var _me=class e extends r${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.object)return WQ(t,{code:Q.invalid_type,expected:RQ.object,received:t.parsedType}),KQ;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}):(WQ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),KQ)}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=C$(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:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...n$(r)})}};function w$(e,t){let n=zQ(e),r=zQ(t);if(e===t)return{valid:!0,data:e};if(n===RQ.object&&r===RQ.object){let n=LQ.objectKeys(t),r=LQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=w$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===RQ.array&&r===RQ.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=w$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===RQ.date&&r===RQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var T$=class extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(YQ(e)||YQ(r))return KQ;let i=w$(e.value,r.value);return i.valid?((XQ(e)||XQ(r))&&t.dirty(),{status:t.value,value:i.data}):(WQ(n,{code:Q.invalid_intersection_types}),KQ)};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}))}};T$.create=(e,t,n)=>new T$({left:e,right:t,typeName:$.ZodIntersection,...n$(n)});var E$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.array)return WQ(n,{code:Q.invalid_type,expected:RQ.array,received:n.parsedType}),KQ;if(n.data.length<this._def.items.length)return WQ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),KQ;!this._def.rest&&n.data.length>this._def.items.length&&(WQ(n,{code:Q.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 e$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>GQ.mergeArray(t,e)):GQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};E$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new E$({items:e,typeName:$.ZodTuple,rest:null,...n$(t)})};var vme=class e extends r${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!==RQ.object)return WQ(n,{code:Q.invalid_type,expected:RQ.object,received:n.parsedType}),KQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new e$(n,e,n.path,e)),value:a._parse(new e$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?GQ.mergeObjectAsync(t,r):GQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof r$?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...n$(r)}):new e({keyType:s$.create(),valueType:t,typeName:$.ZodRecord,...n$(n)})}},D$=class extends r${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!==RQ.map)return WQ(n,{code:Q.invalid_type,expected:RQ.map,received:n.parsedType}),KQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new e$(n,e,n.path,[a,`key`])),value:i._parse(new e$(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 KQ;(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 KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};D$.create=(e,t,n)=>new D$({valueType:t,keyType:e,typeName:$.ZodMap,...n$(n)});var O$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.set)return WQ(n,{code:Q.invalid_type,expected:RQ.set,received:n.parsedType}),KQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(WQ(n,{code:Q.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&&(WQ(n,{code:Q.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 KQ;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 e$(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:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:$Q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};O$.create=(e,t)=>new O$({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...n$(t)});var yme=class e extends r${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.function)return WQ(t,{code:Q.invalid_type,expected:RQ.function,received:t.parsedType}),KQ;function n(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Q.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof P$){let e=this;return JQ(async function(...t){let o=new BQ([]),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 JQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new BQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new BQ([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:E$.create(t).rest(g$.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||E$.create([]).rest(g$.create()),returns:n||g$.create(),typeName:$.ZodFunction,...n$(r)})}},k$=class extends r${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})}};k$.create=(e,t)=>new k$({getter:e,typeName:$.ZodLazy,...n$(t)});var A$=class extends r${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return WQ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),KQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};A$.create=(e,t)=>new A$({value:e,typeName:$.ZodLiteral,...n$(t)});function j$(e,t){return new M$({values:e,typeName:$.ZodEnum,...n$(t)})}var M$=class e extends r${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{expected:LQ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),KQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),KQ}return JQ(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})}};M$.create=j$;var N$=class extends r${_parse(e){let t=LQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==RQ.string&&n.parsedType!==RQ.number){let e=LQ.objectValues(t);return WQ(n,{expected:LQ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),KQ}if(this._cache||=new Set(LQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=LQ.objectValues(t);return WQ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),KQ}return JQ(e.data)}get enum(){return this._def.values}};N$.create=(e,t)=>new N$({values:e,typeName:$.ZodNativeEnum,...n$(t)});var P$=class extends r${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==RQ.promise&&t.common.async===!1?(WQ(t,{code:Q.invalid_type,expected:RQ.promise,received:t.parsedType}),KQ):JQ((t.parsedType===RQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};P$.create=(e,t)=>new P$({type:e,typeName:$.ZodPromise,...n$(t)});var F$=class extends r${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.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=>{WQ(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 KQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r});{if(t.value===`aborted`)return KQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(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`?KQ:(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`?KQ:(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(!ZQ(e))return KQ;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=>ZQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):KQ);LQ.assertNever(r)}};F$.create=(e,t,n)=>new F$({schema:e,typeName:$.ZodEffects,effect:t,...n$(n)}),F$.createWithPreprocess=(e,t,n)=>new F$({schema:t,effect:{type:`preprocess`,transform:e},typeName:$.ZodEffects,...n$(n)});var I$=class extends r${_parse(e){return this._getType(e)===RQ.undefined?JQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I$.create=(e,t)=>new I$({innerType:e,typeName:$.ZodOptional,...n$(t)});var L$=class extends r${_parse(e){return this._getType(e)===RQ.null?JQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:$.ZodNullable,...n$(t)});var R$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===RQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...n$(t)});var z$=class extends r${_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 QQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...n$(t)});var B$=class extends r${_parse(e){if(this._getType(e)!==RQ.nan){let t=this._getOrReturnCtx(e);return WQ(t,{code:Q.invalid_type,expected:RQ.nan,received:t.parsedType}),KQ}return{status:`valid`,value:e.data}}};B$.create=e=>new B$({typeName:$.ZodNaN,...n$(e)});var V$=class extends r${_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}},H$=class e extends r${_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`?KQ:e.status===`dirty`?(t.dirty(),qQ(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`?KQ: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:$.ZodPipeline})}},U$=class extends r${_parse(e){let t=this._def.innerType._parse(e),n=e=>(ZQ(e)&&(e.value=Object.freeze(e.value)),e);return QQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};U$.create=(e,t)=>new U$({innerType:e,typeName:$.ZodReadonly,...n$(t)}),x$.lazycreate;var $;(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`})($||={}),s$.create,c$.create,B$.create,l$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create;const bme=x$.create;x$.strictCreate,S$.create,_me.create,T$.create,E$.create,vme.create,D$.create,O$.create,yme.create,k$.create,A$.create,M$.create,N$.create,P$.create,F$.create,I$.create,L$.create,F$.createWithPreprocess,H$.create;const xme=m(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);v.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>pe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>fe(e,t,n),e.parseAsync=async(t,n)=>r(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>h(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>y(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),Sme=m(`ZodMiniObject`,(e,t)=>{o.init(e,t),xme.init(e,t),l(e,`shape`,()=>t.shape)});function W$(e,t){return new Sme({type:`object`,shape:e??{},...d(t)})}function G$(e){return!!e._zod}function K$(e){let t=Object.values(e);if(t.length===0)return W$({});let n=t.every(G$),r=t.every(e=>!G$(e));if(n)return W$(e);if(r)return bme(e);throw Error(`Mixed Zod versions detected in object shape.`)}function q$(e,t){return G$(e)?fe(e,t):e.safeParse(t)}async function J$(e,t){return G$(e)?await h(e,t):await e.safeParseAsync(t)}function Y$(e){if(!e)return;let t;if(t=G$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function X$(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 K$(e)}}if(G$(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 Z$(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 Cme(e){return e.description}function wme(e){if(G$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Q$(e){if(G$(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 $$=`2025-11-25`,e1=[$$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],t1=`io.modelcontextprotocol/related-task`,n1=ve(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),r1=ke([I(),F().int()]),i1=I();se({ttl:F().optional(),pollInterval:F().optional()});const Tme=P({ttl:F().optional()}),Eme=P({taskId:I()}),a1=se({progressToken:r1.optional(),[t1]:Eme.optional()}),o1=P({_meta:a1.optional()}),s1=o1.extend({task:Tme.optional()}),Dme=e=>s1.safeParse(e).success,c1=P({method:I(),params:o1.loose().optional()}),l1=P({_meta:a1.optional()}),u1=P({method:I(),params:l1.loose().optional()}),d1=se({_meta:a1.optional()}),f1=ke([I(),F().int()]),p1=P({jsonrpc:M(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=P({jsonrpc:M(`2.0`),...u1.shape}).strict(),Ome=e=>h1.safeParse(e).success,g1=P({jsonrpc:M(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(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`})(v1||={});const y1=P({jsonrpc:M(`2.0`),id:f1.optional(),error:P({code:F().int(),message:I(),data:j().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=ke([p1,h1,g1,y1]);ke([g1,y1]);const S1=d1.strict(),kme=l1.extend({requestId:f1.optional(),reason:I().optional()}),C1=u1.extend({method:M(`notifications/cancelled`),params:kme}),w1=P({icons:N(P({src:I(),mimeType:I().optional(),sizes:N(I()).optional(),theme:Ce([`light`,`dark`]).optional()})).optional()}),T1=P({name:I(),title:I().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:I(),websiteUrl:I().optional(),description:I().optional()}),Ame=le(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,he(P({form:he(P({applyDefaults:A().optional()}),k(I(),j())).optional(),url:n1.optional()}),k(I(),j()).optional())),jme=se({list:n1.optional(),cancel:n1.optional(),requests:se({sampling:se({createMessage:n1.optional()}).optional(),elicitation:se({create:n1.optional()}).optional()}).optional()}),Mme=se({list:n1.optional(),cancel:n1.optional(),requests:se({tools:se({call:n1.optional()}).optional()}).optional()}),Nme=P({experimental:k(I(),n1).optional(),sampling:P({context:n1.optional(),tools:n1.optional()}).optional(),elicitation:Ame.optional(),roots:P({listChanged:A().optional()}).optional(),tasks:jme.optional(),extensions:k(I(),n1).optional()}),Pme=o1.extend({protocolVersion:I(),capabilities:Nme,clientInfo:E1}),D1=c1.extend({method:M(`initialize`),params:Pme}),O1=e=>D1.safeParse(e).success,Fme=P({experimental:k(I(),n1).optional(),logging:n1.optional(),completions:n1.optional(),prompts:P({listChanged:A().optional()}).optional(),resources:P({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:P({listChanged:A().optional()}).optional(),tasks:Mme.optional(),extensions:k(I(),n1).optional()}),Ime=d1.extend({protocolVersion:I(),capabilities:Fme,serverInfo:E1,instructions:I().optional()}),k1=u1.extend({method:M(`notifications/initialized`),params:l1.optional()}),Lme=e=>k1.safeParse(e).success,A1=c1.extend({method:M(`ping`),params:o1.optional()}),Rme=P({progress:F(),total:ue(F()),message:ue(I())}),zme=P({...l1.shape,...Rme.shape,progressToken:r1}),j1=u1.extend({method:M(`notifications/progress`),params:zme}),Bme=o1.extend({cursor:i1.optional()}),M1=c1.extend({params:Bme.optional()}),N1=d1.extend({nextCursor:i1.optional()}),Vme=Ce([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=P({taskId:I(),status:Vme,ttl:ke([F(),_e()]),createdAt:I(),lastUpdatedAt:I(),pollInterval:ue(F()),statusMessage:ue(I())}),F1=d1.extend({task:P1}),Hme=l1.merge(P1),I1=u1.extend({method:M(`notifications/tasks/status`),params:Hme}),L1=c1.extend({method:M(`tasks/get`),params:o1.extend({taskId:I()})}),R1=d1.merge(P1),z1=c1.extend({method:M(`tasks/result`),params:o1.extend({taskId:I()})});d1.loose();const B1=M1.extend({method:M(`tasks/list`)}),V1=N1.extend({tasks:N(P1)}),H1=c1.extend({method:M(`tasks/cancel`),params:o1.extend({taskId:I()})}),Ume=d1.merge(P1),U1=P({uri:I(),mimeType:ue(I()),_meta:k(I(),j()).optional()}),W1=U1.extend({text:I()}),G1=I().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=Ce([`user`,`assistant`]),J1=P({audience:N(q1).optional(),priority:F().min(0).max(1).optional(),lastModified:i({offset:!0}).optional()}),Y1=P({...T1.shape,...w1.shape,uri:I(),description:ue(I()),mimeType:ue(I()),size:ue(F()),annotations:J1.optional(),_meta:ue(se({}))}),Wme=P({...T1.shape,...w1.shape,uriTemplate:I(),description:ue(I()),mimeType:ue(I()),annotations:J1.optional(),_meta:ue(se({}))}),X1=M1.extend({method:M(`resources/list`)}),Gme=N1.extend({resources:N(Y1)}),Z1=M1.extend({method:M(`resources/templates/list`)}),Kme=N1.extend({resourceTemplates:N(Wme)}),Q1=o1.extend({uri:I()}),qme=Q1,$1=c1.extend({method:M(`resources/read`),params:qme}),Jme=d1.extend({contents:N(ke([W1,K1]))}),Yme=u1.extend({method:M(`notifications/resources/list_changed`),params:l1.optional()}),Xme=Q1,Zme=c1.extend({method:M(`resources/subscribe`),params:Xme}),Qme=Q1,$me=c1.extend({method:M(`resources/unsubscribe`),params:Qme}),ehe=l1.extend({uri:I()}),the=u1.extend({method:M(`notifications/resources/updated`),params:ehe}),nhe=P({name:I(),description:ue(I()),required:ue(A())}),rhe=P({...T1.shape,...w1.shape,description:ue(I()),arguments:ue(N(nhe)),_meta:ue(se({}))}),e0=M1.extend({method:M(`prompts/list`)}),ihe=N1.extend({prompts:N(rhe)}),ahe=o1.extend({name:I(),arguments:k(I(),I()).optional()}),t0=c1.extend({method:M(`prompts/get`),params:ahe}),n0=P({type:M(`text`),text:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),r0=P({type:M(`image`),data:G1,mimeType:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),i0=P({type:M(`audio`),data:G1,mimeType:I(),annotations:J1.optional(),_meta:k(I(),j()).optional()}),ohe=P({type:M(`tool_use`),name:I(),id:I(),input:k(I(),j()),_meta:k(I(),j()).optional()}),she=P({type:M(`resource`),resource:ke([W1,K1]),annotations:J1.optional(),_meta:k(I(),j()).optional()}),a0=ke([n0,r0,i0,Y1.extend({type:M(`resource_link`)}),she]),che=P({role:q1,content:a0}),lhe=d1.extend({description:I().optional(),messages:N(che)}),uhe=u1.extend({method:M(`notifications/prompts/list_changed`),params:l1.optional()}),dhe=P({title:I().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),fhe=P({taskSupport:Ce([`required`,`optional`,`forbidden`]).optional()}),o0=P({...T1.shape,...w1.shape,description:I().optional(),inputSchema:P({type:M(`object`),properties:k(I(),n1).optional(),required:N(I()).optional()}).catchall(j()),outputSchema:P({type:M(`object`),properties:k(I(),n1).optional(),required:N(I()).optional()}).catchall(j()).optional(),annotations:dhe.optional(),execution:fhe.optional(),_meta:k(I(),j()).optional()}),s0=M1.extend({method:M(`tools/list`)}),phe=N1.extend({tools:N(o0)}),c0=d1.extend({content:N(a0).default([]),structuredContent:k(I(),j()).optional(),isError:A().optional()});c0.or(d1.extend({toolResult:j()}));const mhe=s1.extend({name:I(),arguments:k(I(),j()).optional()}),l0=c1.extend({method:M(`tools/call`),params:mhe}),hhe=u1.extend({method:M(`notifications/tools/list_changed`),params:l1.optional()});P({autoRefresh:A().default(!0),debounceMs:F().int().nonnegative().default(300)});const u0=Ce([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),ghe=o1.extend({level:u0}),d0=c1.extend({method:M(`logging/setLevel`),params:ghe}),_he=l1.extend({level:u0,logger:I().optional(),data:j()}),vhe=u1.extend({method:M(`notifications/message`),params:_he}),yhe=P({hints:N(P({name:I().optional()})).optional(),costPriority:F().min(0).max(1).optional(),speedPriority:F().min(0).max(1).optional(),intelligencePriority:F().min(0).max(1).optional()}),bhe=P({mode:Ce([`auto`,`required`,`none`]).optional()}),xhe=P({type:M(`tool_result`),toolUseId:I().describe(`The unique identifier for the corresponding tool call.`),content:N(a0).default([]),structuredContent:P({}).loose().optional(),isError:A().optional(),_meta:k(I(),j()).optional()}),She=xe(`type`,[n0,r0,i0]),f0=xe(`type`,[n0,r0,i0,ohe,xhe]),Che=P({role:q1,content:ke([f0,N(f0)]),_meta:k(I(),j()).optional()}),whe=s1.extend({messages:N(Che),modelPreferences:yhe.optional(),systemPrompt:I().optional(),includeContext:Ce([`none`,`thisServer`,`allServers`]).optional(),temperature:F().optional(),maxTokens:F().int(),stopSequences:N(I()).optional(),metadata:n1.optional(),tools:N(o0).optional(),toolChoice:bhe.optional()}),The=c1.extend({method:M(`sampling/createMessage`),params:whe}),p0=d1.extend({model:I(),stopReason:ue(Ce([`endTurn`,`stopSequence`,`maxTokens`]).or(I())),role:q1,content:She}),m0=d1.extend({model:I(),stopReason:ue(Ce([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(I())),role:q1,content:ke([f0,N(f0)])}),Ehe=P({type:M(`boolean`),title:I().optional(),description:I().optional(),default:A().optional()}),Dhe=P({type:M(`string`),title:I().optional(),description:I().optional(),minLength:F().optional(),maxLength:F().optional(),format:Ce([`email`,`uri`,`date`,`date-time`]).optional(),default:I().optional()}),Ohe=P({type:Ce([`number`,`integer`]),title:I().optional(),description:I().optional(),minimum:F().optional(),maximum:F().optional(),default:F().optional()}),khe=P({type:M(`string`),title:I().optional(),description:I().optional(),enum:N(I()),default:I().optional()}),Ahe=P({type:M(`string`),title:I().optional(),description:I().optional(),oneOf:N(P({const:I(),title:I()})),default:I().optional()}),jhe=ke([ke([P({type:M(`string`),title:I().optional(),description:I().optional(),enum:N(I()),enumNames:N(I()).optional(),default:I().optional()}),ke([khe,Ahe]),ke([P({type:M(`array`),title:I().optional(),description:I().optional(),minItems:F().optional(),maxItems:F().optional(),items:P({type:M(`string`),enum:N(I())}),default:N(I()).optional()}),P({type:M(`array`),title:I().optional(),description:I().optional(),minItems:F().optional(),maxItems:F().optional(),items:P({anyOf:N(P({const:I(),title:I()}))}),default:N(I()).optional()})])]),Ehe,Dhe,Ohe]),Mhe=ke([s1.extend({mode:M(`form`).optional(),message:I(),requestedSchema:P({type:M(`object`),properties:k(I(),jhe),required:N(I()).optional()})}),s1.extend({mode:M(`url`),message:I(),elicitationId:I(),url:I().url()})]),Nhe=c1.extend({method:M(`elicitation/create`),params:Mhe}),Phe=l1.extend({elicitationId:I()}),Fhe=u1.extend({method:M(`notifications/elicitation/complete`),params:Phe}),h0=d1.extend({action:Ce([`accept`,`decline`,`cancel`]),content:le(e=>e===null?void 0:e,k(I(),ke([I(),F(),A(),N(I())])).optional())}),Ihe=P({type:M(`ref/resource`),uri:I()}),Lhe=P({type:M(`ref/prompt`),name:I()}),Rhe=o1.extend({ref:ke([Lhe,Ihe]),argument:P({name:I(),value:I()}),context:P({arguments:k(I(),I()).optional()}).optional()}),g0=c1.extend({method:M(`completion/complete`),params:Rhe});function zhe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Bhe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Vhe=d1.extend({completion:se({values:N(I()).max(100),total:ue(F().int()),hasMore:ue(A())})}),Hhe=P({uri:I().startsWith(`file://`),name:I().optional(),_meta:k(I(),j()).optional()}),Uhe=c1.extend({method:M(`roots/list`),params:o1.optional()}),_0=d1.extend({roots:N(Hhe)}),Whe=u1.extend({method:M(`notifications/roots/list_changed`),params:l1.optional()});ke([A1,D1,g0,d0,t0,e0,X1,Z1,$1,Zme,$me,l0,s0,L1,z1,B1,H1]),ke([C1,j1,k1,Whe,I1]),ke([S1,p0,m0,h0,_0,R1,V1,F1]),ke([A1,The,Nhe,Uhe,L1,z1,B1,H1]),ke([C1,j1,vhe,the,Yme,hhe,uhe,I1,Fhe]),ke([S1,Ime,Vhe,lhe,ihe,Gme,Kme,Jme,c0,phe,R1,V1,F1]);var v0=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===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ghe(e.elicitations,n)}return new e(t,n,r)}},Ghe=class extends v0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function y0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Khe=Symbol(`Let zodToJsonSchema decide on which parser to use`),b0={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`},qhe=e=>typeof e==`string`?{...b0,name:e}:{...b0,...e},Jhe=e=>{let t=qhe(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 x0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function S0(e,t,n,r,i){e[t]=n,x0(e,t,r,i)}const C0=(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 w0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?C0(t,e.currentPath):t.join(`/`)}}function Yhe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==$.ZodAny&&(n.items=L0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&S0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&S0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(S0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),S0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Xhe(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?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function Zhe(){return{type:`boolean`}}function T0(e,t){return L0(e.type._def,t)}const Qhe=(e,t)=>L0(e.innerType._def,t);function E0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E0(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 $he(e,t)}}const $he=(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`:S0(n,`minimum`,r.value,r.message,t);break;case`max`:S0(n,`maximum`,r.value,r.message,t);break}return n};function ege(e,t){return{...L0(e.innerType._def,t),default:e.defaultValue()}}function tge(e,t){return t.effectStrategy===`input`?L0(e.schema._def,t):w0(t)}function nge(e){return{type:`string`,enum:Array.from(e.values)}}const rge=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function ige(e,t){let n=[L0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L0(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(rge(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 age(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 D0;const O0={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:()=>(D0===void 0&&(D0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),D0),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 k0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:S0(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`:j0(n,`email`,r.message,t);break;case`format:idn-email`:j0(n,`idn-email`,r.message,t);break;case`pattern:zod`:M0(n,O0.email,r.message,t);break}break;case`url`:j0(n,`uri`,r.message,t);break;case`uuid`:j0(n,`uuid`,r.message,t);break;case`regex`:M0(n,r.regex,r.message,t);break;case`cuid`:M0(n,O0.cuid,r.message,t);break;case`cuid2`:M0(n,O0.cuid2,r.message,t);break;case`startsWith`:M0(n,RegExp(`^${A0(r.value,t)}`),r.message,t);break;case`endsWith`:M0(n,RegExp(`${A0(r.value,t)}$`),r.message,t);break;case`datetime`:j0(n,`date-time`,r.message,t);break;case`date`:j0(n,`date`,r.message,t);break;case`time`:j0(n,`time`,r.message,t);break;case`duration`:j0(n,`duration`,r.message,t);break;case`length`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:M0(n,RegExp(A0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&j0(n,`ipv4`,r.message,t),r.version!==`v4`&&j0(n,`ipv6`,r.message,t);break;case`base64url`:M0(n,O0.base64url,r.message,t);break;case`jwt`:M0(n,O0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&M0(n,O0.ipv4Cidr,r.message,t),r.version!==`v4`&&M0(n,O0.ipv6Cidr,r.message,t);break;case`emoji`:M0(n,O0.emoji(),r.message,t);break;case`ulid`:M0(n,O0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:j0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:S0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:M0(n,O0.base64,r.message,t);break}break;case`nanoid`:M0(n,O0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function A0(e,t){return t.patternStrategy===`escape`?sge(e):e}const oge=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function sge(e){let t=``;for(let n=0;n<e.length;n++)oge.has(e[n])||(t+=`\\`),t+=e[n];return t}function j0(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}}})):S0(e,`format`,t,n,r)}function M0(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:N0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):S0(e,`pattern`,N0(t,r),n,r)}function N0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1218
1218
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1219
1219
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function P0(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===$.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??w0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===$.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=k0(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===$.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===$.ZodBranded&&e.keyType._def.type._def.typeName===$.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=T0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function cge(e,t){return t.mapStrategy===`record`?P0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||w0(t),L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||w0(t)],minItems:2,maxItems:2}}}function lge(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 uge(e){return e.target===`openAi`?void 0:{not:w0({...e,currentPath:[...e.currentPath,`not`]})}}function dge(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const F0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function fge(e,t){if(t.target===`openApi3`)return I0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in F0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=F0[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 I0(e,t)}const I0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L0(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 pge(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:F0[e.innerType._def.typeName],nullable:!0}:{type:[F0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function mge(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`,x0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function hge(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=_ge(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=L0(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=gge(e,t);return o!==void 0&&(r.additionalProperties=o),r}function gge(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L0(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 _ge(e){try{return e.isOptional()}catch{return!0}}const vge=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L0(e.innerType._def,t);let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:w0(t)},n]}:w0(t)},yge=(e,t)=>{if(t.pipeStrategy===`input`)return L0(e.in._def,t);if(t.pipeStrategy===`output`)return L0(e.out._def,t);let n=L0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function bge(e,t){return L0(e.type._def,t)}function xge(e,t){let n={type:`array`,uniqueItems:!0,items:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&S0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&S0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Sge(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Cge(e){return{not:w0(e)}}function wge(e){return w0(e)}const Tge=(e,t)=>L0(e.innerType._def,t),Ege=(e,t,n)=>{switch(t){case $.ZodString:return k0(e,n);case $.ZodNumber:return mge(e,n);case $.ZodObject:return hge(e,n);case $.ZodBigInt:return Xhe(e,n);case $.ZodBoolean:return Zhe();case $.ZodDate:return E0(e,n);case $.ZodUndefined:return Cge(n);case $.ZodNull:return dge(n);case $.ZodArray:return Yhe(e,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return fge(e,n);case $.ZodIntersection:return ige(e,n);case $.ZodTuple:return Sge(e,n);case $.ZodRecord:return P0(e,n);case $.ZodLiteral:return age(e,n);case $.ZodEnum:return nge(e);case $.ZodNativeEnum:return lge(e);case $.ZodNullable:return pge(e,n);case $.ZodOptional:return vge(e,n);case $.ZodMap:return cge(e,n);case $.ZodSet:return xge(e,n);case $.ZodLazy:return()=>e.getter()._def;case $.ZodPromise:return bge(e,n);case $.ZodNaN:case $.ZodNever:return uge(n);case $.ZodEffects:return tge(e,n);case $.ZodAny:return w0(n);case $.ZodUnknown:return wge(n);case $.ZodDefault:return ege(e,n);case $.ZodBranded:return T0(e,n);case $.ZodReadonly:return Tge(e,n);case $.ZodCatch:return Qhe(e,n);case $.ZodPipeline:return yge(e,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(e=>void 0)(t)}};function L0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Khe)return i}if(r&&!n){let e=Dge(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=Ege(e,e.typeName,t),o=typeof a==`function`?L0(a(),t):a;if(o&&Oge(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Dge=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:C0(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`),w0(t)):t.$refStrategy===`seen`?w0(t):void 0}},Oge=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),kge=(e,t)=>{let n=Jhe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??w0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??w0(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 Age(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function R0(e,t){return G$(e)?Ee(e,{target:Age(t?.target),io:t?.pipeStrategy??`input`}):kge(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function z0(e){let t=Y$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Q$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function B0(e,t){let n=q$(e,t);if(!n.success)throw n.error;return n.data}var jge=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(C1,e=>{this._oncancel(e)}),this.setNotificationHandler(j1,e=>{this._onprogress(e)}),this.setRequestHandler(A1,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(L1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new v0(v1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(z1,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 v0(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 v0(v1.InvalidParams,`Task not found: ${r}`);if(!y0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(y0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[t1]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(B1,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 v0(v1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(H1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new v0(v1.InvalidParams,`Task not found: ${e.params.taskId}`);if(y0(n.status))throw new v0(v1.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 v0(v1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof v0?e:new v0(v1.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),v0.fromError(v1.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),_1(e)||b1(e)?this._onresponse(e):m1(e)?this._onrequest(e,t):Ome(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=v0.fromError(v1.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?.[t1]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:v1.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=Dme(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 v0(v1.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:v1.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),_1(e)?n(e):n(new v0(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(_1(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),_1(e)?r(e):r(v0.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 v0?e:new v0(v1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,F1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new v0(v1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},y0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new v0(v1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new v0(v1.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 v0?e:new v0(v1.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||{},[t1]: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 v0?e:new v0(v1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=q$(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(v0.fromError(v1.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},R1,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},V1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Ume,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||{},[t1]: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||{},[t1]: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||{},[t1]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=z0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=B0(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=z0(e);this._notificationHandlers.set(n,n=>{let r=B0(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`&&m1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new v0(v1.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 v0(v1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new v0(v1.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 v0(v1.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=I1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),y0(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 v0(v1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(y0(a.status))throw new v0(v1.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=I1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),y0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function V0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Mge(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];V0(a)&&V0(i)?n[r]={...a,...i}:n[r]=i}return n}var Nge=t(en(),1),Pge=t(Ai(),1);function Fge(){let e=new Nge.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Pge.default)(e),e}var Ige=class{constructor(e){this._ajv=e??Fge()}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)}}},Lge=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},p0,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},h0,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 Rge(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 zge(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 Bge=class extends jge{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(u0.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 Ige,this.setRequestHandler(D1,e=>this._oninitialize(e)),this.setNotificationHandler(k1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(d0,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=u0.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Lge(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Mge(this._capabilities,e)}setRequestHandler(e,t){let n=Y$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(G$(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=q$(l0,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new v0(v1.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=q$(F1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new v0(v1.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=q$(c0,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new v0(v1.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){zge(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Rge(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:e1.includes(t)?t:$$,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`},S1)}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},m0,t):this.request({method:`sampling/createMessage`,params:e},p0,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},h0,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},h0,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new v0(v1.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof v0?e:new v0(v1.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},_0,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 H0=Symbol.for(`mcp.completable`);function U0(e){return!!e&&typeof e==`object`&&H0 in e}function Vge(e){return e[H0]?.complete}var Hge;(function(e){e.Completable=`McpCompletable`})(Hge||={});const Uge=/^[A-Za-z0-9._-]{1,128}$/;function Wge(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`),!Uge.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 Gge(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 W0(e){let t=Wge(e);return Gge(e,t.warnings),t.isValid}var Kge=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)}},G0=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 Bge(e,t)}get experimental(){return this._experimental||={tasks:new Kge(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(s0)),this.server.assertCanSetRequestHandler(X0(l0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(s0,()=>({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=X$(t.inputSchema);return e?R0(e,{strictUnions:!0,pipeStrategy:`input`}):qge})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=X$(t.outputSchema);e&&(n.outputSchema=R0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(l0,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new v0(v1.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new v0(v1.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 v0(v1.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new v0(v1.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 v0&&e.code===v1.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 J$(X$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.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 v0(v1.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await J$(X$(e.outputSchema),t.structuredContent);if(!r.success){let e=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.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 v0(v1.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(X0(g0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(g0,async e=>{switch(e.params.ref.type){case`ref/prompt`:return zhe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Bhe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new v0(v1.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new v0(v1.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new v0(v1.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Q0;let r=Y$(n.argsSchema)?.[e.params.argument.name];if(!U0(r))return Q0;let i=Vge(r);return i?Z0(await i(e.params.argument.value,e.params.context)):Q0}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 Q0;throw new v0(v1.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Z0(await r(e.params.argument.value,e.params.context)):Q0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(X1)),this.server.assertCanSetRequestHandler(X0(Z1)),this.server.assertCanSetRequestHandler(X0($1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(X1,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(Z1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler($1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new v0(v1.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 v0(v1.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(e0)),this.server.assertCanSetRequestHandler(X0(t0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(e0,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Jge(t.argsSchema):void 0}))})),this.server.setRequestHandler(t0,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new v0(v1.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new v0(v1.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await J$(X$(n.argsSchema),e.params.arguments);if(!r.success){let t=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.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:K$(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=K$(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=>U0(e instanceof ae?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){W0(e);let l={title:t,description:n,inputSchema:Y0(r),outputSchema:Y0(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`&&W0(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=K$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=K$(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(J0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!J0(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 qge={type:`object`,properties:{}};function K0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function q0(e){return`_def`in e||`_zod`in e||K0(e)}function J0(e){return typeof e!=`object`||!e||q0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(K0)}function Y0(e){if(e){if(J0(e))return K$(e);if(!q0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Jge(e){let t=Y$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:Cme(t),required:!wme(t)})):[]}function X0(e){let t=Y$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Q$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Z0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Q0={completion:{values:[],hasMore:!1}};var $0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Yge=e=>e instanceof $0?e:new $0(e.message,{cause:e}),Xge=global.Request,e2=class extends Xge{constructor(e,t){typeof e==`object`&&n2 in e&&(e=e[n2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Zge=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)},t2=Symbol(`wrapBodyStream`),Qge=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new e2(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[t2]){let e;a.body=new ReadableStream({async pull(t){try{e||=ku.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=ku.toWeb(r);return new e2(t,a)},n2=Symbol(`getRequestCache`),r2=Symbol(`requestCache`),i2=Symbol(`incomingKey`),a2=Symbol(`urlKey`),$ge=Symbol(`headersKey`),o2=Symbol(`abortControllerKey`),s2={get method(){return this[i2].method||`GET`},get url(){return this[a2]},get headers(){return this[$ge]||=Zge(this[i2])},[Symbol(`getAbortController`)](){return this[n2](),this[o2]},[n2](){return this[o2]||=new AbortController,this[r2]||=Qge(this.method,this[a2],this.headers,this[i2],this[o2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(s2,e,{get(){return this[n2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(s2,e,{value:function(){return this[n2]()[e]()}})}),Object.defineProperty(s2,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[r2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(s2,e2.prototype);var e_e=(e,t)=>{let n=Object.create(s2);n[i2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof zu)throw new $0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[a2]=new URL(r).href}catch(e){throw new $0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof zu?e.authority:e.headers.host)||t;if(!i)throw new $0(`Missing host header`);let a;if(e instanceof zu){if(a=e.scheme,!(a===`http`||a===`https`))throw new $0(`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 $0(`Invalid host header`);return n[a2]=o.href,n},c2=Symbol(`responseCache`),l2=Symbol(`getResponseCache`),u2=Symbol(`cache`),d2=global.Response,f2=class e{#e;#t;[l2](){return delete this[u2],this[c2]||=new d2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[c2];if(e){this.#t=e,this[l2]();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[u2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[u2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[l2]().headers}get status(){return this[u2]?.[0]??this[l2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(f2.prototype,e,{get(){return this[l2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(f2.prototype,e,{value:function(){return this[l2]()[e]()}})}),Object.defineProperty(f2.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[c2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(f2,d2),Object.setPrototypeOf(f2.prototype,d2.prototype);async function t_e(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function p2(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 n_e(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:p2(e.getReader(),t)}var m2=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},r_e=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=gte);var h2=Symbol(`outgoingEnded`),g2=Symbol(`incomingDraining`),i_e=500,a_e=64*1024*1024,_2=e=>{let t=e;if(e.destroyed||t[g2])return;if(t[g2]=!0,e instanceof zu){try{e.stream?.close?.(Bu.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,i_e);a.unref?.();let o=e=>{n+=e.length,n>a_e&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},o_e=()=>new Response(null,{status:400}),v2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),y2=(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))},b2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},x2=async(e,t)=>{let[n,r,i]=e[u2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=m2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=m2(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())):(b2(t),await n_e(r,t)?.catch(e=>y2(e,t))),t[h2]?.()},s_e=e=>typeof e.then==`function`,c_e=async(e,t,n={})=>{if(s_e(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(v2);if(u2 in e)return x2(e,t);let r=m2(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 t_e(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&&b2(t),await p2(n,t,o))}else r[r_e]||(t.writeHead(e.status,r),t.end());t[h2]?.()},S2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==e2&&(Object.defineProperty(global,`Request`,{value:e2}),Object.defineProperty(global,`Response`,{value:f2})),async(r,i)=>{let a,o;try{o=e_e(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[t2]=!0,r.on(`end`,()=>{s=!0}),r instanceof zu&&(i[h2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{_2(r)})})}),i.on(`finish`,()=>{s||_2(r)})),i.on(`close`,()=>{o[o2]&&(r.errored?o[o2].abort(r.errored.toString()):i.writableFinished||o[o2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{_2(r)})})}),a=e(o,{incoming:r,outgoing:i}),u2 in a)return x2(a,i)}catch(e){if(a)return y2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Yge(e)),!a)return}else a=o?v2(e):o_e()}try{return await c_e(a,i,t)}catch(e){return y2(e,i)}}},l_e=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId=`_GET_stream`,this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),new Response(JSON.stringify({jsonrpc:`2.0`,error:i,id:null}),{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw Error(`Stateless transport cannot be reused across requests. Create a new transport per request.`);this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e)){this.onerror?.(Error(`Failed replay events`));try{i.close()}catch{}}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
1220
1220
  `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>x1.parse(e)):[x1.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(O1);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(m1)){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=>O1(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)m1(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)m1(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;m1(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&&!e1.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${e1.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${e1.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((_1(e)||b1(e))&&(n=e.id),n===void 0){if(_1(e)||b1(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(_1(e)||b1(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)}}}},u_e=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new l_e(e),this._requestListener=S2(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 S2(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};function C2(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||!d_e(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=g(i.error);throw new v0(v1.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function d_e(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const w2=2e3,T2=2e3,f_e=[/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 E2(e){return f_e.some(t=>t.test(e))}function p_e(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 Wl(e)?e:null}catch{return null}}function m_e(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&&Wl(a)?a:null}function h_e(e){let t=[];for(let n of e.split(`
@@ -2027,6 +2027,6 @@ native-divergence-injected
2027
2027
  `,`utf-8`),o&&E!==void 0){let r=null;try{H(k)&&(r=U(k,`utf-8`))}catch(e){r=null,A7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&ai(r)!==ai(E)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:E.length,candidateBytes:S.length})),ge(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=Dx(e);if(t.length===0)return;o?.record({event:Db,docName:i,writerId:hx.id,direction:`b`,site:ue,lostLen:t.reduce((e,t)=>e+t.length,0),digest:qn(t.join(`
2028
2028
  `))})}catch(e){A7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},iR)}catch(e){throw t.recordStoreFailure(i,N7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(Lae(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let A=`${k}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await Qo(A,S,`utf-8`),await _s(A,k),DR(k,kR(S)),t.clearStoreFailure(i),Hae();try{d?.(i,f,S,E??null)}catch(e){A7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{is(A)}catch{}throw C.delete(i),t.recordStoreFailure(i,N7(e)),A7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}A7.info({filePath:k,bytes:S.length},`[persistence] Wrote ${k} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){A7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Wo({"persistence.bytes":S.length}),M()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),ye?.record((Date.now()-o)/1e3)})}function Ce({document:e,documentName:n,lastTransactionOrigin:r}){ne.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function we(e=`within-branch`){return A?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,A):(A=(async()=>{let n=e;for(;;){let e=[...ne.entries()];if(ne.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await Se({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=qn(r),a;try{a=UEe(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:qn(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}Roe(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),A7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,ne.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{A=null}),A)}let I={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),Vx(i))return;if(Hx(i)){sEe(n,i,h);return}if(Ux(i)){YG(n,i,_);return}if(Wx(i)||Gx(i)){LEe(n,i,v);return}xe();let o=Date.now();return Zo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{A7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=iN(i,r);if(!H(a))return;let o=a;try{let e=W(a);if(!aN(e,r)){A7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Us(e)===`ELOOP`){A7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=lu(o).size;if(s>524288)throw A7.warn({documentName:i,fileSize:s,limit:Tn},`[persistence] Document exceeds open byte limit; refusing to load`),new VEe(i,s);let c=U(a,`utf-8`),l=n.getXmlFragment(`default`);A7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{aR(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(Pe,crypto.randomUUID())},iR),A7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{A7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):A7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{F?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!Vx(n)){if(Hx(n)){let t=await lEe(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){A7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if(Ux(n)){if(await QG(e,n,r,_)===`persisted`){let e=j7(r,c);if(e&&e.id!==_x.id&&!e.id.startsWith(`agent-`)){let t=VG(n);t&&(Wj(t.docKey,e.id,e.name,e.id,t.subject),M())}}return}if(Wx(n)||Gx(n)){await REe(e,n,r,v);return}if(t.isBatchInProgress()){Ce({document:e,documentName:n,lastTransactionOrigin:r});return}return Se({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Te(){te&&await te}async function Ee(){if(te){await te;return}Jj()!==0&&(te=j().finally(()=>{te=null,k&&(k=!1,M())}),await te)}function De(){return{branchDeferred:ne.size,quiescenceDeferred:C.size}}async function Oe(e,n){if(!Jx(n)){if(t.isBatchInProgress()){Ce({document:e,documentName:n,lastTransactionOrigin:null});return}return Se({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:I,durabilityState:t,flushDeferredStores:we,flushPendingGitCommit:ae,flushContributors:Ee,waitForPendingCommits:Te,getQueueDepths:De,forceStore:Oe,configPersistenceCtx:h,managedArtifactCtx:_}}const F7=L(`persistence-staleness`);var I7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function GEe(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??XS,c=new Map,l=!1,u=null;function d(e){return M7(e)}function f(e){return e===void 0?void 0:ai(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Ya(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),Jx(n)||aS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let E=T?.fingerprint!==x;E&&noe();let ee=!E&&T?T.firstDetectedAtMs:C,D=C-ee,O=null,te=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(O=`disk-file-never-loaded`):t===null?O=`disk-file-missing`:ai(t)!==S&&(O=`disk-diverged-from-base`)}catch(e){e instanceof I7?(O=`disk-read-refused`,F7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(O=`disk-read-failed`,te=!0,F7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(O!==null){g++,ioe(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!te}),F7.warn({docName:n,ageMs:w,staleForMs:D,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:O},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}F7.warn({docName:n,ageMs:w,staleForMs:D,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!1}),roe(),h++;try{await e.forceStore(v,n)}catch(e){F7.error({err:e,docName:n,staleForMs:D},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let k=v.getText(`source`).toString(),A=i(n),ne=d(k);p(ne,f(A),k,A)&&ne===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!0}),F7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?F7.info(v,`[persistence-staleness] sweep complete`):F7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{F7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function KEe(e){try{let t=Ns({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function L7(e){let t=oA(e),n=V(t,`principal.json`),{name:r,email:i}=await KEe(e);if(H(n)){let e;try{e=JSON.parse(U(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${Du()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?qm(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?qm(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return du(n,JSON.stringify(s,null,2),`utf-8`),s}tu(t,{recursive:!0});let a=`principal-${Du()}`,o=a.slice(10,18),s={id:a,display_name:r?qm(r):`Local User`,display_email:i?qm(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return du(n,JSON.stringify(s,null,2),`utf-8`),s}var qEe=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};function R7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function JEe(e,t){try{if(Kx(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(R7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw qb(),Wo({"auth.reason":`doc-deleted`}),new wQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){Hoe(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw Kb(),Wo({"auth.reason":`rename-redirect`}),new wQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw R7(t,i)?(t.recentlyRemovedDocs.delete(i),Kb(),Wo({"auth.reason":`rename-redirect`}),new wQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(qb(),Wo({"auth.reason":`doc-deleted`}),new wQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof wQ)throw t;Voe(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const z7=L(`removed-docs-journal`);function B7(e){return z(oA(e),`removed-docs.json`)}function YEe(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function XEe(e){let t=B7(e);if(!H(t))return[];try{let e=JSON.parse(U(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return z7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!YEe(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return z7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function V7(e,t){let n=B7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};ls(R(n),{recursive:!0});let i=`${n}.tmp`;vs(i,JSON.stringify(r),`utf-8`),ns(i,n)}const H7=L(`server-observers`);function U7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(Vx(r)||Hx(r)||Wx(r)||Gx(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=Dw({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return H7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),Ub(`a`),Ub(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(H7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){H7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const W7=`state.json`;function G7(e){return e.lockDir,H(e.shadowRepoDir)?`adopt`:`fresh`}function K7(e){return V(e,W7)}function ZEe(e,t){return e===t||e===0&&t===1}var q7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function QEe(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function J7(e){let t=K7(e);if(!H(t))return{status:`absent`};let n;try{n=U(t,`utf-8`)}catch(e){throw new q7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new q7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!QEe(r))throw new q7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function Y7(e,t){let n=K7(e);tu(R(n),{recursive:!0}),du(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function X7(e){let t=L(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Vs,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=K7(e.lockDir),s=J7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!ZEe(c.stateSchemaVersion,n))throw new q7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return Y7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(G7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return Y7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return Y7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function $Ee(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function eDe(e){return e.git?.toString()??e.message??``}function Z7(e,t){return t.some(t=>t.test(e))}const tDe={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},nDe=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],Q7=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],rDe=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],iDe=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],aDe=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],oDe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],sDe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],cDe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],lDe=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],uDe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],dDe=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],fDe=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],pDe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function $7(e){let t=mDe(e);return{...t,userFacingCode:$Ee(t.class,t.subclass)}}function mDe(e){let t=e instanceof Error?e:Error(String(e)),n=eDe(t),r=`${t.message}\n${n}`.toLowerCase();if(Z7(r,cDe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(Z7(r,lDe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(Z7(r,uDe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=pa(t);return i.kind===`auth`?i.subclass===`403`&&Z7(r,Q7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:tDe[i.subclass],rawStderr:n}:Z7(r,Q7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:Z7(r,nDe)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:Z7(r,rDe)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:Z7(r,iDe)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:Z7(r,aDe)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:Z7(r,sDe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:Z7(r,oDe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:Z7(r,pDe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:Z7(r,fDe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:Z7(r,dDe)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function hDe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const e9=L(`github-permissions`);function gDe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function _De(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function vDe(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function yDe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return e9.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=vDe(t);return n===null?(e9.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return e9.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function bDe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){e9.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function xDe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await bDe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?(e9.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):(e9.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${gDe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;e9.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:_De(l)}),t=await yDe(e,l!==void 0);return e9.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?(e9.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):(e9.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function SDe(e){let t=performance.now(),n=await xDe(e);return EDe(n,performance.now()-t),n}function CDe(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let t9=null;function wDe(){return t9||=xs().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),t9}let n9=null;function TDe(){return n9||=xs().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),n9}function EDe(e,t){let n=CDe(e);wDe().add(1,n),TDe().record(t,{outcome:n.outcome})}function r9(e,t,n=Date.now()){if(!e)return 0;let r=new Date(e).getTime();if(Number.isNaN(r))return 0;let i=r+t*1e3;return Math.max(0,i-n)}function DDe(e,t){return t===`anonymous`?Math.max(180,e):e}const i9=L(`sync-engine`),a9=/^[0-9a-f]{40}$/i,ODe=Nu(Il);function kDe(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 ADe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function o9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function s9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function c9(e){let t=qu(e);if(t.kind!==`repository`)return!1;let n=t.repository.readHead();return n.kind===`branch`?t.repository.readRef(n.ref).kind===`absent`:!1}function jDe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const l9=12e4;var MDe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=hDe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??SDe,this.statePath=V(oA(this.projectDir),`sync-state.json`),this.conflictStore=new OQ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return fF(this.projectDir)}gitHandle(e){return Is(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){i9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),i9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){i9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=od(this.projectDir),n=t?z(t,`MERGE_HEAD`):null,r=n!==null&&H(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){i9.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await Pb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&i9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){i9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){i9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){i9.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),i9.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=r9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=r9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),i9.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,i9.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){i9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await Mu(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||c9(this.projectDir)?0:this.unpushedCommitCount(this.gitHandle())}async unpushedCommitCount(e){try{let t=await e.git.status();if(t.tracking)return t.ahead}catch{}try{let t=(await e.git.raw([`rev-list`,`--count`,`origin/${this.currentBranch}..HEAD`])).trim(),n=Number.parseInt(t,10);return Number.isFinite(n)?n:0}catch{return 0}}async convertStrandedCommitsToOverlay(){if(!this.hasRemote||c9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){i9.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){i9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Ps(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,i9.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,i9.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?i9.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):i9.info({op:e,state:this.state},`[sync] trigger(${e}) running`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return i9.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||c9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?Kde(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await Dz(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=dF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,o9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,i9.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){i9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=ADe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,i9.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,i9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!o9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,i9.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!H(z(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return i9.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=od(this.projectDir),r=n?z(n,`MERGE_HEAD`):null;if(r!==null&&H(r))try{let n=this.gitHandle(),r=new Set(await Pb(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&i9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){i9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{i9.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&(i9.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{i9.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??s9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{i9.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){i9.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?DDe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=jDe(this.consecutiveFailures);return s9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(c9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,i9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=$7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=$7(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),i9.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await Pb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Pb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=new Map;for(let e of this.conflictStore.list())e.variant===`working-tree`&&i.set(e.file,e);let a;try{a=await this.planOverlapReconciliation(e,t,n,r,i)}catch(e){return this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){i9.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return i9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return i9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(i9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError($7(Error(`git merge --ff-only timed out after ${l9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),i9.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return i9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError($7(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return i9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError($7(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return i9.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await ODe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:l9}),{ok:!0}}catch(e){let t=e,n=t.killed===!0||t.signal===`SIGTERM`,r=typeof t.code==`number`?t.code:null,i=typeof t.stderr==`string`?t.stderr:e instanceof Error?e.message:String(e);return{ok:!1,refusal:kDe({exitCode:r,stderr:i}),stderr:i,exitCode:r,timedOut:n}}}async planOverlapReconciliation(e,t,n,r,i){let a=[],o=[],s=[],c=[],l=[],u=[],d=[],f=[];for(let p of r){let r=i.get(p),m=r!==void 0;if(!H(z(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),i9.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=U(z(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&i9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=pi(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){i9.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){for(let{path:t,bytes:n}of e){let e=z(this.projectDir,t);WI(e,this.projectDir),vs(e,n)}for(let e of t){let t=z(this.projectDir,e);WI(t,this.projectDir);try{is(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=z(this.projectDir,e),n=nN(B(this.contentDir,t));return!n.startsWith(`..`)&&kx(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 Pb(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(c9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=this.gatherContentFilesSync(),n=z(gu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Ps(async()=>{let e=this.gitHandle(n);if(c9(this.projectDir)){i9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){i9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError($7(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i),o=await this.stageContentFiles(e,t),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(e,c);let l=(await e.git.raw([`write-tree`])).trim(),u=``;try{u=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){i9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}i9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let d=[],f=[];try{let n=await Pb(e.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){d.push(t);let n=e.get(t)??nN(B(this.contentDir,z(this.projectDir,t)));n&&!n.startsWith(`..`)&&f.push(n)}}}catch{d=t.map(e=>e.projectRelPath).concat(c),f=t.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f),m=await Dz(this.projectDir),h=m===null;this.identityUnresolved!==h&&(this.identityUnresolved=h,this.cc1Broadcaster?.signal(`sync-status`));let g=m?.name??`OpenKnowledge`,_=m?.email??`sync@open-knowledge.local`;Rs(e,{GIT_AUTHOR_NAME:g,GIT_AUTHOR_EMAIL:_,GIT_COMMITTER_NAME:g,GIT_COMMITTER_EMAIL:_});let v=(await e.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!v||!a9.test(v)){i9.warn({raw:v},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,v,i]),await this.resetRealIndexForPaths(d);let y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),y=!0}catch{}y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=v}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=$7(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){i9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=$7(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}i9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{uu(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=z(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 Pb(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}let u=await Dz(this.projectDir),d=u?.name??`OpenKnowledge`,f=u?.email??`sync@open-knowledge.local`;Rs(a,{GIT_AUTHOR_NAME:d,GIT_AUTHOR_EMAIL:f,GIT_COMMITTER_NAME:d,GIT_COMMITTER_EMAIL:f});let p=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!p||!a9.test(p)?(i9.warn({raw:p},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,p,t]),await this.resetRealIndexForPaths(l,e),p)}finally{try{uu(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await Pb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return i9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await Pb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return i9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),i9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return i9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){i9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}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 Pb(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,i9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&i9.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=n=>{let r;try{r=iu(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=z(n,i.name);if(i.isDirectory()){let e=nN(B(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=nN(B(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=nN(B(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return H(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Pb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=z(this.projectDir,e),r=nN(B(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await Pb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){i9.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){i9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=z(this.projectDir,e),i=nN(B(this.contentDir,t));!i.startsWith(`..`)&&kx(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),i9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){i9.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){i9.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),i9.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),i9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=od(this.projectDir);t=n===null||!H(z(n,`MERGE_HEAD`))}catch(e){i9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),i9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){i9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),i9.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){i9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){i9.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),i9.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,i9.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};du(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){i9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(H(this.statePath))try{let e=U(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){i9.warn({err:e},`[sync] failed to load sync state`)}}};zo();const NDe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function PDe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Vx(e)||Hx(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&NDe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Ko(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Bo.with(Lo.extract(Bo.active(),r),e)}else e()}catch(e){L(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let u9=!1;function d9(){if(u9)return;let e=Uu;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){u9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),u9=!0}catch(e){L(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const FDe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function IDe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(v8).join(` `)} auth git-credential`]}function LDe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=zl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],cN({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return L(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return L(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
2029
2029
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=V(e,r);if(!aN(a,t))continue;let s=BR(a,t);i.has(s)||H(a)&&i.set(s,o)}return i}function f9(e){d9();let{contentDir:t,projectDir:n=t,quiet:r=!0,debounce:i=2e3,maxDebounce:a=1e4,gitEnabled:o=!0,commitDebounceMs:s=3e4,wipRef:c=`refs/wip/main`,configHomedirOverride:l,enableTestRoutes:u=!1,shadowRepo:d,contentRoot:f,destroyTimeoutMs:p=1e4,localOpCliArgs:m,authStreamHeartbeatMs:h,skipStateManifestCheck:g=!1,singleDocRelPath:_,ephemeral:v=!1}=e,y=L(`server`),x=new c7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),E=e=>x.switchReconciledBaseScope(e),ee=e=>x.setBatchInProgress(e),D=()=>x.isBatchInProgress();function te(){let e=qo({absPath:Yo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=oe(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}y.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function k(){let e=qo({absPath:Yo(`project-local`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)}),t=b(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||y.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let r=qo({absPath:Yo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config`)});return r.valid||y.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:O(r.value.autoSync?.default)??`off`,source:`committed-default`}}function A(){let e=qo({absPath:Yo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?Fn(e):Ze}function ne(){return qo({absPath:Yo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function j(){return _M(n,{configHomedirOverride:l,onWarn:e=>y.warn({message:e},`[config] could not read project-local config`)})}function re(){let e=qo({absPath:Yo(`project-local`,n,l),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function M(){return Go({cwd:n,homedirOverride:l,warn:e=>y.debug({message:e},`[config] diagnostics read`)})}function ae(){for(let e of M().diagnostics)e.code===`REMOVED_KEY`&&y.warn({scope:e.scope,file:e.file,path:e.path.join(`.`)},`[config] ${e.path.join(`.`)} is no longer read and was ignored. ${e.redirect}`)}function se(e){return`${sM(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function ce(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=k();t=n.mode,ft?.setMode(n.mode,n.source).catch(t=>{y.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=j();Ae.applyConfig({enabled:n.enabled,providerFingerprint:se(n)}),e===`__config__/project`&&we?.signal(`lint-config`),y.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}bs();let le=Du(),ue=oA(n),de=new Jd({localDir:ue,log:L(`acp-registry`)}),N=new Rd(ue,L(`acp-permissions`));if(Xs(ue,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!g)try{X7({lockDir:ue,shadowRepoDir:sd(n)})}catch(e){throw Hs(ue),e}let fe=Da(),pe=(e,t)=>fe.resolveEmbed(e,t),me=(e,n)=>{let r=fe.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=V(t,r);if(!rN(i,V(t)))return null;try{let e=lu(i);return e.isFile()?e.size:null}catch{return null}},he,P,ge,_e,ve,F,ye,be,xe,Se,Ce,we=null,I=null,Te=null,Ee=null,De=null,Oe=null,ke=j(),Ae=new Gle({loadEmbedder:e.embedderLoader??(()=>{let t=j();return jle({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:z(oA(n),`embeddings`),enabled:ke.enabled,providerFingerprint:se(ke)}),je=null,Me=new Set,Ne=!1,Pe=[],Fe,Ie,Le,Re=new Promise((e,t)=>{Ie=e,Le=t});function ze(e){we?.signal(e)}let Be=null,Ve=!1,He=()=>{try{V7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ue=new qEe(void 0,{onEviction:()=>zoe(),onSizeChange:e=>Boe(e),onMutate:()=>{!Ve||Be!==null||(Be=setTimeout(()=>{Be=null,He()},2e3))}});for(let[e,r]of XEe(n))Kx(e)||hQ(e)&&([`.md`,`.mdx`].some(n=>{let r=V(t,`${e}${n}`);return rN(r,V(t))&&H(r)})||Ue.restore(e,r));Ve=!0;let We={current:null},Ge=(e,t)=>{Kx(e)||Ue.setRenamed(e,t)},Ke=e=>{if(!Kx(e)){if(Ue.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ue.setDeleted(e),We.current?.deleted(e)}},qe=e=>{Kx(e)||Ue.delete(e)};try{he=aP({projectDir:n,contentDir:t,singleDocRelPath:_,inPlaceSkillDirs:UI(t),rescanInPlaceSkillDirs:()=>UI(t),onAfterRebuild:()=>{P.refreshContentScope().catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),lz(ut).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?L(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):L(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),P=new rR({projectDir:n,contentDir:t,contentFilter:he,getGlobalSkillRoots:()=>UG(ve.managedArtifactCtx),signalChannel:ze}),ge={current:d},_e=o?FEe({getShadow:()=>ge.current??null,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,contentRoot:f??``,projectGitDir:od(n)??void 0,isWriterLive:e=>{if(!Ee&&!be)return L(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ee?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of be?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ve=P7({contentDir:t,projectDir:n,gitEnabled:o,commitDebounceMs:s,wipRef:c,shadowRef:ge,ephemeral:v,contentRoot:f,derivedDocumentIndex:P,configHomedirOverride:l,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:pe,resolveSize:me,getPrincipal:()=>je,onAgentCommit:()=>we?.signal(`session-activity`),onFlushCommit:()=>_e?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{we?.emitDiskAck(e,t),!Kx(e)&&Zz(r,n)&&(De?.(),ze(`files`))},onConfigRejected:(e,t)=>we?.emitConfigValidationRejected(e,t),onConfigPersisted:ce,isRecentlyRemoved:e=>Ue.has(e),mdManager:e.mdManager,getLossRing:()=>F,durabilityState:x}),ye=new ZTe({quiet:r,debounce:i,maxDebounce:a,extensions:[ve.extension]});let p=ye;Pe.push(XC(()=>p.documents.size),ZC(()=>ve.getQueueDepths()),$C(()=>{let e=0;for(let t of p.documents.values())e+=t.directConnectionsCount;return{websocket:p.getConnectionsCount()-e,direct:e}})),tw(),v||(Oe=GEe({getLoadedDocuments:()=>p.documents,forceStore:(e,t)=>ve.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=iN(e,t),r,i;try{r=W(n),i=lu(r).size}catch(t){let n=Us(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new I7(`symlink cycle at content path: ${e}`):t}if(!aN(r,t))throw new I7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new I7(`document exceeds the open byte limit: ${e}`);try{return U(r,`utf-8`)}catch(e){if(Us(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let g=ye.shouldUnloadDocument.bind(ye);ye.shouldUnloadDocument=e=>{if(Me.has(e)||Ne&&g(e))return!0;let t=e.name;return Kx(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:g(e)},Fe=async e=>{Me.add(e);try{await ye.unloadDocument(e)}finally{Me.delete(e)}},we=new Yx(ye),Te=new fD(ye),Ee=new mD(ye),be=new Jw(ye,e.agentSessionOptions);let b=be;Pe.push(ew(()=>({active:b.liveSessionCount,limit:b.sessionLimit})));let w=f7({derivedDocumentIndex:P,onDocumentSettled:e=>We.current?.changed(e)});ye.configuration.extensions.push(w),ye.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=TQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==le)throw new wQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${le}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new wQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(je&&n.principalId===je.id?o.principalId=je.id:je?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:je.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),ye.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!Hx(t.documentName)&&!Ux(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!kz(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&Fz(a,e.remotePublicHost);if(!Az(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let T=V(t);function E(e){if(!hQ(e))return null;let t=V(T,Rx(e));return rN(t,T)?t:null}ye.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await JEe(e.documentName,{recentlyRemovedDocs:Ue,resolveFilePath:E,fileExists:H})}}),ye.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=TQ(e.token);pEe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>ye.documents.get(e)})}}),ye.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new E5(e.update);if(t.readVarString(),t.readVarUint()===L5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${$r} rejected — server-only channel`)}});let ee=gQ({hocuspocus:ye,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:be,commentDocHooksRef:We,contentDir:t,contentFilter:he,serverInstanceId:le,getFileIndex:()=>ut?ut.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>ut?ut.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ut?.getFileIndexGeneration()??0,mutateFileIndex:e=>ut?.mutateFileIndex(e),getFolderIndex:()=>ut?ut.getFolderIndex():new Map,getAliasMap:()=>ut?ut.getAliasMap():new Map,getFolderAliasIndex:()=>ut?ut.getFolderAliasIndex():new Map,rescanFiles:()=>ut?.rescanFromDisk(),enableTestRoutes:u,shadowRef:ge,flushGitCommit:()=>ve.flushPendingGitCommit(),flushContributors:()=>ve.flushContributors(),getCurrentBranch:()=>dt?.getLastKnownBranch()??null,getDiskAckSVs:()=>we?.getLatestDiskAckSVsAsBase64()??{},contentRoot:f,derivedDocumentIndex:P,signalChannel:ze,agentFocusBroadcaster:Te,agentPresenceBroadcaster:Ee,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>ft,localOpCliArgs:m,authStreamHeartbeatMs:h,projectDir:n,resolveEmbed:pe,getBridgeLossReporter:()=>Ce,getPrincipal:()=>je,acpRegistry:de,loadAcpCustomAgents:()=>Yd(ue,L(`acp-registry`)),homeDirOverride:l,forceUnloadDocument:Fe,ready:Re,recentlyRemovedDocs:Ue,serializeDoc:$e,evictManagedArtifactLkg:e=>{ve.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ae,getSemanticSimilarityFloor:()=>j().similarityFloor,getLinterBaseConfig:()=>A(),getLinksValidationSetting:()=>ne(),getLinkPreviewsEnabled:re,getConfigDiagnostics:M,embeddingsSecretsFile:mM(l),readSemanticProviderConfig:j,ephemeral:v,onReferencedAssetsCacheInvalidator:e=>{De=e}});ye.configuration.extensions.push(ee),xe=ee.nativeApi,Se=ee.localApi;let D=qo({absPath:Yo(`project`,n),sideline:!1,warn:e=>y.warn({message:e},`[config] could not read project config for bridge guards`)}),O=D.value.bridge.deferGuard.enabled,k=D.value.bridge.fixedPoint.enabled,ie=D.value.bridge.preDrain.enabled;F=D.value.lossCapture.enabled?new Oae({projectDir:n,maxBytes:D.value.lossCapture.maxBytes}):void 0,D.value.bridge.lossDetector.enabled&&(Ce=yse({shadow:()=>ge.current,ring:F,getBranch:()=>dt?.getLastKnownBranch()??`main`,contentRoot:f??``}),be.attachBridgeLossReporter(Ce)),ye.configuration.extensions.push(U7({mdManager:Ho,schema:Vo,shadowRef:ge,contentRoot:f,getCurrentBranch:()=>dt?.getLastKnownBranch()??null,resolveEmbed:pe,resolveSize:me,deferGuardEnabled:O,lossDetectorEnabled:D.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:k,preDrainEnabled:ie,lossRing:F})),ye.configuration.extensions.push(PDe()),ye.configuration.extensions.push(fEe({getSyncEngine:()=>ft,projectDir:n,contentDir:t}))}catch(e){for(let e of Pe.splice(0))e();throw Oe?.dispose(),Oe=null,Hs(ue),e}let Je=null,Ye=new Map,Xe=[];function Qe(e,t){let n=V(e,`rescue`),r=V(n,Rx(t));return rN(r,n)?r:null}function $e(e){let t=ye.documents.get(e);return t?gR(t):null}let et=(e,t)=>pR(x,ye,e,t,pe,me,Ce);function tt(e){if(!iS(e)||ft?.getConflicts().some(r=>s7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let nt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of ye.documents){if(Kx(n))continue;let r=ye.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{aR(r,i,pe,n)},iR)}catch(t){y.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},rt=null,it=e=>{e&&(rt===null&&(rt=new Set,setImmediate(()=>{let e=rt;if(rt=null,e)try{for(let t of e)nt(t)}catch(t){y.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),rt.add(e))};function at(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return SR(e)}}async function ot(e){try{switch(e.kind){case`create`:y.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await P.recordDiskUpsert(e.docName,e.content),ze(`files`),qe(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=ye.documents.get(t);if(!r){await P.recordDiskUpsert(t,n);return}let i=C(t)??``,a=$e(t)??i,o=lR({docName:t,base:i,ours:a,theirs:n}),s=kR(i).slice(0,6),c=kR(a).slice(0,6),l=kR(n).slice(0,6);switch(y.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:tt(r),await P.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Fb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await P.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{et(t,o.newContent),w(t,n),Fb(),tt(r),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),tt(r)}e&&await P.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{et(t,o.newContent),w(t,o.newContent),Fb(),Ib(),e=!0}catch(e){y.error({err:e,docName:t},`[reconcile] failed to apply conflict content to Y.Doc for ${t}`),w(t,n)}{let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,`merged-with-markers`)}e&&await P.recordDiskUpsert(t,n);break}case`refused`:{Ib();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=ye.documents.get(t);if(!n){await P.recordDiskDelete(t),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=$e(t)??``,a=i!==r;if(a&&ge.current){let e=ge.current,n=dt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Sx(e,f??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Rb(),y.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{y.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await P.recordDiskDelete(t),y.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),ye.closeConnections(t),await Fe(n),ze(`files`),Ke(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=ye.documents.get(t);if(T(t),w(n,r),await P.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}y.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),ze(`files`),Ge(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=ye.documents.get(t);if(!n)return;let r=$e(t);r===null?y.warn({docName:t},`[reconcile] case 'conflict': serializeDoc returned null for ${t}; reconciledBase snapshot skipped — post-resolution reconcile may degrade to 3-way merge`):w(t,r);let i=n.getMap(`lifecycle`);i.set(`status`,`conflict`),i.set(`reason`,`conflict-markers`),y.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:fe.add(e.relativePath),ze(`files`),it(Vl(e.relativePath));break;case`asset-delete`:fe.remove(e.relativePath),ze(`files`),it(Vl(e.relativePath));break;case`folder-create`:case`folder-delete`:ze(`files`);break;case`file-create`:case`file-update`:case`file-delete`:ze(`files`);break;default:SR(e)}}catch(t){let n=at(e);y.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let st=[];async function ct(e){if(D()){st.push(e);return}await ot(e)}async function lt(){let e=st.splice(0,st.length);for(let t of e)await ot(t)}let ut=null,dt=null,ft=null,pt=null;async function mt(e){if(ye.documents.size===0)return;let t=!1,n=new Promise(e=>{ye.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(ye.documents.keys());ye.closeConnections(),ye.flushPendingStores();for(let e of ye.documents.values())e.getConnectionsCount()===0&&ye.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(ye.documents.keys()),i=[],o=[];if(ge.current){for(let e of n)if(!Kx(e))try{let t=$e(e);if(t===null){y.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Qe(ge.current.gitDir,e);if(!n){y.warn({docName:e,gitDir:ge.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}tu(R(n),{recursive:!0}),du(n,t,`utf-8`),Rb(),i.push(e),y.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),y.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else y.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function ht(){return pt||(pt=(async()=>{let e=Date.now(),t=[];Ne=!0;for(let e of Pe.splice(0))e();try{await Oe?.dispose()}catch(e){y.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Oe=null;try{Qs(ue)}catch(e){y.warn({err:e},`[server] failed to mark server.lock draining`)}if(Be!==null&&(clearTimeout(Be),Be=null),Ve)try{V7(n,Ue.entries())}catch(e){y.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let r,i=await Promise.race([Re.then(()=>`completed`,e=>(y.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&y.warn({},`[server] init did not complete within 5s during shutdown`);let a=ye.documents.size;_e?.destroy();try{try{try{I&&=(clearTimeout(I),null),dt&&=(await dt.unsubscribe(),null),ut&&=(await ut.unsubscribe(),null);for(let{docName:e,cleanup:t}of Xe)try{await t()}catch(t){y.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Xe.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{we?.destroy(),Ee?.destroy(),Je&&=(await Je.disconnect(),null);for(let[e,t]of Ye)try{await t.disconnect()}catch(t){y.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ye.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await be.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await BS()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await mt(p)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-3 flush failed`)}P.close();let e;try{await Promise.race([(async()=>{await ve.flushPendingGitCommit(),await ve.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),p)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{ft&&=(await ft.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(ge.current){let e;try{await Promise.race([nx(ge.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),p)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await Ns({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&du(V(ge.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{ese(ge.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let r=Date.now()-e;t.length===0?y.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):y.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{Hs(ue,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),y.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await ys()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),pt)}let gt=[];async function _t(){try{je=await L7(n),y.info({principalId:je.id},`[server] principal loaded`)}catch(e){y.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!ge.current)try{ge.current=await cx(n),y.info({gitDir:ge.current.gitDir},`[server] history repo initialized at ${ge.current.gitDir}`)}catch(e){y.error({err:e},`[server] history repo init failed`),gt.push(`shadow-repo`)}if(ge.current){let e=null;try{e=NK(ge.current.gitDir),nq(ge.current.gitDir,e),RK(ge.current.gitDir,e),y.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){y.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(e){let t=1e4;try{await Promise.race([rq(ge.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){y.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await _e?.runBootMaintenance()}catch(e){y.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(ge.current)try{await ox(ge.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){y.warn({},`[server] history repo appears corrupted — reinitializing`);try{ge.current=await cx(n)}catch(e){y.error({err:e},`[server] history repo reinit failed`),ge.current=void 0,gt.includes(`shadow-repo`)||gt.push(`shadow-repo`)}}else y.error({err:e},`[server] history repo check failed (transient?)`)}if(ge.current)try{let e=V(ge.current.gitDir,`last-known-head`),t=null;try{t=U(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await Ns({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await Ns({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}y.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await yx(ge.current,f??``,t,r,e),Lb()}catch(e){y.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else y.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{du(e,r,`utf-8`)}catch(e){y.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){y.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=yK(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;y.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){y.error({err:e},`[server] managed rename recovery failed`),gt.push(`managed-rename-recovery`)}try{let e=Xfe(n);(e.deleted>0||e.errors>0)&&y.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){y.error({err:e},`[server] upload-tempfile sweep failed`),gt.push(`upload-tempfile-sweep`)}try{Je=await ye.openDirectConnection($r),we?.emitServerInfo(le,S())}catch(e){y.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),gt.push(`cc1-push`)}let r=v?[]:ca;for(let e of r)try{let t=await ye.openDirectConnection(e);Ye.set(e,t)}catch(t){y.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),gt.push(`config-doc:${e}`)}let i=new Map([[Di,Yo(`project`,n)],[Rr,Yo(`project-local`,n)],[ma,Yo(`user`,n,l)]]);for(let e of r){let t=i.get(e);if(t)try{y.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await X5(t,t=>{let n=ye.documents.get(e);y.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=o7(n??null,e,t,ve.configPersistenceCtx);y.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),ce(e)});Xe.push({docName:e,cleanup:n}),y.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){y.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),gt.push(`config-file-watcher:${e}`)}}if(!v){let e=(e,t)=>{let n=JG(e,ve.managedArtifactCtx);if(!n)return;let r=$G(ye.documents.get(n)??null,n,t,ve.managedArtifactCtx);y.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),ze(`files`),yi(n)&&P.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=JG(e,ve.managedArtifactCtx);ze(`files`),t&&yi(t)&&P.refreshGlobalSkillNodes().catch(e=>{y.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=UG(ve.managedArtifactCtx),r=await IEe(n,e,t);Xe.push({docName:`__skill-files__`,cleanup:r}),y.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){y.warn({err:e},`[managed-artifact-watcher] skills failed to start`),gt.push(`managed-artifact-watcher:skills`)}try{let e=V(BG(ve.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await X5(e,()=>{ze(`files`)});Xe.push({docName:`__skill-state__`,cleanup:t}),y.info({path:e},`[skill-state-watcher] started`)}catch(e){y.warn({err:e},`[skill-state-watcher] failed to start`),gt.push(`skill-state-watcher`)}}try{let e=V(t,`.okignore`),r=V(n,`.gitignore`),i=null;try{let e=zl(`git`,[`rev-parse`,`--git-common-dir`],cN({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=z(V(n,e.stdout.trim()),`info`,`exclude`);H(R(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=y;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:v},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=v?null:await rEe(a,(t,r)=>{(async()=>{if(t===e)try{let e=o7(ye.documents.get(`__config__/okignore`)??null,ja,r,ve.configPersistenceCtx);o.info({docName:ja,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:B(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await he.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:B(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),we?.signal(`files`);else{let e=B(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),we?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:B(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Xe.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){y.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),gt.push(`ignore-files-watcher`)}let a=d7(n).branch??`main`;E(a);let o=P.beginStartup(a),s=!1,c=performance.now();try{await Zo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:r}=await o.backlinksReady;r&&gt.push(`backlink-index`);let i=0;for(let t of e)Kx(t)||Ue.peek(t)?.kind!==`renamed`&&(Ue.setDeleted(t),i++);i>0&&y.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,u=he?UI(t):new Set,d=e=>{e.some(e=>c.test(B(t,e).split(ql).join(`/`)))&&(I&&clearTimeout(I),I=setTimeout(()=>{I=null;try{nZ(n,t).then(e=>{e>0&&(y.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),we?.signal(`files`))}).catch(e=>y.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=UI(t);if(!(e.size!==u.size||[...e].some(e=>!u.has(e))))return;u=e,he.rebuildIgnorePatterns().then(t=>{t.ok?(y.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),we?.signal(`files`)):y.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>y.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){y.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};ut=await Zo(`ok.boot.seed-walk`,void 0,async()=>cz(t,ct,he,{onRawBatch:d})),nZ(n,t).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=l??pu();nZ(e,e,VI(e)).then(e=>{e>0&&y.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>y.warn({err:e},`[in-place-skills] global copy re-sync failed`))}BL(`seedWalkMs`,Math.round(performance.now()-a));{let e=V(t),n=0;for(let[t]of Ue.entries()){if(!hQ(t))continue;let r=V(e,`${t}${Ix(t)}`);rN(r,e)&&H(r)&&(Ue.delete(t),n++)}n>0&&y.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await P.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&gt.push(`tag-index`);let p=0;try{_===void 0?await yQ({contentDir:t,contentFilter:he,basenameIndex:fe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Bpe({contentDir:t,basenameIndex:fe,onSkip:(e,t,n)=>{p++,y.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(y.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),gt.push(`basename-index-partial`))}catch(e){y.error({err:e},`[basename-index] startup seed failed`),gt.push(`basename-index`)}})}catch(e){if(y.error({err:e},`[server] disk bridge watcher failed to start`),gt.push(`file-watcher`),!s){let e=await P.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&gt.push(`tag-index`)}}finally{BL(`indexesMs`,Math.round(performance.now()-c)),ut&&VL(`fileCount`,ut.getFileIndex().size)}try{dt=await vEe(n,async({trigger:e})=>{if(y.info({trigger:e},`[batch] begin trigger=${e}`),Iae(),ye.flushPendingStores(),await ve.flushPendingGitCommit(),ee(!0),ge.current){let e=S(),t=d7(n).branch??e,r=[];for(let[e,t]of ye.documents){if(Kx(e))continue;let n=null;if(t.transact(()=>{n=$e(e)},FDe),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await use(ge.current,e,_x.id,r,t);n&&(zae(),y.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){y.error({err:e},`[shadow] park failed`)}}},async e=>{let r=st.length,i=e.newBranch??`main`;if(y.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(ee(!1),await lt(),e.headMoved&&e.newHead){let r=LDe(n,V(t),e.oldHead,e.newHead);if(r.size>0){ile(r.keys());for(let[e,t]of r)Wj(e,rd(t.email),t.name,t.email,Td(e));await ve.flushContributors()}}if(await ve.flushDeferredStores(`within-branch`),ft!==null)try{await ft.reconcileConflictsFromGit()}catch(e){y.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Rae(),st.splice(0,st.length);let n=!1,r;try{E(i),r=await P.beginBranchSwitch(i),he.rebuildDirCount();try{let e=0;fe.clear(),await yQ({contentDir:t,contentFilter:he,basenameIndex:fe,onSkip:(t,n,r)=>{e++,y.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(y.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),gt.includes(`basename-index-partial`)||gt.push(`basename-index-partial`))}catch(e){y.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of ye.documents)if(!Kx(e))try{let r=iN(e,t);if(!H(r)){let t=C(e)??``,r=$e(e)??``;if(r!==t&&ge.current){let t=ge.current;queueMicrotask(()=>{Sx(t,f??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Rb(),y.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{y.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),y.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=U(r,`utf-8`);et(e,a),w(e,a),y.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){y.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}y.info({branch:i,docCount:ye.documents.size},`[branch-switch] loaded branch ${i} (${ye.documents.size} docs)`);try{await P.settleBranchFromDisk(r)}catch(e){P.abortBranchSwitch(r),y.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(ge.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of ye.documents)if(!Kx(t))try{let n=await fse(ge.current,i,_x.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=lR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:et(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:et(t,a.newContent),w(t,a.newContent),Ib(),e++;{let e=ye.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){y.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&y.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&ge.current)try{let t=ox(ge.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await nx(ge.current).withMutator(async()=>{for(let e of n.split(`
2030
- `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await ve.flushDeferredStores(`discard-stale`),n=!0,we?.emitBranchSwitched(i)}finally{P.abortBranchSwitch(r),n||(ee(!1),await ve.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ge.current&&r>0){let t=f??`.`;try{let n=await yx(ge.current,t,e.oldHead,e.newHead,i);Lb(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=nN(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=jx(e),a=ye.documents.get(i);if(!a)continue;let o=$e(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=nN(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=ye.documents.get(jx(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=IDe(m),h=k();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new MDe({projectDir:n,contentDir:t,contentFilter:he,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ge.current;n&&await xx(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ge.current;n&&await xx(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await cs({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ie(t.error),configPath:Yo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}ze(`files`),P.announceReadyViews();let g=zL();g!==void 0&&BL(`readyMs`,g),ae()}return _t().then(Ie,e=>{P.close(),Le(e)}),{hocuspocus:ye,durabilityState:x,sessionManager:be,nativeApi:xe,localApi:Se,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:Ee,maintenanceCoordinator:_e,contentFilter:he,basenameIndex:fe,serverInstanceId:le,destroy:ht,ready:Re,degraded:gt,lockDir:ue,get syncEngine(){return ft},getLinkPreviewsEnabled:re,resolveEmbed:pe,acpRegistry:de,acpPermissions:N}}function p9(e){return e/1048576}function RDe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:p9(e.rss),heapTotalMb:p9(e.heapTotal),heapUsedMb:p9(e.heapUsed),externalMb:p9(e.external),arrayBuffersMb:p9(e.arrayBuffers)}}}let m9=null,h9=null,g9=null;const _9=1e6;let v9=null,y9=null;Xo(()=>{m9=null,h9=null,g9=null,v9?.disable(),v9=null,y9=null});function zDe(){if(m9)return;let e=xs().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}=RDe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),m9=e}function BDe(){if(!h9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!v9){v9=yte({resolution:20}),v9.enable();return}e.observe(v9.percentile(50)/_9,{stat:`p50`}),e.observe(v9.percentile(99)/_9,{stat:`p99`}),v9.reset()}),h9=e}if(!g9){let e=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=y9;if(y9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),g9=e}}const b9=L(`skill-migrate`);function x9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=sO.indexOf(e.host),r=sO.indexOf(t.host);return(n===-1?sO.length:n)-(r===-1?sO.length:r)||e.host.localeCompare(t.host)})}const VDe=x9(qt),HDe=x9(wa);function UDe(e,t){ls(R(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function WDe(e,t,n){let r=iI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function S9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+ql)}catch{return!0}}).map(e=>e.name))}async function C9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??VDe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=iu(n)}catch{return a}let s=B(t,n).split(ql).join(`/`),c=new Set;for(let[e,n]of Object.entries($X(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ie.test(e)||TF.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=XD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:fI(t,i),state:WDe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ps(d.path,{recursive:!0,force:!0}),UDe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await LN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),b9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),b9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const w9=L(`skill-reconcile`),GDe=TF;function T9(){let e=[];for(let t of vr){let n=qt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function KDe(e,t){let n=B(e,V(t));return Wl(n)?V(t):n}function E9(e){let{frontmatter:t,body:n}=eo(e),r={};if(t!==``)try{let e=(0,Dk.parse)(To(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function qDe(e,t){let n=E9(e),r=E9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function D9(e,t){let n=O9(e),r=O9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=lu(s).size+lu(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!qDe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function O9(e,t=``){let n=[];for(let r of iu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...O9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function k9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(KDe(e,n),t,`dir`)}function A9(e,t){try{let n=au(e);return V(Wl(n)?n:V(R(e),n))===V(t)}catch{return!1}}function JDe(e,t){try{let n=au(e),r=Wl(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Wl(i))}catch(t){return w9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const YDe=[...vr,`agents`];function XDe(e){for(let t of YDe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function ZDe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=iu(n)}catch{return}let i=T9();for(let e of r){let r=XDe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=eu(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!D9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(fI(t,r))continue;let i=z(r,e);A9(i,a)&&k9(r,i,o)}ps(a,{recursive:!0,force:!0}),w9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){w9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function QDe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of T9()){let o=V(t,e);if(!H(o)||fI(t,o))continue;let s;try{s=iu(o)}catch(e){w9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(GDe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=eu(t);if(l.isSymbolicLink()){if(A9(t,s)&&c)continue;if(JDe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(k9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ie.test(e)){w9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&D9(t,s)){k9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){w9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=PN(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await IN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??sI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){w9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{ZDe({projectDir:t,skillsRoot:n})}catch(e){w9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let j9=null,M9=!1;function N9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function P9(e){if(!N9())return;let t=oA(e);j9=new As({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ha(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};j9?.append(`${JSON.stringify(t)}\n`).catch(e=>{M9||(M9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function F9(){ha(null),await j9?.drain(),j9=null,M9=!1}zo();const $De=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],eOe=[`cache`,`tmp`];function tOe(e){let t=V(e,ge);if(!(()=>{if(!H(t))return!0;try{return iu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of $De)H(V(e,t))&&n.push(t);for(let t of eOe){let r=V(e,t);try{H(r)&&lu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function nOe(e){let t=ad(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const I9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function rOe(e){RL();let t=e.projectDir??e.contentDir,n=qpe({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}`)}Es.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),P9(t),zDe(),BDe();let{kind:r,gitdir:i}=nOe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=Gpe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Zo(`ok.boot`,{attributes:a},async()=>L9(e)),l=()=>{if(s)try{let e=Lo.extract(Bo.active(),{traceparent:s});return Bo.with(e,c)}catch(e){L(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function L9(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Mz(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new jz("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-Rh5J9yH2.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new Y8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??iG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof tG||e instanceof nG){let t=e instanceof nG?e.detected:``,n=e instanceof nG?`too_old`:`not_available`;CG(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ys(),await Promise.race([F9(),new Promise(e=>setTimeout(e,I9))]),e}let v=tOe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);let y=f9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:ee,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:te}=y,k=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),A=e.port??0,ne=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${k}:${A}`,localApi:y.localApi,log:r}),j=l();j.headersTimeout=3e4,j.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:_Q({contentFilter:y.contentFilter,contentSirv:rc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:E,assetExtensions:c,blocklistExtensions:x}),ie=!1;if(e.reactShellDistDir)try{KI(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof GI)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let M=e.reactShellDistDir?rc(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ae=e.ephemeral?null:new XE({contentDir:e.contentDir,localDir:T,globalDir:V(pu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:ee,agentPresenceBroadcaster:O,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${k}:${A}`,getMcpStdioCommand:()=>YE(e.localOpCliArgs,A),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ae!==null&&await ae.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let oe=`pending`;C.then(()=>{oe=`ready`},()=>{oe=`failed`});let se=q8({httpServer:j,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:ne,remoteAccess:i,health:{readiness:()=>oe,degraded:()=>w},log:r,sessionManager:ee,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:M,ephemeral:e.ephemeral,acpThreadManager:ae}),ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},le=null;a!==null&&(le=jQ({httpServer:j,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ce()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);j.once(`error`,r),j.listen(e.port,e.host,()=>{j.removeListener(`error`,r),t()})})}catch(e){if(ie)try{YI(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let ue=zL();ue!==void 0&&BL(`httpListenMs`,ue);let de=j.address(),N=typeof de==`object`&&de?de.port:e.port??0;A=N;let fe=`http://${k}:${N}`;if(f(T,N,fe),ie&&qI(T,N,fe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${I9}ms`))},I9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ce=async()=>{if(pe)return;pe=!0,oe=`draining`;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),ie&&Kfe(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{le?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ae!==null&&await t(`acpThreads.destroy`,()=>ae.destroy()),await t(`mount.shutdown`,()=>se.shutdown()),ne!==void 0&&await t(`mcpHttpHandler.close`,()=>ne.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{se.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{j.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{j.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),ie&&await t(`releaseUiLock`,async()=>YI(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>F9()),await t(`flushLogFileSinks`,()=>Es.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await C9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:S9(e.contentDir,BI(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=pu(),t=await C9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:HDe,inPlaceNames:S9(e,VI(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await QDe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:j,destroy:ce,lockDir:T,contentDir:e.contentDir,port:N,ready:C,degraded:w,didAutoInit:p,serverInstance:y,runtime:eTe(y,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:ae}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new OQ(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=od(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Fs({baseDir:n,timeout:{block:5e3}});s=new Set(await Pb(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=jx(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 iOe=Oe;function aOe(e={}){let t=e.home??pu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(ks(),1);const B9=z(pu(),`.ok`,`logs`),oOe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function sOe(){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 cOe(e){tu(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function lOe(e){try{if(lu(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{ou(n,r)}catch{}}try{uu(`${e}.3`)}catch{}}function uOe(e){try{let t=Date.now(),n=10080*60*1e3,r=iu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=lu(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{uu(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{uu(z(e,t.name)),a-=t.size}catch{}}}catch{}}function dOe(e){cOe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);lOe(n),(e._setTimeout??setTimeout)(()=>uOe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:sOe(),name:e.name,redact:{paths:oOe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function fOe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function pOe(e){return z(B9,`${e}.${V9()}.log`)}function mOe(){return B9}function hOe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=Nu(Il),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function gOe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],cN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function _Oe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!lu(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=iG()}catch(e){throw e instanceof tG||e instanceof nG?(CG(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof nG?`too_old`:`not_available`,detectedVersion:e instanceof nG?e.detected:``},e instanceof nG?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await gOe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],cN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!H(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,vOe=fr.map(e=>e.replace(/\/$/,``));async function yOe(e){let t=od(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(COe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Is(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ps(async()=>{let t=await bOe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await xOe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Is(e,{gitIndexFile:z(gu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await SOe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await Dz(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Rs(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 \`${wr}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of vOe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function bOe(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 xOe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function SOe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function COe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function wOe(e,t){let n;try{n=Fl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await bu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const TOe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of TOe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function EOe(e){if(!kx(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!lu(t).isFile())throw new Q9(e);let n=R(t),r=dz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:jx(B(DOe(e),t).split(ql).join(`/`)),canonicalFilePath:t}}let i=Vl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:jx(i)}}function DOe(e){return V(e,qo({absPath:Yo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function OOe(e){let t=nu(V(gu(),`ok-ephemeral-`)),n=V(t,`.ok`);return tu(n,{recursive:!0}),du(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),du(V(n,`.gitignore`),`local/
2030
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),y.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){y.error({err:e},`[branch-switch] detached cleanup failed`)}ee(!1),await ve.flushDeferredStores(`discard-stale`),n=!0,we?.emitBranchSwitched(i)}finally{P.abortBranchSwitch(r),n||(ee(!1),await ve.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&ge.current&&r>0){let t=f??`.`;try{let n=await yx(ge.current,t,e.oldHead,e.newHead,i);Lb(),y.info({oldHead:e.oldHead?.slice(0,8)??`null`,newHead:e.newHead.slice(0,8),sha:n.slice(0,8)},`[history] upstream-import from ${e.oldHead?.slice(0,8)??`null`}..${e.newHead.slice(0,8)} → ${n.slice(0,8)}`)}catch(e){y.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){y.error({err:e},`[server] HEAD watcher failed to start`),gt.push(`head-watcher`)}function u(e){for(let r of e)try{let e=nN(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=jx(e),a=ye.documents.get(i);if(!a)continue;let o=$e(i);o===null?y.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),y.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){y.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let r of e)try{let e=nN(B(t,z(n,r)));if(e.startsWith(`..`))continue;let i=ye.documents.get(jx(e));i&&tt(i)}catch(e){y.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let p=IDe(m),h=k();h.mode!==`off`&&y.info({mode:h.mode,source:h.source},`[sync] mode active at boot`);try{ft=new MDe({projectDir:n,contentDir:t,contentFilter:he,contentRoot:f,mode:h.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:p,cc1Broadcaster:we,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ve.flushDeferredStores(`within-branch`).catch(e=>{y.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{y.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:u,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=ge.current;n&&await xx(n,f??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=ge.current;n&&await xx(n,f??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{y.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await cs({cwd:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||y.error({result:t,reason:e,humanError:ie(t.error),configPath:Yo(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await ft.start()}catch(e){y.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),ft=null}ze(`files`),P.announceReadyViews();let g=zL();g!==void 0&&BL(`readyMs`,g),ae()}return _t().then(Ie,e=>{P.close(),Le(e)}),{hocuspocus:ye,durabilityState:x,sessionManager:be,nativeApi:xe,localApi:Se,cc1Broadcaster:we,agentFocusBroadcaster:Te,agentPresenceBroadcaster:Ee,maintenanceCoordinator:_e,contentFilter:he,basenameIndex:fe,serverInstanceId:le,destroy:ht,ready:Re,degraded:gt,lockDir:ue,get syncEngine(){return ft},getLinkPreviewsEnabled:re,resolveEmbed:pe,acpRegistry:de,acpPermissions:N}}function p9(e){return e/1048576}function RDe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:p9(e.rss),heapTotalMb:p9(e.heapTotal),heapUsedMb:p9(e.heapUsed),externalMb:p9(e.external),arrayBuffersMb:p9(e.arrayBuffers)}}}let m9=null,h9=null,g9=null;const _9=1e6;let v9=null,y9=null;Xo(()=>{m9=null,h9=null,g9=null,v9?.disable(),v9=null,y9=null});function zDe(){if(m9)return;let e=xs().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}=RDe();e.observe(t.heapUsedMb,{section:`heap_used`}),e.observe(t.heapTotalMb,{section:`heap_total`}),e.observe(t.rssMb,{section:`rss`}),e.observe(t.externalMb,{section:`external`}),e.observe(t.arrayBuffersMb,{section:`array_buffers`})}),m9=e}function BDe(){if(!h9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!v9){v9=yte({resolution:20}),v9.enable();return}e.observe(v9.percentile(50)/_9,{stat:`p50`}),e.observe(v9.percentile(99)/_9,{stat:`p99`}),v9.reset()}),h9=e}if(!g9){let e=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=y9;if(y9={cpu:t,hrtimeNs:n},!r)return;let i=Number(n-r.hrtimeNs)/1e3;i<=0||(e.observe((t.user-r.cpu.user)/i,{mode:`user`}),e.observe((t.system-r.cpu.system)/i,{mode:`system`}))}),g9=e}}const b9=L(`skill-migrate`);function x9(e){return[{host:`agents`,root:`.agents/skills`},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=sO.indexOf(e.host),r=sO.indexOf(t.host);return(n===-1?sO.length:n)-(r===-1?sO.length:r)||e.host.localeCompare(t.host)})}const VDe=x9(qt),HDe=x9(wa);function UDe(e,t){ls(R(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function WDe(e,t,n){let r=iI(e,t,n);switch(r.kind){case`absent`:return{kind:`absent`};case`other`:return{kind:`occupied`,by:`different`};case`symlink`:return r.resolution===`target`?{kind:`store-link`}:{kind:`occupied`,by:`foreign-link`};case`dir`:return r.identity===`different`?{kind:`occupied`,by:`different`}:{kind:`same-copy`}}}function S9(e,t){let n;try{n=W(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!W(V(e,t.dir)).startsWith(n+ql)}catch{return!0}}).map(e=>e.name))}async function C9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??VDe,a={migrated:[],skipped:[]};if(!H(n))return a;let o;try{o=iu(n)}catch{return a}let s=B(t,n).split(ql).join(`/`),c=new Set;for(let[e,n]of Object.entries($X(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Ie.test(e)||TF.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=V(n,e);if(!H(z(o,`SKILL.md`)))continue;let s=XD(o)?.contentHash;if(s===void 0)continue;let l=W(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:fI(t,i),state:WDe(z(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&H(V(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ps(d.path,{recursive:!0,force:!0}),UDe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await LN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),b9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),b9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const w9=L(`skill-reconcile`),GDe=TF;function T9(){let e=[];for(let t of vr){let n=qt[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:`.agents/skills`,editor:null}),e}function KDe(e,t){let n=B(e,V(t));return Wl(n)?V(t):n}function E9(e){let{frontmatter:t,body:n}=eo(e),r={};if(t!==``)try{let e=(0,Dk.parse)(To(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function qDe(e,t){let n=E9(e),r=E9(t);if(n.body!==r.body)return!1;for(let e of Object.keys(n.fm))if(e in r.fm&&JSON.stringify(n.fm[e])!==JSON.stringify(r.fm[e]))return!1;return!0}function D9(e,t){let n=O9(e),r=O9(t);if(n.length!==r.length)return!1;let i=0;for(let a=0;a<n.length;a+=1){if(n[a]!==r[a])return!1;let o=n[a],s=z(e,o),c=z(t,o);if(i+=lu(s).size+lu(c).size,i>1048576)return!1;let l=U(s),u=U(c);if(!l.equals(u)&&(o!==`SKILL.md`||!qDe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function O9(e,t=``){let n=[];for(let r of iu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...O9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function k9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(KDe(e,n),t,`dir`)}function A9(e,t){try{let n=au(e);return V(Wl(n)?n:V(R(e),n))===V(t)}catch{return!1}}function JDe(e,t){try{let n=au(e),r=Wl(n)?V(n):V(R(e),n);if(!H(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||Wl(i))}catch(t){return w9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const YDe=[...vr,`agents`];function XDe(e){for(let t of YDe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function ZDe(e){let{projectDir:t,skillsRoot:n}=e;if(!H(n))return;let r;try{r=iu(n)}catch{return}let i=T9();for(let e of r){let r=XDe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(H(o))try{let n=eu(a);if(n.isSymbolicLink()||!n.isDirectory()||!H(z(a,`SKILL.md`))||!H(z(o,`SKILL.md`))||!D9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(fI(t,r))continue;let i=z(r,e);A9(i,a)&&k9(r,i,o)}ps(a,{recursive:!0,force:!0}),w9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){w9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function QDe(e){let{projectDir:t,skillsRoot:n}=e,r={healed:[],replaced:[],orphansRemoved:[],skipped:[]},i=new Map,a=(e,t)=>{if(t===null)return;let n=i.get(e)??new Set;n.add(t),i.set(e,n)};for(let{rel:e,editor:i}of T9()){let o=V(t,e);if(!H(o)||fI(t,o))continue;let s;try{s=iu(o)}catch(e){w9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(GDe.has(e))continue;let t=z(o,e),s=V(n,e),c=H(s);try{let l=eu(t);if(l.isSymbolicLink()){if(A9(t,s)&&c)continue;if(JDe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(k9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Ie.test(e)){w9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&D9(t,s)){k9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){w9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=PN(t);for(let[r,a]of i){let i=V(n,r);if(!H(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await IN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??sI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){w9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{ZDe({projectDir:t,skillsRoot:n})}catch(e){w9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let j9=null,M9=!1;function N9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function P9(e){if(!N9())return;let t=oA(e);j9=new As({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ha(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};j9?.append(`${JSON.stringify(t)}\n`).catch(e=>{M9||(M9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function F9(){ha(null),await j9?.drain(),j9=null,M9=!1}zo();const $De=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],eOe=[`cache`,`tmp`];function tOe(e){let t=V(e,ge);if(!(()=>{if(!H(t))return!0;try{return iu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of $De)H(V(e,t))&&n.push(t);for(let t of eOe){let r=V(e,t);try{H(r)&&lu(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function nOe(e){let t=ad(e);switch(t.kind){case`directory`:return{kind:`main`,gitdir:t.path};case`linked`:return{kind:`linked`,gitdir:t.path};case`malformed-pointer`:return{kind:`linked`,gitdir:null};case`inaccessible`:case`absent`:return{kind:`main`,gitdir:null}}}const I9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function rOe(e){RL();let t=e.projectDir??e.contentDir,n=qpe({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}`)}Es.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),P9(t),zDe(),BDe();let{kind:r,gitdir:i}=nOe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=Gpe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Zo(`ok.boot`,{attributes:a},async()=>L9(e)),l=()=>{if(s)try{let e=Lo.extract(Bo.active(),{traceparent:s});return Bo.with(e,c)}catch(e){L(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function L9(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??L(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Mz(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new jz("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:l}=await import(`node:http`),{markServerLockDraining:u,releaseServerLock:d,updateServerLockPort:f}=await import(`./server-lock-Dy_yO6Nk.mjs`),p=!1;if(!t&&e.autoInitFn)try{p=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let m=e.projectDir??e.contentDir,h=V(m,`.ok`);if(!H(V(h,`config.yml`)))throw new Y8(H(h)?`config`:`okdir`,m);let g=V(h,`.gitignore`);H(g)||L(`boot`).warn({path:g},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let _=e.gitPreflight??iG;try{e.gitEnabled!==!1&&_()}catch(e){if(e instanceof tG||e instanceof nG){let t=e instanceof nG?e.detected:``,n=e instanceof nG?`too_old`:`not_available`;CG(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await ys(),await Promise.race([F9(),new Promise(e=>setTimeout(e,I9))]),e}let v=tOe(h);v.length>0&&L(`boot`).warn({files:v},`Found legacy runtime files at .ok/${v.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);let y=f9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:b,destroy:S,ready:C,degraded:w,lockDir:T,sessionManager:ee,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:te}=y,k=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),A=e.port??0,ne=e.ephemeral?void 0:H8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${k}:${A}`,localApi:y.localApi,log:r}),j=l();j.headersTimeout=3e4,j.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:_Q({contentFilter:y.contentFilter,contentSirv:rc(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:E,assetExtensions:c,blocklistExtensions:x}),ie=!1;if(e.reactShellDistDir)try{KI(T,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof GI)r.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:T},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await S().catch(()=>{}),d(T),e}let M=e.reactShellDistDir?rc(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ae=e.ephemeral?null:new XE({contentDir:e.contentDir,localDir:T,globalDir:V(pu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:ee,agentPresenceBroadcaster:O,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>`http://${k}:${A}`,getMcpStdioCommand:()=>YE(e.localOpCliArgs,A),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ae!==null&&await ae.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let oe=`pending`;C.then(()=>{oe=`ready`},()=>{oe=`failed`});let se=q8({httpServer:j,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:ne,remoteAccess:i,health:{readiness:()=>oe,degraded:()=>w},log:r,sessionManager:ee,agentFocusBroadcaster:D,agentPresenceBroadcaster:O,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:M,ephemeral:e.ephemeral,acpThreadManager:ae}),ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},le=null;a!==null&&(le=jQ({httpServer:j,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ce()})})),await R9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);j.once(`error`,r),j.listen(e.port,e.host,()=>{j.removeListener(`error`,r),t()})})}catch(e){if(ie)try{YI(T)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await S().catch(()=>{}),d(T),e}let ue=zL();ue!==void 0&&BL(`httpListenMs`,ue);let de=j.address(),N=typeof de==`object`&&de?de.port:e.port??0;A=N;let fe=`http://${k}:${N}`;if(f(T,N,fe),ie&&qI(T,N,fe),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:T,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let pe=!1,me=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${I9}ms`))},I9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ce=async()=>{if(pe)return;pe=!0,oe=`draining`;let e=[],t=async(t,n)=>{try{await me(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{u(T),ie&&Kfe(T)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{le?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ae!==null&&await t(`acpThreads.destroy`,()=>ae.destroy()),await t(`mount.shutdown`,()=>se.shutdown()),ne!==void 0&&await t(`mcpHttpHandler.close`,()=>ne.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{se.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{j.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{j.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>S()),ie&&await t(`releaseUiLock`,async()=>YI(T,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>F9()),await t(`flushLogFileSinks`,()=>Es.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await C9({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:S9(e.contentDir,BI(e.contentDir))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=pu(),t=await C9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:HDe,inPlaceNames:S9(e,VI(e))});t.migrated.length+t.skipped.length>0&&r.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){r.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await QDe({projectDir:m,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.replaced.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:j,destroy:ce,lockDir:T,contentDir:e.contentDir,port:N,ready:C,degraded:w,didAutoInit:p,serverInstance:y,runtime:eTe(y,{contentDir:e.contentDir,projectDir:m}),acpThreadManager:ae}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new OQ(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=od(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!H(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Fs({baseDir:n,timeout:{block:5e3}});s=new Set(await Pb(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=jx(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 iOe=Oe;function aOe(e={}){let t=e.home??pu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?H(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?H(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var z9=t(ks(),1);const B9=z(pu(),`.ok`,`logs`),oOe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function sOe(){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 cOe(e){tu(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function lOe(e){try{if(lu(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{ou(n,r)}catch{}}try{uu(`${e}.3`)}catch{}}function uOe(e){try{let t=Date.now(),n=10080*60*1e3,r=iu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=lu(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{uu(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{uu(z(e,t.name)),a-=t.size}catch{}}}catch{}}function dOe(e){cOe(B9);let t=V9(),n=e.filePath??z(B9,`${e.name}.${t}.log`);lOe(n),(e._setTimeout??setTimeout)(()=>uOe(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:sOe(),name:e.name,redact:{paths:oOe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function fOe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function pOe(e){return z(B9,`${e}.${V9()}.log`)}function mOe(){return B9}function hOe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=H(V(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=R(t);if(r===t)return null;t=r,n+=1}return null}const H9=Nu(Il),U9=L(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function gOe(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],cN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function _Oe(e){let t=V(e),n=V(t,`.git`),r=V(n,`HEAD`),i=!1;if(H(n)){if(!lu(n).isDirectory()||H(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=iG()}catch(e){throw e instanceof tG||e instanceof nG?(CG(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof nG?`too_old`:`not_available`,detectedVersion:e instanceof nG?e.detected:``},e instanceof nG?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await gOe(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],cN({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!H(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=L(`project-skill-git`),K9=/^[0-9a-f]{40}$/,vOe=fr.map(e=>e.replace(/\/$/,``));async function yOe(e){let t=od(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(COe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Is(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ps(async()=>{let t=await bOe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await xOe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Is(e,{gitIndexFile:z(gu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await SOe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await Dz(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Rs(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 \`${wr}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of vOe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function bOe(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 xOe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function SOe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function COe(e){return H(z(e,`MERGE_HEAD`))||H(z(e,`rebase-merge`))||H(z(e,`rebase-apply`))||H(z(e,`CHERRY_PICK_HEAD`))||H(z(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function wOe(e,t){let n;try{n=Fl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=R(n),r=0;r<32;r+=1){let n=z(t,`package.json`);if(H(n))try{let t=JSON.parse(await bu(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=R(t);if(r===t)return;t=r}}const TOe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of TOe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function EOe(e){if(!kx(e))throw new $9(e);let t;try{t=W(V(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!lu(t).isFile())throw new Q9(e);let n=R(t),r=dz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:jx(B(DOe(e),t).split(ql).join(`/`)),canonicalFilePath:t}}let i=Vl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:jx(i)}}function DOe(e){return V(e,qo({absPath:Yo(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function OOe(e){let t=nu(V(gu(),`ok-ephemeral-`)),n=V(t,`.ok`);return tu(n,{recursive:!0}),du(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),du(V(n,`.gitignore`),`local/
2031
2031
  `,`utf-8`),t}export{J2 as $,Tx as $i,qI as $n,gM as $r,tG as $t,Y7 as A,Uw as Ai,OR as An,PP as Ar,mQ as At,d7 as B,Hx as Bi,mR as Bn,_N as Br,Nq as Bt,f9 as C,Ju as Ca,HE as Ci,Az as Cn,fF as Cr,yQ as Ct,X7 as D,kw as Di,SR as Dn,UP as Dr,Epe as Dt,q7 as E,Zw as Ei,uz as En,HP as Er,RZ as Et,jEe as F,Dw as Fi,qR as Fn,MP as Fr,Oq as Ft,K8 as G,wx as Gi,iR as Gn,mN as Gr,Rq as Gt,J8 as H,Ux as Hi,sR as Hn,bN as Hr,Wq as Ht,b7 as I,rS as Ii,cz as In,jP as Ir,Hq as It,z8 as J,_x as Ji,DL as Jn,cN as Jr,Tq as Jt,W8 as K,hx as Ki,ZL as Kn,lN as Kr,Pq as Kt,y7 as L,q as Li,KR as Ln,ude as Lr,Bq as Lt,L7 as M,Fw as Mi,GR as Mn,FP as Mr,tJ as Mt,P7 as N,iw as Ni,BR as Nn,NP as Nr,Qq as Nt,G7 as O,Gw as Oi,JR as On,BP as Or,Dpe as Ot,v7 as P,aw as Pi,DR as Pn,dde as Pr,qq as Pt,U2 as Q,mx as Qi,YI as Qn,_M as Qr,CG as Qt,yEe as R,nS as Ri,TR as Rn,aP as Rr,Uq as Rt,F9 as S,sd as Sa,XE as Si,Mz as Sn,rfe as Sr,TQ as St,W7 as T,Yw as Ti,dz as Tn,VP as Tr,zZ as Tt,Y8 as U,Kx as Ui,lR as Un,vN as Ur,Iq as Ut,c7 as V,qx as Vi,oR as Vn,gN as Vr,Vq as Vt,q8 as W,Vx as Wi,cR as Wn,yN as Wr,Fq as Wt,V2 as X,yx as Xi,KI as Xn,WM as Xr,TG as Xt,k8 as Y,fx as Yi,GI as Yn,iN as Yr,DG as Yt,H2 as Z,ux as Zi,JI as Zn,UM as Zr,SG as Zt,iOe as _,Yd as _a,sA as _i,NU as _n,PF as _r,wQ as _t,EOe as a,ox as aa,Tle as ai,uG as an,JF as ar,y_e as at,P9 as b,dd as ba,fD as bi,zz as bn,wF as br,SQ as bt,yOe as c,Yb as ca,sle as ci,YW as cn,KF as cr,G0 as ct,hOe as d,Ym as da,qj as di,AU as dn,qF as dr,Lme as dt,cx as ea,pM as ei,nG as en,rI as er,j_e as et,dOe as f,Jm as fa,Wj as fi,jU as fn,RF as fr,m1 as ft,aOe as g,zd as ga,aA as gi,wU as gn,MF as gr,xQ as gt,mOe as h,Jd as ha,oA as hi,MU as hn,FF as hr,EQ as ht,OOe as i,Ex as ia,Ile as ii,rG as in,ZF as ir,v_e as it,U7 as j,Ww as ji,YR as jn,IP as jr,HZ as jt,J7 as k,Jw as ki,kR as kn,gde as kr,gQ as kt,W9 as l,Hb as la,Jj as li,KW as ln,GF as lr,x1 as lt,pOe as m,Xm as ma,Gj as mi,FU as mn,LF as mr,jQ as mt,Z9 as n,xx as na,Fle as ni,iG as nn,xfe as nr,P2 as nt,X9 as o,$b as oa,nM as oi,oG as on,YF as or,b_e as ot,fOe as p,Zm as pa,Kj as pi,EU as pn,IF as pr,_1 as pt,H8 as q,gx as qi,FL as qn,fN as qr,wq as qt,$9 as r,Sx as ra,Lle as ri,xG as rn,$F as rr,k2 as rt,wOe as s,Zb as sa,lM as si,XW as sn,XF as sr,C2 as st,Q9 as t,Cx as ta,Rle as ti,$W as tn,nI as tr,F2 as tt,_Oe as u,qoe as ua,ale as ui,SU as un,lfe as ur,$$ as ut,rOe as v,Rd as va,tk as vi,Bz as vn,DF as vr,bQ as vt,d9 as w,YE as wi,kz as wn,tF as wr,_Q as wt,N9 as x,Fd as xa,uD as xi,Lz as xn,kF as xr,Vpe as xt,R9 as y,fd as ya,mD as yi,jz as yn,OF as yr,CQ as yt,f7 as z,Yx as zi,pR as zn,Yue as zr,Mq as zt};
2032
- //# sourceMappingURL=src-T22OxNCJ.mjs.map
2032
+ //# sourceMappingURL=src-bozJXbns.mjs.map