@inkeep/open-knowledge 0.68.4-beta.0 → 0.68.4-beta.1

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 (168) hide show
  1. package/dist/{acp-harness-probe-DHPNTPAW.mjs → acp-harness-probe-C_3_wwAe.mjs} +2 -2
  2. package/dist/cli.mjs +6 -6
  3. package/dist/constants-DMZa5zQG.mjs +2 -0
  4. package/dist/{git-handle-DnoBon5O.mjs → git-handle-C9RU-MxT.mjs} +2 -2
  5. package/dist/git-handle-CzN6a5i1.mjs +1 -0
  6. package/dist/index.mjs +3 -3
  7. package/dist/{init-NLWQBOCI.mjs → init-DLQ79hjt.mjs} +3 -3
  8. package/dist/init-DW4PoVz_.mjs +1 -0
  9. package/dist/{launch-json-removal-BDX2jb-4.mjs → launch-json-removal-nqSmu4fN.mjs} +2 -2
  10. package/dist/loader-BA_dGJtf.mjs +1 -0
  11. package/dist/{loader-c29Dx87s.mjs → loader-D4Gb5uCH.mjs} +2 -2
  12. package/dist/md-manager-B0rABilg.mjs +2 -0
  13. package/dist/{open-browser-F9_RxhVL.mjs → open-browser-DxgGjEoj.mjs} +2 -2
  14. package/dist/parse-worker.mjs +1 -1
  15. package/dist/preview-B-771SYz.mjs +1 -0
  16. package/dist/{preview-BvikFuF1.mjs → preview-QbIfBqoY.mjs} +2 -2
  17. package/dist/public/assets/{ActivityModeContent-DpyVgHoT.js → ActivityModeContent-Co1JyqXQ.js} +1 -1
  18. package/dist/public/assets/{AddPropertiesButton-DEQfRnsk.js → AddPropertiesButton-b5lnEVKK.js} +2 -2
  19. package/dist/public/assets/{AgentDiffPane-Dbh2Ku2m.js → AgentDiffPane-DSyEDn_Y.js} +1 -1
  20. package/dist/public/assets/{AgentThreadClientBinder-BfzzW91s.js → AgentThreadClientBinder-g9d9BU09.js} +1 -1
  21. package/dist/public/assets/{BugReportHistory-BFeDHqqW.js → BugReportHistory-BYU251NU.js} +1 -1
  22. package/dist/public/assets/{BugReportHistoryDialog-BTq3iS9V.js → BugReportHistoryDialog-wi8j2imF.js} +1 -1
  23. package/dist/public/assets/CodeMirrorPropInput-2n_88FNl.js +3 -0
  24. package/dist/public/assets/{ConsentDialogBody-e0bDGpfC.js → ConsentDialogBody-D2QQqLvP.js} +1 -1
  25. package/dist/public/assets/{DiffViewBoundary-C_NVhw3Y.js → DiffViewBoundary-BIjXbCNm.js} +1 -1
  26. package/dist/public/assets/DocumentContext-C1MDqUGQ.js +38 -0
  27. package/dist/public/assets/{EditorModeToggle-ibhbLQIy.js → EditorModeToggle-PGfji8Z4.js} +1 -1
  28. package/dist/public/assets/{EnableSyncConfirmDialog-BcL75l3F.js → EnableSyncConfirmDialog-D73cTIc2.js} +1 -1
  29. package/dist/public/assets/{ExcalidrawDocEditor-BNHSMJQS.js → ExcalidrawDocEditor-DLYL4uLQ.js} +1 -1
  30. package/dist/public/assets/FeedbackForm-DgVONYW4.js +1 -0
  31. package/dist/public/assets/{GraphPanel-BUWA0D9J.js → GraphPanel-DODcHiM6.js} +2 -2
  32. package/dist/public/assets/{ImportSkillDialog-jFU7pbPY.js → ImportSkillDialog-SFJoXCHy.js} +1 -1
  33. package/dist/public/assets/{LintConfigEditor-D7YDlVNL.js → LintConfigEditor-cz4oBJkn.js} +1 -1
  34. package/dist/public/assets/ManagedArtifactProperties-D4in1i0d.js +1 -0
  35. package/dist/public/assets/{ManagedArtifactProperties-CZgD-BSq.js → ManagedArtifactProperties-DVYEs_-t.js} +1 -1
  36. package/dist/public/assets/{MermaidDocEditor-CxdG1bUB.js → MermaidDocEditor-BnbvkIUa.js} +1 -1
  37. package/dist/public/assets/{PropertyDisplayRow-B4oaLWuk.js → PropertyDisplayRow-DoKlSeCY.js} +1 -1
  38. package/dist/public/assets/{ReportBugDialogBody-B5V7nLOX.js → ReportBugDialogBody-Cn9kuPrd.js} +1 -1
  39. package/dist/public/assets/{ReportBugMenuTrigger-86Ew_tTi.js → ReportBugMenuTrigger-BWaaWbbQ.js} +2 -2
  40. package/dist/public/assets/{SchemaConfigEditor-Dm6jiRdF.js → SchemaConfigEditor-BqXzeHB3.js} +1 -1
  41. package/dist/public/assets/{SessionsHost-B8iiwkuP.js → SessionsHost-C1OZt5vc.js} +2 -2
  42. package/dist/public/assets/{SettingsDialogBody-CGru4MuC.js → SettingsDialogBody-DQtkh-bL.js} +4 -4
  43. package/dist/public/assets/{ShareBranchSwitchDialog-4R7TrS-D.js → ShareBranchSwitchDialog--N1Bd5qo.js} +1 -1
  44. package/dist/public/assets/{ShareReceiveDialog-Cmq2hZPb.js → ShareReceiveDialog-By6mslOj.js} +1 -1
  45. package/dist/public/assets/{ShareReceiveMissDialog-B0S_dCJU.js → ShareReceiveMissDialog-DrHrN8Zh.js} +1 -1
  46. package/dist/public/assets/{SkillCostValue-DHSmxhI-.js → SkillCostValue-CkONMU96.js} +1 -1
  47. package/dist/public/assets/{SkillEditBanner-B27-_Aay.js → SkillEditBanner-BkN4Vlyo.js} +1 -1
  48. package/dist/public/assets/{SkillForkDialog-BAZRmLVh.js → SkillForkDialog-Bkhm9FwF.js} +1 -1
  49. package/dist/public/assets/{SkillInstallMenu-Cw_GhQXv.js → SkillInstallMenu-DPBO7ZLl.js} +2 -2
  50. package/dist/public/assets/{SkillOriginInline-BSlC26uH.js → SkillOriginInline-DqGgPWeD.js} +1 -1
  51. package/dist/public/assets/{SkillToolbarControls-CKvPee0l.js → SkillToolbarControls-kSIovUXj.js} +1 -1
  52. package/dist/public/assets/{SlidesToolbarControls-BxNx9-Fx.js → SlidesToolbarControls-CloREzdd.js} +1 -1
  53. package/dist/public/assets/{SourceEditor-WIRsBFEm.js → SourceEditor-DxcW7Ji4.js} +1 -1
  54. package/dist/public/assets/{TerminalPanel-uwQJYmWz.js → TerminalPanel-zXPIa6n_.js} +1 -1
  55. package/dist/public/assets/{TerminalWindowApp-Beh9r_L9.js → TerminalWindowApp-Cpr1PRtm.js} +1 -1
  56. package/dist/public/assets/{TextDocEditor-otzsAiqo.js → TextDocEditor-CNvGi20m.js} +1 -1
  57. package/dist/public/assets/{ThreadView-DP20xiUN.js → ThreadView-BdfdaWKJ.js} +1 -1
  58. package/dist/public/assets/{TimelineDiffPane-BoPvynYM.js → TimelineDiffPane-BIR2lWwH.js} +1 -1
  59. package/dist/public/assets/{agent-diff-store-DVYE4Dgm.js → agent-diff-store-_WIhmrnK.js} +1 -1
  60. package/dist/public/assets/{auth-state-cache-q3yenLPa.js → auth-state-cache-BCDkELSW.js} +4 -4
  61. package/dist/public/assets/{bug-report-send-manager-TlhphH7d.js → bug-report-send-manager-BhNwFXTM.js} +1 -1
  62. package/dist/public/assets/{client-version-Celk29vl.js → client-version-DPdchc8q.js} +1 -1
  63. package/dist/public/assets/{comment-chips-DtlggR_o.js → comment-chips-SxWcQbb_.js} +1 -1
  64. package/dist/public/assets/config-provider-CFXUtiwu.js +5 -0
  65. package/dist/public/assets/{dist-CMzT53pm.js → dist-CDr44_5B.js} +3 -3
  66. package/dist/public/assets/{doc-hash-CbN6l-bN.js → doc-hash-CbPdvdAA.js} +1 -1
  67. package/dist/public/assets/{documents-events-BQph4Rf_.js → documents-events-CRdjzLAr.js} +1 -1
  68. package/dist/public/assets/{file-tree-adapter-BpMqjQeh.js → file-tree-adapter-Bg4PgS4F.js} +1 -1
  69. package/dist/public/assets/{file-tree-utils-D3vfryrA.js → file-tree-utils-Dt-qVN4W.js} +1 -1
  70. package/dist/public/assets/{folder-config-api-BGqXA_Yc.js → folder-config-api-Do2u-Rpg.js} +1 -1
  71. package/dist/public/assets/{globals-CL98nbsz.css → globals-ByagJMEb.css} +1 -1
  72. package/dist/public/assets/i18n-CApFNCKM.js +1 -0
  73. package/dist/public/assets/{index-DOJcKH7u.js → index-DWEZyyUh.js} +14 -14
  74. package/dist/public/assets/{launcher-selection-Q4ZIQ0VB.js → launcher-selection-BtAC_6OE.js} +1 -1
  75. package/dist/public/assets/{lint-config-client-nUUp3gxC.js → lint-config-client-C7Do4K-V.js} +1 -1
  76. package/dist/public/assets/{markdownlint-rule-browser-Dw2Ln--S.js → markdownlint-rule-browser-BuLeocmZ.js} +1 -1
  77. package/dist/public/assets/messages-6fcD2J3f.js +1 -0
  78. package/dist/public/assets/messages-BcgMON4t.js +1 -0
  79. package/dist/public/assets/messages-BfSRfllp.js +1 -0
  80. package/dist/public/assets/messages-BzB2vjb8.js +1 -0
  81. package/dist/public/assets/messages-CFC4xaZ5.js +1 -0
  82. package/dist/public/assets/messages-CHyeSnWa.js +1 -0
  83. package/dist/public/assets/messages-DZE-VzhB.js +1 -0
  84. package/dist/public/assets/messages-DZfszRg3.js +1 -0
  85. package/dist/public/assets/messages-DnatZmOM.js +1 -0
  86. package/dist/public/assets/messages-DrjcM4fb.js +1 -0
  87. package/dist/public/assets/messages-DvrupXSr.js +1 -0
  88. package/dist/public/assets/messages-DwrUkQ2i.js +1 -0
  89. package/dist/public/assets/page-list-cache-VMIjzKn4.js +1 -0
  90. package/dist/public/assets/{pending-receive-nav-store-YB8g1-yz.js → pending-receive-nav-store-DWGtNmXZ.js} +1 -1
  91. package/dist/public/assets/{progress-B1dcJzAD.js → progress-mhZcxRBo.js} +3 -3
  92. package/dist/public/assets/{project-paths-5B1myPxo.js → project-paths-BhoLIJti.js} +1 -1
  93. package/dist/public/assets/{prop-types-BkTKnQXu.js → prop-types-CUmrzSW1.js} +1 -1
  94. package/dist/public/assets/{receive-store-BQjSh3hv.js → receive-store-D2_q1wUu.js} +1 -1
  95. package/dist/public/assets/{selection-context-DrNiKImh.js → selection-context-EAVqhQEK.js} +1 -1
  96. package/dist/public/assets/{skill-scope-QdZW9jQB.js → skill-scope-NCYHirwV.js} +1 -1
  97. package/dist/public/assets/{skills-api-_0gvQ7uH.js → skills-api-Dz_rVA1C.js} +1 -1
  98. package/dist/public/assets/{src-DIGxVClC.js → src-DuGGvfdD.js} +1 -1
  99. package/dist/public/assets/{startup-marks-BrgDU-FF.js → startup-marks-BPR5ipj8.js} +1 -1
  100. package/dist/public/assets/{tag-pill-input-ORi2pYBF.js → tag-pill-input-CYAsZCew.js} +1 -1
  101. package/dist/public/assets/{target-navigation-intent-BE1C7c1m.js → target-navigation-intent-CYAnPRok.js} +1 -1
  102. package/dist/public/assets/{telemetry-startup-BJDvRilA.js → telemetry-startup-kezMCRHJ.js} +1 -1
  103. package/dist/public/assets/{terminal-cli-display-BBkrKOa9.js → terminal-cli-display-jaULlk-O.js} +1 -1
  104. package/dist/public/assets/{terminal-command-events-De5Ifk_s.js → terminal-command-events-D5gbDNfs.js} +1 -1
  105. package/dist/public/assets/typing-burst-detector-Dc6Z0dV2.js +8 -0
  106. package/dist/public/assets/{uninstall-4tf55J2_.js → uninstall-DAcZS1HG.js} +1 -1
  107. package/dist/public/assets/{use-activity-panel-DL_QQUqS.js → use-activity-panel-C8rnLWCk.js} +1 -1
  108. package/dist/public/assets/{use-apply-config-color-theme-B7J-6HE8.js → use-apply-config-color-theme-C3t6RLOI.js} +1 -1
  109. package/dist/public/assets/{use-collab-url-2h75iiK6.js → use-collab-url-CUI36lWb.js} +1 -1
  110. package/dist/public/assets/{use-conflicts-aEERGkga.js → use-conflicts-CBdH6psn.js} +1 -1
  111. package/dist/public/assets/{use-live-xterm-theme-tJoPOgqZ.js → use-live-xterm-theme-mYE4hguI.js} +1 -1
  112. package/dist/public/assets/{use-open-skill-DIebCcK8.js → use-open-skill-1xuIk7AK.js} +1 -1
  113. package/dist/public/assets/{use-settings-route-DwMidANO.js → use-settings-route-C_HC7gny.js} +1 -1
  114. package/dist/public/assets/{use-skill-origin-BCC3l5H8.js → use-skill-origin-BKe9dbHW.js} +1 -1
  115. package/dist/public/assets/{use-skills-rVlSdbIJ.js → use-skills-BhaOexz2.js} +1 -1
  116. package/dist/public/assets/{use-terminal-enabled-EXyL5BtZ.js → use-terminal-enabled-M2ci--Ho.js} +1 -1
  117. package/dist/public/assets/use-timeline-entry-diff-CIsFdF1_.js +6 -0
  118. package/dist/public/assets/{use-workspace-BzePm1UL.js → use-workspace-BHq7gCE9.js} +1 -1
  119. package/dist/public/index.html +52 -52
  120. package/dist/public/uninstall.html +6 -6
  121. package/dist/{repair-launch-json-CYrgkeXs.mjs → repair-launch-json-Cf98tAL2.mjs} +2 -2
  122. package/dist/{repair-mcp-configs-Doum-Sk9.mjs → repair-mcp-configs-BDUoYSqZ.mjs} +2 -2
  123. package/dist/{repair-skills-B4Ie9zFi.mjs → repair-skills-C8i0m9eF.mjs} +2 -2
  124. package/dist/repair-skills-WzWxastJ.mjs +1 -0
  125. package/dist/{resolve-project-root-CRNVR4G6.mjs → resolve-project-root-DbR2ne4Y.mjs} +2 -2
  126. package/dist/{server-lock-BIDrb6q3.mjs → server-lock-CGm9uKLf.mjs} +2 -2
  127. package/dist/server-lock-CHQfzAi7.mjs +1 -0
  128. package/dist/{skill-teardown-BkKm3Pt9.mjs → skill-teardown-ByJL1y5S.mjs} +2 -2
  129. package/dist/{src-BJWagnEk.mjs → src-B7MPIdgi.mjs} +2 -2
  130. package/dist/src-Bh9AbwbZ.mjs +1 -0
  131. package/dist/{src-CDcerRX2.mjs → src-CIngi0dD.mjs} +3 -3
  132. package/dist/{src-C_6FcYaw.mjs → src-DoNjy6J-.mjs} +4 -4
  133. package/dist/{src-DOJwM-g6.mjs → src-Dp7hirDl.mjs} +1 -1
  134. package/dist/{start-BQkQRbu6.mjs → start-CyKXYuNo.mjs} +3 -3
  135. package/dist/start-DgBREyCm.mjs +1 -0
  136. package/package.json +4 -4
  137. package/dist/constants-x2sw3BhG.mjs +0 -2
  138. package/dist/git-handle-CgzfmB2x.mjs +0 -1
  139. package/dist/init-_Kckfs8h.mjs +0 -1
  140. package/dist/loader-qy5vX1uK.mjs +0 -1
  141. package/dist/md-manager-BcWiy3AP.mjs +0 -2
  142. package/dist/preview-o83fzdre.mjs +0 -1
  143. package/dist/public/assets/CodeMirrorPropInput-CGzVH90R.js +0 -3
  144. package/dist/public/assets/DocumentContext-ClyIRsul.js +0 -38
  145. package/dist/public/assets/FeedbackForm-CGeSSXdH.js +0 -1
  146. package/dist/public/assets/ManagedArtifactProperties-Dui05152.js +0 -1
  147. package/dist/public/assets/config-provider-BOrlbspR.js +0 -5
  148. package/dist/public/assets/i18n-DOzrqmfh.js +0 -1
  149. package/dist/public/assets/messages-BFk3Lbb9.js +0 -1
  150. package/dist/public/assets/messages-BNDQG0rj.js +0 -1
  151. package/dist/public/assets/messages-BuzgKw3_.js +0 -1
  152. package/dist/public/assets/messages-BxF4_NK8.js +0 -1
  153. package/dist/public/assets/messages-CE6e4GL6.js +0 -1
  154. package/dist/public/assets/messages-CNIbN9u4.js +0 -1
  155. package/dist/public/assets/messages-CnEItHo-.js +0 -1
  156. package/dist/public/assets/messages-DANL5pZx.js +0 -1
  157. package/dist/public/assets/messages-DORMb6Q5.js +0 -1
  158. package/dist/public/assets/messages-DxrZl_3h.js +0 -1
  159. package/dist/public/assets/messages-RozmOeuj.js +0 -1
  160. package/dist/public/assets/messages-f6yF6x8h.js +0 -1
  161. package/dist/public/assets/page-list-cache-D2uEX_G6.js +0 -1
  162. package/dist/public/assets/typing-burst-detector-QMNs16Vx.js +0 -8
  163. package/dist/public/assets/use-timeline-entry-diff-D0zdVNJx.js +0 -6
  164. package/dist/repair-skills-Nir-boO_.mjs +0 -1
  165. package/dist/server-lock-C1GmzCcn.mjs +0 -1
  166. package/dist/src-DUxLgY5j.mjs +0 -1
  167. package/dist/start-DrdcM8ZS.mjs +0 -1
  168. /package/dist/public/assets/{globals-QZHWoM5P.js → globals-DIT-uAXH.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$a as i,$i as a,$n as o,$o as s,$r as c,$s as l,$t as u,A as d,Aa as f,Ac as p,Ai as m,An as h,Ao as g,Ar as _,As as v,At as y,B as b,Ba as x,Bc as S,Bi as C,Bn as w,Bo as T,Br as E,Bt as D,C as ee,Ca as te,Cc as O,Ci as ne,Cn as re,Co as ie,Cr as ae,Cs as oe,Ct as se,D as ce,Da as le,Dc as ue,Di as de,Dn as fe,Do as pe,Dr as me,Ds as he,Dt as ge,E as _e,Ec as ve,Ei as ye,En as be,Er as xe,Es as Se,Et as Ce,F as we,Fa as Te,Fc as k,Fi as Ee,Fn as De,Fo as Oe,Fr as ke,Fs as Ae,Ft as je,G as Me,Ga as Ne,Gi as Pe,Gn as Fe,Gr as Ie,Gt as Le,H as Re,Hc as ze,Hi as Be,Hn as Ve,Ho as He,Hr as Ue,Ht as We,I as Ge,Ic as Ke,Ii as qe,In as Je,Io as Ye,Ir as Xe,It as Ze,J as Qe,Ja as $e,Ji as et,Jn as tt,Jr as nt,Js as rt,Jt as it,K as at,Ka as ot,Ki as st,Kn as ct,Ko as lt,Kr as ut,Ks as dt,Kt as ft,L as pt,Lc as mt,Li as ht,Ln as gt,Lo as _t,Lr as vt,Ls as yt,Lt as bt,M as xt,Ma as St,Mc as Ct,Mi as wt,Mn as Tt,Mr as Et,Ms as Dt,Mt as Ot,N as kt,Na as At,Nc as jt,Ni as Mt,Nn as Nt,No as Pt,Nr as Ft,Ns as It,Nt as Lt,O as Rt,Oa as zt,Oc as Bt,Oi as Vt,On as Ht,Oo as Ut,Or as Wt,Os as Gt,Ot as Kt,P as qt,Pa as Jt,Pc as Yt,Pi as Xt,Pn as Zt,Po as Qt,Pr as $t,Ps as en,Pt as tn,Q as nn,Qa as rn,Qi as an,Qn as on,Qr as sn,Qt as cn,R as ln,Ra as un,Rc as dn,Ri as fn,Rn as pn,Rr as eee,Rs as mn,Rt as hn,S as gn,Sa as _n,Sc as vn,Si as yn,Sn as bn,So as xn,Sr as Sn,St as Cn,T as wn,Ta as Tn,Tc as En,Ti as Dn,Tn as On,To as kn,Tr as tee,Ts as nee,Tt as ree,U as An,Ua as jn,Uc as Mn,Ui as Nn,Un as Pn,Uo as Fn,Ur as In,Ut as Ln,V as Rn,Va as zn,Vc as Bn,Vi as Vn,Vn as Hn,Vo as Un,Vr as Wn,Vt as Gn,W as Kn,Wa as qn,Wc as Jn,Wi as Yn,Wn as Xn,Wo as Zn,Wr as Qn,Wt as $n,Xa as er,Xi as tr,Xn as nr,Xo as rr,Xr as ir,Xs as ar,Xt as or,Y as sr,Ya as cr,Yi as lr,Yn as ur,Yo as dr,Yr as fr,Ys as pr,Yt as iee,Z as mr,Za as hr,Zi as gr,Zn as _r,Zo as vr,Zr as aee,Zt as oee,_ as yr,_a as br,_c as xr,_i as Sr,_n as Cr,_o as wr,_r as Tr,_s as Er,_t as Dr,aa as see,ai as Or,an as cee,ao as kr,ar as Ar,as as jr,at as Mr,b as Nr,ba as Pr,bc as Fr,bi as Ir,bn as Lr,br as Rr,bs as zr,bt as Br,c as Vr,ca as Hr,cc as Ur,ci as Wr,cn as lee,co as Gr,cr as Kr,cs as uee,ct as qr,d as Jr,da as Yr,dc as Xr,di as Zr,dn as Qr,do as $r,dr as dee,ds as ei,dt as ti,ea as fee,ec as ni,ei as ri,en as pee,eo as ii,er as ai,es as oi,f as si,fa as ci,fc as li,fi as ui,fn as di,fo as fi,fr as pi,fs as mi,ft as hi,g as gi,ga as _i,gc as vi,gi as yi,gn as bi,go as xi,gr as mee,gs as Si,gt as Ci,h as wi,ha as Ti,hc as Ei,hi as Di,hn as Oi,ho as ki,hr as hee,hs as Ai,ht as ji,i as Mi,ia as Ni,ic as Pi,ii as Fi,in as Ii,io as Li,ir as Ri,is as zi,it as Bi,j as Vi,ja as Hi,jc as Ui,ji as Wi,jn as Gi,jo as Ki,jr as gee,js as _ee,jt as vee,k as qi,ka as Ji,kc as Yi,ki as Xi,kn as yee,kr as Zi,ks as Qi,kt as bee,l as $i,la as xee,lc as ea,li as ta,ln as See,lo as na,lr as ra,ls as ia,lt as aa,m as oa,ma as sa,mc as ca,mi as la,mn as ua,mo as da,mr as fa,mt as pa,n as ma,na as Cee,nc as ha,ni as ga,nn as _a,no as va,nr as ya,nt as ba,oa as wee,oi as xa,on as Sa,oo as Ca,or as wa,os as Ta,ot as Ea,p as Da,pa as Oa,pc as ka,pi as Aa,pn as ja,pr as Ma,ps as Na,pt as Pa,q as Fa,qa as Ia,qi as Tee,qn as La,qo as Ra,qr as za,qs as Ba,qt as Eee,r as Va,ra as Dee,rc as Ha,ri as Ua,rn as Wa,ro as Ga,rr as Ka,rs as qa,rt as Ja,s as Ya,sa as Oee,sc as Xa,si as Za,sn as kee,so as Qa,sr as $a,st as eo,t as to,ta as Aee,tc as no,ti as ro,tn as io,to as ao,tr as oo,ts as so,tt as co,u as lo,ua as uo,uc as fo,ui as po,un as mo,uo as ho,ur as go,us as _o,ut as vo,v as yo,va as bo,vc as xo,vi as So,vn as Co,vr as wo,vs as To,vt as Eo,w as Do,wa as Oo,wc as ko,wi as Ao,wn as jo,wr as jee,ws as Mo,wt as Mee,x as No,xa as Po,xc as Fo,xi as Io,xn as Lo,xo as Ro,xr as zo,xs as Bo,xt as Vo,y as Ho,ya as Uo,yc as Wo,yi as Nee,yn as Pee,yo as Fee,yr as Iee,ys as Lee,yt as Go,z as Ree,za as zee,zc as Ko,zi as Bee,zn as Vee,zo as Hee,zr as qo,zs as Uee,zt as Wee}from"./src-CDcerRX2.mjs";import{$t as Gee,A as Jo,At as Yo,B as Xo,Bt as Zo,Ct as Kee,D as qee,Dt as Qo,Et as $o,Gt as A,H as es,Ht as j,I as Jee,It as M,J as Yee,Jt as ts,K as ns,Kt as Xee,Lt as rs,Mt as is,Nt as as,O as os,Pt as ss,Qt as Zee,R as Qee,Rt as N,St as $ee,Tt as ete,U as tte,Ut as P,V as cs,Vt as ls,W as us,Wt as ds,Yt as nte,_ as rte,_t as fs,a as ps,an as ite,b as ms,bt as ate,cn as hs,dt as gs,en as ote,ft as ste,gt as _s,ht as vs,i as ys,in as cte,it as bs,j as xs,jt as lte,k as Ss,kt as F,ln as Cs,nn as ws,o as ute,on as dte,p as fte,pt as Ts,qt as pte,rn as Es,s as mte,sn as hte,st as gte,t as Ds,tn as _te,ut as Os,vt as ks,xt as vte,y as As,z as js,zt as I}from"./sleep-CFk6IVkN.mjs";import{c as Ms,i as Ns,l as yte,n as Ps,s as Fs}from"./esm-DxvI2ZVA.mjs";import{n as Is,t as Ls}from"./md-manager-BcWiy3AP.mjs";import{A as Rs,C as zs,E as Bs,F as Vs,L as Hs,M as Us,N as Ws,S as Gs,T as Ks,_ as qs,a as Js,b as bte,c as Ys,d as Xs,f as Zs,g as Qs,h as $s,i as xte,j as ec,k as Ste,l as tc,m as nc,n as rc,o as ic,p as ac,r as Cte,s as wte,t as oc,u as sc,v as cc,w as lc,x as uc,y as dc}from"./fs-traced-C8gNIaHq.mjs";import{E as Tte,T as Ete,a as fc,b as pc,l as Dte,p as Ote,r as L,s as mc,v as kte,w as Ate,x as hc,y as gc}from"./logger-Dq-cRhcP.mjs";import{a as _c,c as jte,i as vc,l as Mte,o as Nte,r as yc,s as bc,t as xc}from"./git-handle-DnoBon5O.mjs";import{C as Pte,S as Sc,a as Cc,b as wc,d as Tc,i as Fte,n as Ite,o as Ec,r as Dc,v as Oc,y as kc}from"./server-lock-BIDrb6q3.mjs";import{t as Ac}from"./libesm-DzwC_yFw.mjs";import{t as jc}from"./yazl-DejPO9b3.mjs";import{t as Mc}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as Nc,c as Pc,d as Fc,f as Ic,h as Lc,i as Rc,l as zc,m as Bc,n as Vc,o as Hc,p as Uc,r as Wc,s as Gc,t as Kc,u as qc}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as Jc,B as Yc,C as Xc,D as Zc,E as Qc,F as $c,H as el,I as tl,L as nl,M as rl,N as il,O as al,P as ol,S as sl,T as cl,V as ll,_ as ul,a as dl,b as fl,c as pl,d as ml,f as hl,g as gl,h as _l,i as vl,j as yl,k as bl,l as xl,m as Lte,n as Rte,o as Sl,p as Cl,r as wl,s as Tl,t as zte,u as El,v as Dl,w as Ol,x as kl,y as Al,z as jl}from"./chunk-BGSUD5R5-Cj4a16wX.mjs";import{a as Ml,c as Nl,d as Pl,i as Fl,l as Il,n as Bte,o as Vte,r as Hte,s as Ll,t as Ute,u as Rl}from"./chunk-KX3P26DQ-KA7oOKfS.mjs";import{n as zl,r as Bl,t as Vl}from"./chunk-R6VWJ2ZL-B9eBwYXQ.mjs";import{r as Hl}from"./chunk-CWQS3NFK-BmYxhDXa.mjs";import{t as Ul}from"./chunk-DXB73IDG-Dx7prHrO.mjs";import{n as Wl,t as Gl}from"./chunk-5QMZ5MUS-BliBLsUm.mjs";import{n as Wte,t as Gte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as Kl,r as ql,t as Jl}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Kte,t as Yl}from"./chunk-24IMIIXA-C3WrrB2N.mjs";import{n as Xl}from"./chunk-3THT3N7L-Be-SmWEj.mjs";import{t as Zl}from"./chunk-44UOCSGV-CZohvp0c.mjs";import{t as qte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as Ql}from"node:module";import{execFile as $l,execFileSync as Jte,spawn as eu,spawnSync as tu}from"node:child_process";import*as nu from"node:path";import{basename as ru,delimiter as iu,dirname as R,extname as au,isAbsolute as ou,join as z,normalize as su,parse as cu,posix as lu,relative as B,resolve as V,sep as H,win32 as Yte}from"node:path";import{URLSearchParams as Xte,fileURLToPath as uu,pathToFileURL as du}from"node:url";import*as fu from"node:fs";import{appendFileSync as Zte,chmodSync as pu,closeSync as mu,constants as hu,createReadStream as gu,createWriteStream as _u,existsSync as U,fstatSync as Qte,lstatSync as vu,mkdirSync as yu,mkdtempSync as bu,openSync as xu,opendirSync as Su,readFile as $te,readFileSync as W,readSync as Cu,readdirSync as wu,readlinkSync as Tu,realpathSync as G,renameSync as Eu,rmSync as Du,rmdirSync as Ou,statSync as ku,unlinkSync as Au,writeFileSync as ju,writeSync as ene}from"node:fs";import{arch as Mu,availableParallelism as tne,homedir as Nu,hostname as Pu,platform as Fu,tmpdir as Iu}from"node:os";import{access as Lu,chmod as nne,constants as Ru,lstat as zu,readFile as Bu,readdir as Vu,realpath as Hu,stat as Uu,writeFile as rne}from"node:fs/promises";import{Readable as Wu,Transform as ine,Writable as ane}from"node:stream";import Gu,{createHash as Ku,randomUUID as qu,webcrypto as Ju}from"node:crypto";import one from"crypto";import{Readable as Yu}from"stream";import{EventEmitter as sne}from"node:events";import{readdirSync as cne,statSync as lne}from"fs";import{join as Xu,resolve as une}from"path";import{Worker as dne}from"node:worker_threads";import{monitorEventLoopDelay as fne,performance as Zu}from"node:perf_hooks";import{createInterface as pne}from"node:readline";import{pipeline as Qu}from"node:stream/promises";import{setImmediate as mne,setTimeout as $u}from"node:timers/promises";import{promisify as ed}from"node:util";import{request as hne}from"node:http";import{Http2ServerRequest as td,constants as gne}from"node:http2";import{lookup as _ne}from"node:dns/promises";import{request as vne}from"node:https";import{createBrotliDecompress as yne,createGunzip as bne,createInflate as xne}from"node:zlib";import*as Sne from"node:querystring";import{Http2ServerRequest as nd,constants as Cne}from"http2";import{AsyncLocalStorage as wne}from"node:async_hooks";import{lookup as Tne}from"node:dns";import Ene from"node:tls";var rd=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=W(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=ou(t)?t:V(this.gitDir,t))}catch(e){if(!sd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=W(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return sd(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]}:ld(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=W(z(t.path,`config`),`utf-8`)}catch(e){return sd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Dne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!cd(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(`..`)||ou(r))return{kind:`invalid`};try{let e=W(n,`utf-8`).trim(),t=Ane(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!sd(e))return{kind:`unreadable`,cause:e}}let i;try{i=W(z(t.path,`packed-refs`),`utf-8`)}catch(e){return sd(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 ld(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function id(e){return od(V(e),``)}function ad(e){let t=V(e),n=V(Nu());if(t===n)return{kind:`absent`};let r=od(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=od(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function od(e,t){let n=z(e,`.git`),r;try{r=ku(n)}catch(e){return sd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new rd(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=W(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=ou(o)?o:V(e,o);try{if(!ku(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 rd(`linked`,e,t,n,s)}}function Dne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=One(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=kne(i[1]);if(a.length>0)return a}return null}function One(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function kne(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function sd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function cd(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Ane(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?cd(t[1])?{kind:`symbolic`,target:t[1]}:null:ld(e)?{kind:`oid`,oid:e}:null}function ld(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const ud=`ok-generator`;function jne(e){return`git-author-${Yi(e.trim().toLowerCase())}`}const Mne=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function dd(e){let t=ad(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 fd(e){let t=dd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function pd(e){let t=dd(e);switch(t.kind){case`directory`:return V(t.path,md(t.projectSubPath));case`linked`:if(!U(t.path))throw new hd(t.gitPath,t.path);return V(t.path,md(t.projectSubPath));case`malformed-pointer`:throw new hd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new gd(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function md(e){return e===``?`ok`:`ok-${Nne(e)}`}function Nne(e){let t=e.split(H).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Pne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Pne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var hd=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,n){let r=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${r}. Run \`git worktree prune\` from the source repo and try again.`,n),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},gd=class extends Error{gitPath;constructor(e,t){let n=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${n}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function Fne(e){let t;try{t=pd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return U(V(t,`HEAD`))?t:null}function _d(e){return`refs/wip/${e}/`}function Ine(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{$ as r,$a as i,$i as a,$n as o,$o as s,$r as c,$s as l,$t as u,A as d,Aa as f,Ac as p,Ai as m,An as h,Ao as g,Ar as _,As as v,At as y,B as b,Ba as x,Bc as S,Bi as C,Bn as w,Bo as T,Br as E,Bt as D,C as ee,Ca as te,Cc as O,Ci as ne,Cn as re,Co as ie,Cr as ae,Cs as oe,Ct as se,D as ce,Da as le,Dc as ue,Di as de,Dn as fe,Do as pe,Dr as me,Ds as he,Dt as ge,E as _e,Ec as ve,Ei as ye,En as be,Er as xe,Es as Se,Et as Ce,F as we,Fa as Te,Fc as k,Fi as Ee,Fn as De,Fo as Oe,Fr as ke,Fs as Ae,Ft as je,G as Me,Ga as Ne,Gi as Pe,Gn as Fe,Gr as Ie,Gt as Le,H as Re,Hc as ze,Hi as Be,Hn as Ve,Ho as He,Hr as Ue,Ht as We,I as Ge,Ic as Ke,Ii as qe,In as Je,Io as Ye,Ir as Xe,It as Ze,J as Qe,Ja as $e,Ji as et,Jn as tt,Jr as nt,Js as rt,Jt as it,K as at,Ka as ot,Ki as st,Kn as ct,Ko as lt,Kr as ut,Ks as dt,Kt as ft,L as pt,Lc as mt,Li as ht,Ln as gt,Lo as _t,Lr as vt,Ls as yt,Lt as bt,M as xt,Ma as St,Mc as Ct,Mi as wt,Mn as Tt,Mr as Et,Ms as Dt,Mt as Ot,N as kt,Na as At,Nc as jt,Ni as Mt,Nn as Nt,No as Pt,Nr as Ft,Ns as It,Nt as Lt,O as Rt,Oa as zt,Oc as Bt,Oi as Vt,On as Ht,Oo as Ut,Or as Wt,Os as Gt,Ot as Kt,P as qt,Pa as Jt,Pc as Yt,Pi as Xt,Pn as Zt,Po as Qt,Pr as $t,Ps as en,Pt as tn,Q as nn,Qa as rn,Qi as an,Qn as on,Qr as sn,Qt as cn,R as ln,Ra as un,Rc as dn,Ri as fn,Rn as pn,Rr as eee,Rs as mn,Rt as hn,S as gn,Sa as _n,Sc as vn,Si as yn,Sn as bn,So as xn,Sr as Sn,St as Cn,T as wn,Ta as Tn,Tc as En,Ti as Dn,Tn as On,To as kn,Tr as tee,Ts as nee,Tt as ree,U as An,Ua as jn,Uc as Mn,Ui as Nn,Un as Pn,Uo as Fn,Ur as In,Ut as Ln,V as Rn,Va as zn,Vc as Bn,Vi as Vn,Vn as Hn,Vo as Un,Vr as Wn,Vt as Gn,W as Kn,Wa as qn,Wc as Jn,Wi as Yn,Wn as Xn,Wo as Zn,Wr as Qn,Wt as $n,Xa as er,Xi as tr,Xn as nr,Xo as rr,Xr as ir,Xs as ar,Xt as or,Y as sr,Ya as cr,Yi as lr,Yn as ur,Yo as dr,Yr as fr,Ys as pr,Yt as iee,Z as mr,Za as hr,Zi as gr,Zn as _r,Zo as vr,Zr as aee,Zt as oee,_ as yr,_a as br,_c as xr,_i as Sr,_n as Cr,_o as wr,_r as Tr,_s as Er,_t as Dr,aa as see,ai as Or,an as cee,ao as kr,ar as Ar,as as jr,at as Mr,b as Nr,ba as Pr,bc as Fr,bi as Ir,bn as Lr,br as Rr,bs as zr,bt as Br,c as Vr,ca as Hr,cc as Ur,ci as Wr,cn as lee,co as Gr,cr as Kr,cs as uee,ct as qr,d as Jr,da as Yr,dc as Xr,di as Zr,dn as Qr,do as $r,dr as dee,ds as ei,dt as ti,ea as fee,ec as ni,ei as ri,en as pee,eo as ii,er as ai,es as oi,f as si,fa as ci,fc as li,fi as ui,fn as di,fo as fi,fr as pi,fs as mi,ft as hi,g as gi,ga as _i,gc as vi,gi as yi,gn as bi,go as xi,gr as mee,gs as Si,gt as Ci,h as wi,ha as Ti,hc as Ei,hi as Di,hn as Oi,ho as ki,hr as hee,hs as Ai,ht as ji,i as Mi,ia as Ni,ic as Pi,ii as Fi,in as Ii,io as Li,ir as Ri,is as zi,it as Bi,j as Vi,ja as Hi,jc as Ui,ji as Wi,jn as Gi,jo as Ki,jr as gee,js as _ee,jt as vee,k as qi,ka as Ji,kc as Yi,ki as Xi,kn as yee,kr as Zi,ks as Qi,kt as bee,l as $i,la as xee,lc as ea,li as ta,ln as See,lo as na,lr as ra,ls as ia,lt as aa,m as oa,ma as sa,mc as ca,mi as la,mn as ua,mo as da,mr as fa,mt as pa,n as ma,na as Cee,nc as ha,ni as ga,nn as _a,no as va,nr as ya,nt as ba,oa as wee,oi as xa,on as Sa,oo as Ca,or as wa,os as Ta,ot as Ea,p as Da,pa as Oa,pc as ka,pi as Aa,pn as ja,pr as Ma,ps as Na,pt as Pa,q as Fa,qa as Ia,qi as Tee,qn as La,qo as Ra,qr as za,qs as Ba,qt as Eee,r as Va,ra as Dee,rc as Ha,ri as Ua,rn as Wa,ro as Ga,rr as Ka,rs as qa,rt as Ja,s as Ya,sa as Oee,sc as Xa,si as Za,sn as kee,so as Qa,sr as $a,st as eo,t as to,ta as Aee,tc as no,ti as ro,tn as io,to as ao,tr as oo,ts as so,tt as co,u as lo,ua as uo,uc as fo,ui as po,un as mo,uo as ho,ur as go,us as _o,ut as vo,v as yo,va as bo,vc as xo,vi as So,vn as Co,vr as wo,vs as To,vt as Eo,w as Do,wa as Oo,wc as ko,wi as Ao,wn as jo,wr as jee,ws as Mo,wt as Mee,x as No,xa as Po,xc as Fo,xi as Io,xn as Lo,xo as Ro,xr as zo,xs as Bo,xt as Vo,y as Ho,ya as Uo,yc as Wo,yi as Nee,yn as Pee,yo as Fee,yr as Iee,ys as Lee,yt as Go,z as Ree,za as zee,zc as Ko,zi as Bee,zn as Vee,zo as Hee,zr as qo,zs as Uee,zt as Wee}from"./src-CIngi0dD.mjs";import{$t as Gee,A as Jo,At as Yo,B as Xo,Bt as Zo,Ct as Kee,D as qee,Dt as Qo,Et as $o,Gt as A,H as es,Ht as j,I as Jee,It as M,J as Yee,Jt as ts,K as ns,Kt as Xee,Lt as rs,Mt as is,Nt as as,O as os,Pt as ss,Qt as Zee,R as Qee,Rt as N,St as $ee,Tt as ete,U as tte,Ut as P,V as cs,Vt as ls,W as us,Wt as ds,Yt as nte,_ as rte,_t as fs,a as ps,an as ite,b as ms,bt as ate,cn as hs,dt as gs,en as ote,ft as ste,gt as _s,ht as vs,i as ys,in as cte,it as bs,j as xs,jt as lte,k as Ss,kt as F,ln as Cs,nn as ws,o as ute,on as dte,p as fte,pt as Ts,qt as pte,rn as Es,s as mte,sn as hte,st as gte,t as Ds,tn as _te,ut as Os,vt as ks,xt as vte,y as As,z as js,zt as I}from"./sleep-CFk6IVkN.mjs";import{c as Ms,i as Ns,l as yte,n as Ps,s as Fs}from"./esm-DxvI2ZVA.mjs";import{n as Is,t as Ls}from"./md-manager-B0rABilg.mjs";import{A as Rs,C as zs,E as Bs,F as Vs,L as Hs,M as Us,N as Ws,S as Gs,T as Ks,_ as qs,a as Js,b as bte,c as Ys,d as Xs,f as Zs,g as Qs,h as $s,i as xte,j as ec,k as Ste,l as tc,m as nc,n as rc,o as ic,p as ac,r as Cte,s as wte,t as oc,u as sc,v as cc,w as lc,x as uc,y as dc}from"./fs-traced-C8gNIaHq.mjs";import{E as Tte,T as Ete,a as fc,b as pc,l as Dte,p as Ote,r as L,s as mc,v as kte,w as Ate,x as hc,y as gc}from"./logger-Dq-cRhcP.mjs";import{a as _c,c as jte,i as vc,l as Mte,o as Nte,r as yc,s as bc,t as xc}from"./git-handle-C9RU-MxT.mjs";import{C as Pte,S as Sc,a as Cc,b as wc,d as Tc,i as Fte,n as Ite,o as Ec,r as Dc,v as Oc,y as kc}from"./server-lock-CGm9uKLf.mjs";import{t as Ac}from"./libesm-DzwC_yFw.mjs";import{t as jc}from"./yazl-DejPO9b3.mjs";import{t as Mc}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as Nc,c as Pc,d as Fc,f as Ic,h as Lc,i as Rc,l as zc,m as Bc,n as Vc,o as Hc,p as Uc,r as Wc,s as Gc,t as Kc,u as qc}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as Jc,B as Yc,C as Xc,D as Zc,E as Qc,F as $c,H as el,I as tl,L as nl,M as rl,N as il,O as al,P as ol,S as sl,T as cl,V as ll,_ as ul,a as dl,b as fl,c as pl,d as ml,f as hl,g as gl,h as _l,i as vl,j as yl,k as bl,l as xl,m as Lte,n as Rte,o as Sl,p as Cl,r as wl,s as Tl,t as zte,u as El,v as Dl,w as Ol,x as kl,y as Al,z as jl}from"./chunk-BGSUD5R5-Cj4a16wX.mjs";import{a as Ml,c as Nl,d as Pl,i as Fl,l as Il,n as Bte,o as Vte,r as Hte,s as Ll,t as Ute,u as Rl}from"./chunk-KX3P26DQ-KA7oOKfS.mjs";import{n as zl,r as Bl,t as Vl}from"./chunk-R6VWJ2ZL-B9eBwYXQ.mjs";import{r as Hl}from"./chunk-CWQS3NFK-BmYxhDXa.mjs";import{t as Ul}from"./chunk-DXB73IDG-Dx7prHrO.mjs";import{n as Wl,t as Gl}from"./chunk-5QMZ5MUS-BliBLsUm.mjs";import{n as Wte,t as Gte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as Kl,r as ql,t as Jl}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Kte,t as Yl}from"./chunk-24IMIIXA-C3WrrB2N.mjs";import{n as Xl}from"./chunk-3THT3N7L-Be-SmWEj.mjs";import{t as Zl}from"./chunk-44UOCSGV-CZohvp0c.mjs";import{t as qte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as Ql}from"node:module";import{execFile as $l,execFileSync as Jte,spawn as eu,spawnSync as tu}from"node:child_process";import*as nu from"node:path";import{basename as ru,delimiter as iu,dirname as R,extname as au,isAbsolute as ou,join as z,normalize as su,parse as cu,posix as lu,relative as B,resolve as V,sep as H,win32 as Yte}from"node:path";import{URLSearchParams as Xte,fileURLToPath as uu,pathToFileURL as du}from"node:url";import*as fu from"node:fs";import{appendFileSync as Zte,chmodSync as pu,closeSync as mu,constants as hu,createReadStream as gu,createWriteStream as _u,existsSync as U,fstatSync as Qte,lstatSync as vu,mkdirSync as yu,mkdtempSync as bu,openSync as xu,opendirSync as Su,readFile as $te,readFileSync as W,readSync as Cu,readdirSync as wu,readlinkSync as Tu,realpathSync as G,renameSync as Eu,rmSync as Du,rmdirSync as Ou,statSync as ku,unlinkSync as Au,writeFileSync as ju,writeSync as ene}from"node:fs";import{arch as Mu,availableParallelism as tne,homedir as Nu,hostname as Pu,platform as Fu,tmpdir as Iu}from"node:os";import{access as Lu,chmod as nne,constants as Ru,lstat as zu,readFile as Bu,readdir as Vu,realpath as Hu,stat as Uu,writeFile as rne}from"node:fs/promises";import{Readable as Wu,Transform as ine,Writable as ane}from"node:stream";import Gu,{createHash as Ku,randomUUID as qu,webcrypto as Ju}from"node:crypto";import one from"crypto";import{Readable as Yu}from"stream";import{EventEmitter as sne}from"node:events";import{readdirSync as cne,statSync as lne}from"fs";import{join as Xu,resolve as une}from"path";import{Worker as dne}from"node:worker_threads";import{monitorEventLoopDelay as fne,performance as Zu}from"node:perf_hooks";import{createInterface as pne}from"node:readline";import{pipeline as Qu}from"node:stream/promises";import{setImmediate as mne,setTimeout as $u}from"node:timers/promises";import{promisify as ed}from"node:util";import{request as hne}from"node:http";import{Http2ServerRequest as td,constants as gne}from"node:http2";import{lookup as _ne}from"node:dns/promises";import{request as vne}from"node:https";import{createBrotliDecompress as yne,createGunzip as bne,createInflate as xne}from"node:zlib";import*as Sne from"node:querystring";import{Http2ServerRequest as nd,constants as Cne}from"http2";import{AsyncLocalStorage as wne}from"node:async_hooks";import{lookup as Tne}from"node:dns";import Ene from"node:tls";var rd=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=W(z(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=ou(t)?t:V(this.gitDir,t))}catch(e){if(!sd(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=W(z(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return sd(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]}:ld(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=W(z(t.path,`config`),`utf-8`)}catch(e){return sd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Dne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!cd(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(`..`)||ou(r))return{kind:`invalid`};try{let e=W(n,`utf-8`).trim(),t=Ane(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!sd(e))return{kind:`unreadable`,cause:e}}let i;try{i=W(z(t.path,`packed-refs`),`utf-8`)}catch(e){return sd(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 ld(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function id(e){return od(V(e),``)}function ad(e){let t=V(e),n=V(Nu());if(t===n)return{kind:`absent`};let r=od(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=od(e,B(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function od(e,t){let n=z(e,`.git`),r;try{r=ku(n)}catch(e){return sd(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new rd(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=W(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=ou(o)?o:V(e,o);try{if(!ku(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 rd(`linked`,e,t,n,s)}}function Dne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=One(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=kne(i[1]);if(a.length>0)return a}return null}function One(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function kne(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function sd(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function cd(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Ane(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?cd(t[1])?{kind:`symbolic`,target:t[1]}:null:ld(e)?{kind:`oid`,oid:e}:null}function ld(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}const ud=`ok-generator`;function jne(e){return`git-author-${Yi(e.trim().toLowerCase())}`}const Mne=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service|ok-generator)$/;function dd(e){let t=ad(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 fd(e){let t=dd(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function pd(e){let t=dd(e);switch(t.kind){case`directory`:return V(t.path,md(t.projectSubPath));case`linked`:if(!U(t.path))throw new hd(t.gitPath,t.path);return V(t.path,md(t.projectSubPath));case`malformed-pointer`:throw new hd(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new gd(t.gitPath,{cause:t.cause});case`absent`:return V(e,`.git/ok`)}}function md(e){return e===``?`ok`:`ok-${Nne(e)}`}function Nne(e){let t=e.split(H).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Pne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Pne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var hd=class extends Error{gitPointerPath;resolvedTarget;constructor(e,t,n){let r=t?`references a missing or unreadable gitdir at ${t}`:`is unreadable or has no valid gitdir: pointer`;super(`\`.git\` pointer at ${e} ${r}. Run \`git worktree prune\` from the source repo and try again.`,n),this.name=`MalformedGitPointerError`,this.gitPointerPath=e,this.resolvedTarget=t}},gd=class extends Error{gitPath;constructor(e,t){let n=t?.cause!==void 0&&t.cause!==null&&typeof t.cause==`object`&&`code`in t.cause&&typeof t.cause.code==`string`?` (${t.cause.code})`:``;super(`Cannot access \`.git\` at ${e}${n}. Check filesystem permissions and that the volume is mounted.`,t),this.name=`GitDirAccessError`,this.gitPath=e}};function Fne(e){let t;try{t=pd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return U(V(t,`HEAD`))?t:null}function _d(e){return`refs/wip/${e}/`}function Ine(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 vd=`ok-actor: `;function yd(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),`${vd}${JSON.stringify(i)}`}function bd(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=Lne(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 Lne(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 Rne(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(vd))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:bd(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(vd))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=bd(r);i&&t.push(i)}return t}function zne(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 Sd(e){let t=xd(e);return t.length>0?t.map(zne):Ine(e)}function Cd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function wd(e){return`reconcile: ${e}`}function Td(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Bne(e,t){return`park: ${e} -> ${t}`}function Ed(e,t){return`rename: ${e} -> ${t}`}function Dd(e){return`checkpoint: ${e}`}function Vne(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Hne=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Od(e){return e.replace(Hne,` `)}function Une(e,t){let n=Od(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=Od(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 kd(e){return Mne.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:e===`ok-generator`?{id:e,classification:`classified-ok-generator`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function Ad(e){let t=dd(e);if(t.kind!==`linked`)return V(e);try{let n=W(z(t.path,`commondir`),`utf-8`).trim();return n===``?V(e):V(R(V(t.path,n)),t.projectSubPath)}catch{return V(e)}}function jd(e){return e.kind??`other`}function Wne(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Md=class{filePath;log;grants=null;constructor(e,t){this.filePath=z(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=jd(t),i=Wne(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=jd(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-CMCYO7L0.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(W(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 Nd=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Pd={"claude-acp":`claude`,"codex-acp":`codex`,opencode:`opencode`,"pi-acp":`pi`},Fd=`acp-agents.json`,Id=`acp-registry-cache.json`;function Ld(){let e=Fu(),t=Mu(),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 Rd=new Set([`goose`,`fast-agent`,`crow-cli`]);function zd(e,t){let n=t.trim();return n.length===0?e:Rd.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Bd(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 Vd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Bd).map(e=>({...e,name:zd(e.id,e.name)})):null}var Hd=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=Vd(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-CMCYO7L0.mjs`);await e(this.localDir,{recursive:!0}),await n(z(this.localDir,Id),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=Vd(await Bu(z(this.localDir,Id),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Ud(e,t){let n;try{n=await Bu(z(e,Fd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Fd} 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 ${Fd} entry`)}return i}const Wd={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`},Gd={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`},Gne={cancel_request:`$/cancel_request`},Kd=Symbol(`skippedItem`);function K(e,t){return e.catch(t)}function qd(e,t){let n=e.catch(t);return A().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Cs):n.parse(e))}function Jd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Yd(e,t,n){return e.superRefine((e,r)=>{let i=Jd(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 Xd(e,t,n){return A().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Cs}let o=a.data,s=Jd(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 Zd(e){return F(e.catch(Kd)).transform(e=>e.filter(e=>e!==Kd))}const Qd=ds([N(),P()]).nullable(),$d=P(),ef=I({sessionId:$d,path:P(),content:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),tf=I({sessionId:$d,path:P(),line:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),nf=P(),rf=ds([M(`read`),M(`edit`),M(`delete`),M(`move`),M(`search`),M(`execute`),M(`think`),M(`fetch`),M(`switch_mode`),M(`other`)]),af=ds([M(`pending`),M(`in_progress`),M(`completed`),M(`failed`)]),of=I({audience:K(Zd(ds([M(`assistant`),M(`user`)])).nullish(),()=>void 0),lastModified:K(P().nullish(),()=>void 0),priority:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),sf=I({annotations:K(of.nullish(),()=>void 0),text:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),cf=I({annotations:K(of.nullish(),()=>void 0),data:P(),mimeType:P(),uri:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),lf=I({annotations:K(of.nullish(),()=>void 0),data:P(),mimeType:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),uf=I({annotations:K(of.nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),mimeType:K(P().nullish(),()=>void 0),name:P(),size:K(N().nullish(),()=>void 0),title:K(P().nullish(),()=>void 0),uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),df=ds([I({mimeType:K(P().nullish(),()=>void 0),text:P(),uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),I({blob:P(),mimeType:K(P().nullish(),()=>void 0),uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)})]),ff=I({annotations:K(of.nullish(),()=>void 0),resource:df,_meta:K(j(P(),A()).nullish(),()=>void 0)}),pf=ds([sf.and(I({type:M(`text`)})),cf.and(I({type:M(`image`)})),lf.and(I({type:M(`audio`)})),uf.and(I({type:M(`resource_link`)})),ff.and(I({type:M(`resource`)}))]),mf=I({content:pf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),hf=I({path:P(),oldText:K(P().nullish(),()=>void 0),newText:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),gf=P(),Kne=I({terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),_f=ds([mf.and(I({type:M(`content`)})),hf.and(I({type:M(`diff`)})),Kne.and(I({type:M(`terminal`)}))]),vf=I({path:P(),line:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),yf=I({toolCallId:nf,kind:K(rf.nullish(),()=>void 0),status:K(af.nullish(),()=>void 0),title:K(P().nullish(),()=>void 0),content:K(Zd(_f).nullish(),()=>void 0),locations:K(Zd(vf).nullish(),()=>void 0),rawInput:K(A().optional(),()=>void 0),rawOutput:K(A().optional(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),bf=P(),qne=ds([M(`allow_once`),M(`allow_always`),M(`reject_once`),M(`reject_always`)]),xf=I({sessionId:$d,toolCall:yf,options:F(I({optionId:bf,name:P(),kind:qne,_meta:K(j(P(),A()).nullish(),()=>void 0)})),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Sf=I({name:P(),value:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Cf=I({sessionId:$d,command:P(),args:K(Zd(P()).optional(),()=>[]),env:K(Zd(Sf).optional(),()=>[]),cwd:K(P().nullish(),()=>void 0),outputByteLimit:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),wf=I({sessionId:$d,terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Tf=I({sessionId:$d,terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ef=I({sessionId:$d,terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Df=I({sessionId:$d,terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Of=I({sessionId:$d,toolCallId:K(nf.nullish(),()=>void 0)}),kf=I({requestId:Qd}),Jne=M(`object`),Yne=ds([M(`email`),M(`uri`),M(`date`),M(`date-time`)]),Af=I({const:P(),title:P(),description:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),jf=I({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minLength:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:P().nullish(),format:Yne.nullish(),default:K(P().nullish(),()=>void 0),enum:F(P()).nullish(),oneOf:F(Af).nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Mf=I({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Nf=I({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minimum:N().nullish(),maximum:N().nullish(),default:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Pf=I({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),default:K(Yo().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ff=I({enum:F(P()),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Xne=I({anyOf:F(Af),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Zne=Xd(ds([Ff.and(I({type:M(`string`)})),Yd(I({type:P()}),`type`,[`string`]),Xne]),`type`,[`string`]),If=I({title:K(P().nullish(),()=>void 0),description:K(P().nullish(),()=>void 0),minItems:N().nullish(),maxItems:N().nullish(),items:Zne,default:K(Zd(P()).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Qne=Xd(ds([jf.and(I({type:M(`string`)})),Mf.and(I({type:M(`number`)})),Nf.and(I({type:M(`integer`)})),Pf.and(I({type:M(`boolean`)})),If.and(I({type:M(`array`)})),Yd(I({type:P()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),$ne=I({type:K(Jne.optional().default(`object`),()=>`object`),title:K(P().nullish(),()=>void 0),properties:j(P(),Qne).optional().default({}),required:F(P()).nullish(),description:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Lf=ss(ds([Of,kf]),I({requestedSchema:$ne})),Rf=P(),zf=ss(ds([Of,kf]),I({elicitationId:Rf,url:Xee()})),Bf=Xd(ss(ds([Lf.and(I({mode:M(`form`)})),zf.and(I({mode:M(`url`)})),Yd(ss(ds([Of,kf]),I({mode:P()})),`mode`,[`form`,`url`])]),I({message:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Vf=P(),ere=I({serverId:Vf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Hf=P(),Uf=I({connectionId:Hf,method:P(),params:j(P(),A()).nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),tre=I({connectionId:Hf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Wf=A();I({id:Qd,method:P(),params:ds([ef,tf,xf,Cf,wf,Tf,Ef,Df,Bf,ere,Uf,tre,Wf]).nullish()});const Gf=as().gte(0).lte(65535),nre=I({image:K(Yo().optional().default(!1),()=>!1),audio:K(Yo().optional().default(!1),()=>!1),embeddedContext:K(Yo().optional().default(!1),()=>!1),_meta:K(j(P(),A()).nullish(),()=>void 0)}),rre=I({http:K(Yo().optional().default(!1),()=>!1),sse:K(Yo().optional().default(!1),()=>!1),acp:K(Yo().optional().default(!1),()=>!1),_meta:K(j(P(),A()).nullish(),()=>void 0)}),ire=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),are=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),ore=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),sre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),cre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),lre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),ure=I({list:K(ire.nullish(),()=>void 0),delete:K(are.nullish(),()=>void 0),additionalDirectories:K(ore.nullish(),()=>void 0),fork:K(sre.nullish(),()=>void 0),resume:K(cre.nullish(),()=>void 0),close:K(lre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),dre=I({logout:K(I({_meta:K(j(P(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),fre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),pre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),mre=I({syncKind:ds([M(`full`),M(`incremental`)]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),hre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),gre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),_re=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),vre=I({document:K(I({didOpen:K(pre.nullish(),()=>void 0),didChange:K(mre.nullish(),()=>void 0),didClose:K(hre.nullish(),()=>void 0),didSave:K(gre.nullish(),()=>void 0),didFocus:K(_re.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),yre=I({maxCount:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),bre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),xre=I({maxCount:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Sre=I({maxCount:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Cre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),wre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Tre=I({recentFiles:K(yre.nullish(),()=>void 0),relatedSnippets:K(bre.nullish(),()=>void 0),editHistory:K(xre.nullish(),()=>void 0),userActions:K(Sre.nullish(),()=>void 0),openFiles:K(Cre.nullish(),()=>void 0),diagnostics:K(wre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ere=I({events:K(vre.nullish(),()=>void 0),context:K(Tre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Kf=ds([M(`utf-16`),M(`utf-32`),M(`utf-8`)]),Dre=I({loadSession:K(Yo().optional().default(!1),()=>!1),promptCapabilities:K(nre.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:K(rre.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:K(ure.optional().default({}),()=>({})),auth:K(dre.optional().default({}),()=>({})),providers:K(fre.nullish(),()=>void 0),nes:K(Ere.nullish(),()=>void 0),positionEncoding:K(Kf.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),qf=P(),Ore=I({name:P(),label:K(P().nullish(),()=>void 0),secret:K(Yo().optional().default(!0),()=>!0),optional:K(Yo().optional().default(!1),()=>!1),_meta:K(j(P(),A()).nullish(),()=>void 0)}),kre=I({id:qf,name:P(),description:K(P().nullish(),()=>void 0),vars:qd(Zd(Ore),()=>[]),link:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Are=I({id:qf,name:P(),description:K(P().nullish(),()=>void 0),args:K(Zd(P()).optional(),()=>[]),env:K(j(P(),P()).optional(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),jre=I({id:qf,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Mre=ds([kre.and(I({type:M(`env_var`)})),Are.and(I({type:M(`terminal`)})),jre]),Jf=I({name:P(),title:K(P().nullish(),()=>void 0),version:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Yf=I({protocolVersion:Gf,agentCapabilities:K(Dre.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:K(Zd(Mre).optional().default([]),()=>[]),agentInfo:K(Jf.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Xf=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Zf=P(),Qf=ds([M(`anthropic`),M(`openai`),M(`azure`),M(`vertex`),M(`bedrock`),P()]),$f=I({apiType:Qf,baseUrl:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),ep=I({providers:F(I({providerId:Zf,supported:qd(Zd(Qf),()=>[]),required:Yo(),current:$f.nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)})),_meta:K(j(P(),A()).nullish(),()=>void 0)}),tp=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),np=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),rp=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),ip=P(),ap=I({currentModeId:ip,availableModes:qd(Zd(I({id:ip,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)})),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),op=P(),sp=ds([M(`mode`),M(`model`),M(`model_config`),M(`thought_level`),P()]),cp=P(),lp=I({value:cp,name:P(),description:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),up=I({group:P(),name:P(),options:qd(Zd(lp),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),dp=I({currentValue:cp,options:ds([F(lp),F(up)])}),fp=I({currentValue:Yo()}),pp=ss(ds([dp.and(I({type:M(`select`)})),fp.and(I({type:M(`boolean`)}))]),I({id:op,name:P(),description:K(P().nullish(),()=>void 0),category:K(sp.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)})),mp=I({sessionId:$d,modes:K(ap.nullish(),()=>void 0),configOptions:K(Zd(pp).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),hp=I({modes:K(ap.nullish(),()=>void 0),configOptions:K(Zd(pp).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),gp=I({sessions:qd(Zd(I({sessionId:$d,cwd:P(),additionalDirectories:K(Zd(P()).optional(),()=>[]),title:K(P().nullish(),()=>void 0),updatedAt:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)})),()=>[]),nextCursor:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),_p=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),vp=I({sessionId:$d,modes:K(ap.nullish(),()=>void 0),configOptions:K(Zd(pp).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),yp=I({modes:K(ap.nullish(),()=>void 0),configOptions:K(Zd(pp).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),bp=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),xp=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Sp=I({configOptions:qd(Zd(pp),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Cp=I({stopReason:ds([M(`end_turn`),M(`max_tokens`),M(`max_turn_requests`),M(`refusal`),M(`cancelled`)]),usage:K(I({totalTokens:N(),inputTokens:N(),outputTokens:N(),thoughtTokens:K(N().nullish(),()=>void 0),cachedReadTokens:K(N().nullish(),()=>void 0),cachedWriteTokens:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),wp=I({sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Tp=P(),Ep=I({line:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Dp=I({start:Ep,end:Ep,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Op=I({range:Dp,newText:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),kp=I({id:Tp,uri:P(),edits:F(Op),cursorPosition:K(Ep.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ap=I({id:Tp,uri:P(),position:Ep,_meta:K(j(P(),A()).nullish(),()=>void 0)}),jp=I({id:Tp,uri:P(),position:Ep,newName:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Mp=I({id:Tp,uri:P(),search:P(),replace:P(),isRegex:Yo().nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Np=I({suggestions:F(ds([kp.and(I({kind:M(`edit`)})),Ap.and(I({kind:M(`jump`)})),jp.and(I({kind:M(`rename`)})),Mp.and(I({kind:M(`searchAndReplace`)}))])),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Pp=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Fp=A(),Ip=A(),Lp=I({code:ds([M(-32700),M(-32600),M(-32601),M(-32602),M(-32603),M(-32800),M(-32e3),M(-32002),as().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:P(),data:K(A().optional(),()=>void 0)});ds([I({id:Qd,result:ds([Yf,Xf,ep,tp,np,rp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Np,Pp,Fp,Ip])}),I({id:Qd,error:Lp})]);const Rp=I({content:pf,messageId:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),zp=I({toolCallId:nf,title:P(),kind:K(rf.optional(),()=>void 0),status:K(af.optional(),()=>void 0),content:K(Zd(_f).optional(),()=>[]),locations:K(Zd(vf).optional(),()=>[]),rawInput:K(A().optional(),()=>void 0),rawOutput:K(A().optional(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Bp=ds([M(`high`),M(`medium`),M(`low`)]),Vp=ds([M(`pending`),M(`in_progress`),M(`completed`)]),Hp=I({content:P(),priority:Bp,status:Vp,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Up=I({entries:qd(Zd(Hp),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Wp=P(),Gp=I({planId:Wp,entries:qd(Zd(Hp),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Kp=I({planId:Wp,uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),qp=I({planId:Wp,content:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Jp=I({plan:ds([Gp.and(I({type:M(`items`)})),Kp.and(I({type:M(`file`)})),qp.and(I({type:M(`markdown`)}))]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Yp=I({planId:Wp,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Xp=I({hint:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Nre=I({availableCommands:qd(Zd(I({name:P(),description:P(),input:K(Xp.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)})),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Pre=I({currentModeId:ip,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Fre=I({configOptions:qd(Zd(pp),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ire=I({title:K(P().nullish(),()=>void 0),updatedAt:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Lre=I({amount:N(),currency:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Rre=I({used:N(),size:N(),cost:K(Lre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Zp=I({sessionId:$d,update:ds([Rp.and(I({sessionUpdate:M(`user_message_chunk`)})),Rp.and(I({sessionUpdate:M(`agent_message_chunk`)})),Rp.and(I({sessionUpdate:M(`agent_thought_chunk`)})),zp.and(I({sessionUpdate:M(`tool_call`)})),yf.and(I({sessionUpdate:M(`tool_call_update`)})),Up.and(I({sessionUpdate:M(`plan`)})),Jp.and(I({sessionUpdate:M(`plan_update`)})),Yp.and(I({sessionUpdate:M(`plan_removed`)})),Nre.and(I({sessionUpdate:M(`available_commands_update`)})),Pre.and(I({sessionUpdate:M(`current_mode_update`)})),Fre.and(I({sessionUpdate:M(`config_option_update`)})),Ire.and(I({sessionUpdate:M(`session_info_update`)})),Rre.and(I({sessionUpdate:M(`usage_update`)}))]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Qp=I({elicitationId:Rf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),$p=I({connectionId:Hf,method:P(),params:K(j(P(),A()).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),em=A();I({method:P(),params:ds([Zp,Qp,$p,em]).nullish()});const zre=I({readTextFile:K(Yo().optional().default(!1),()=>!1),writeTextFile:K(Yo().optional().default(!1),()=>!1),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Bre=I({configOptions:K(I({boolean:K(I({_meta:K(j(P(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Vre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Hre=I({terminal:K(Yo().optional().default(!1),()=>!1),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ure=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Wre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Gre=I({form:K(Ure.nullish(),()=>void 0),url:K(Wre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Kre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),qre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Jre=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Yre=I({jump:K(Kre.nullish(),()=>void 0),rename:K(qre.nullish(),()=>void 0),searchAndReplace:K(Jre.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),tm=I({protocolVersion:Gf,clientCapabilities:K(I({fs:K(zre.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:K(Yo().optional().default(!1),()=>!1),session:K(Bre.nullish(),()=>void 0),plan:K(Vre.nullish(),()=>void 0),auth:K(Hre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:K(Gre.nullish(),()=>void 0),nes:K(Yre.nullish(),()=>void 0),positionEncodings:K(Zd(Kf).optional(),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:K(Jf.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),nm=I({methodId:qf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),rm=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),im=I({providerId:Zf,apiType:Qf,baseUrl:P(),headers:j(P(),P()).optional(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),am=I({providerId:Zf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),om=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),sm=I({name:P(),value:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Xre=I({name:P(),url:P(),headers:F(sm),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Zre=I({name:P(),url:P(),headers:F(sm),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Qre=I({name:P(),serverId:Vf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),$re=I({name:P(),command:P(),args:F(P()),env:F(Sf),_meta:K(j(P(),A()).nullish(),()=>void 0)}),cm=ds([Xre.and(I({type:M(`http`)})),Zre.and(I({type:M(`sse`)})),Qre.and(I({type:M(`acp`)})),$re]),lm=I({cwd:P(),additionalDirectories:K(Zd(P()).optional(),()=>[]),mcpServers:qd(Zd(cm),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),um=I({mcpServers:qd(Zd(cm),()=>[]),cwd:P(),additionalDirectories:K(Zd(P()).optional(),()=>[]),sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)}),dm=I({cwd:P().nullish(),cursor:P().nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),fm=I({sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)}),pm=I({sessionId:$d,cwd:P(),additionalDirectories:K(Zd(P()).optional(),()=>[]),mcpServers:K(Zd(cm).optional(),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),mm=I({sessionId:$d,cwd:P(),additionalDirectories:K(Zd(P()).optional(),()=>[]),mcpServers:K(Zd(cm).optional(),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),hm=I({sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)}),gm=I({sessionId:$d,modeId:ip,_meta:K(j(P(),A()).nullish(),()=>void 0)}),_m=ss(ds([I({value:Yo(),type:M(`boolean`)}),I({value:cp})]),I({sessionId:$d,configId:op,_meta:K(j(P(),A()).nullish(),()=>void 0)})),vm=I({sessionId:$d,prompt:F(pf),_meta:K(j(P(),A()).nullish(),()=>void 0)}),eie=I({uri:P(),name:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),tie=I({name:P(),owner:P(),remoteUrl:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),ym=I({workspaceUri:K(P().nullish(),()=>void 0),workspaceFolders:F(eie).nullish(),repository:K(tie.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),nie=ds([M(`automatic`),M(`diagnostic`),M(`manual`)]),rie=I({uri:P(),languageId:P(),text:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),iie=I({startLine:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),aie=I({uri:P(),excerpts:F(iie),_meta:K(j(P(),A()).nullish(),()=>void 0)}),oie=I({uri:P(),diff:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),sie=I({action:P(),uri:P(),position:Ep,timestampMs:N(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),cie=I({uri:P(),languageId:P(),visibleRange:K(Dp.nullish(),()=>void 0),lastFocusedMs:K(N().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),lie=ds([M(`error`),M(`warning`),M(`information`),M(`hint`)]),uie=I({uri:P(),range:Dp,severity:lie,message:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),die=I({recentFiles:F(rie).nullish(),relatedSnippets:F(aie).nullish(),editHistory:F(oie).nullish(),userActions:F(sie).nullish(),openFiles:F(cie).nullish(),diagnostics:F(uie).nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),bm=I({sessionId:$d,uri:P(),version:N(),position:Ep,selection:Dp.nullish(),triggerKind:nie,context:die.nullish(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),xm=I({sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)});I({id:Qd,method:P(),params:ds([tm,nm,rm,im,am,om,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Uf,Wf]).nullish()});const fie=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),pie=I({content:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),mie=I({optionId:bf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),hie=I({outcome:ds([I({outcome:M(`cancelled`)}),mie.and(I({outcome:M(`selected`)}))]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),gie=I({terminalId:gf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),_ie=I({exitCode:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),vie=I({output:P(),truncated:Yo(),exitStatus:K(_ie.nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),yie=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),bie=I({exitCode:K(as().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:K(P().nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)}),xie=I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Sie=ds([P(),N(),N(),Yo(),F(P())]),Sm=I({content:j(P(),Sie).nullish()});ds([I({id:Qd,result:ds([fie,pie,hie,gie,vie,yie,bie,xie,Xd(ss(ds([Sm.and(I({action:M(`accept`)})),I({action:M(`decline`)}),I({action:M(`cancel`)}),Yd(I({action:P()}),`action`,[`accept`,`cancel`,`decline`])]),I({_meta:K(j(P(),A()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),I({connectionId:Hf,_meta:K(j(P(),A()).nullish(),()=>void 0)}),I({_meta:K(j(P(),A()).nullish(),()=>void 0)}),Ip,Fp])}),I({id:Qd,error:Lp})]);const Cm=I({sessionId:$d,_meta:K(j(P(),A()).nullish(),()=>void 0)}),wm=I({sessionId:$d,uri:P(),languageId:P(),version:N(),text:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Cie=I({range:Dp.nullish(),text:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Tm=I({sessionId:$d,uri:P(),version:N(),contentChanges:qd(Zd(Cie),()=>[]),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Em=I({sessionId:$d,uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Dm=I({sessionId:$d,uri:P(),_meta:K(j(P(),A()).nullish(),()=>void 0)}),Om=I({sessionId:$d,uri:P(),version:N(),position:Ep,visibleRange:Dp,_meta:K(j(P(),A()).nullish(),()=>void 0)}),km=I({sessionId:$d,id:Tp,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Am=I({sessionId:$d,id:Tp,reason:K(ds([M(`rejected`),M(`ignored`),M(`replaced`),M(`cancelled`)]).nullish(),()=>void 0),_meta:K(j(P(),A()).nullish(),()=>void 0)});I({method:P(),params:ds([Cm,wm,Tm,Em,Dm,Om,km,Am,$p,em]).nullish()}),I({requestId:Qd,_meta:K(j(P(),A()).nullish(),()=>void 0)}),Lf.and(I({mode:M(`form`)})).and(I({message:P()})),zf.and(I({mode:M(`url`)})).and(I({message:P()})),ds([Of,kf]).and(I({message:P()})),jf.and(I({type:M(`string`)})),Mf.and(I({type:M(`number`)})),Nf.and(I({type:M(`integer`)})),Pf.and(I({type:M(`boolean`)})),If.and(I({type:M(`array`)})),Ff.and(I({type:M(`string`)})),Sm.and(I({action:M(`accept`)})),I({action:M(`decline`)}),I({action:M(`cancel`)});const jm=`$/cancel_request`;function Mm(e){return typeof e==`object`&&!!e}function wie(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Tie(e){if(!(!Mm(e)||!wie(e.requestId)))return e.requestId}const Nm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Pm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Eie(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Die(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 Fm(e){if(e instanceof Rm)return e.toResult();if(Die(e))return Rm.invalidParams(e.format()).toResult();let t=Eie(e);try{return Rm.internalError(t?JSON.parse(t):{}).toResult()}catch{return Rm.internalError({details:t}).toResult()}}function Oie(e){return e instanceof Rm&&e.code===-32800?e:Rm.requestCancelled(e)}function kie(e,t){let n=Aie(e,t);return n?n.toResult():Fm(e)}function Aie(e,t){if(!(!t.aborted||!jie(e)))return Oie(t.reason)}function jie(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Mie=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 Rm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Pm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Im=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Nie=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}},Lm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Nie(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 Pie}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 Im(()=>{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 Pm(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(jm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Pm(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 Nm.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(!Mm(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(Rm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(kie(n,t.responder.signal));else{let t=Fm(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 Mie(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&&Mm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Rm(n,r,i))}else t.reject(Rm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==jm)return;let t=Tie(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Rm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Pm(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)}},Pie=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)??Nm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Nm.no(r):await n(t(r.params),r.responder,i)??Nm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Nm.no(r):await n(t(r.params),i)??Nm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Lm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Rm=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}}},Fie=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 Iie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Fie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Mm(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)+`
@@ -1190,7 +1190,7 @@ tags: [lore, history]
1190
1190
  `);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=>{jX.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(),ot.release(Hr))}),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()),ot.release(Hr))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),ot.release(Hr))})}let vi=`local-op-auth-signout`,yi=X(_,async(e,t,n)=>{let r=n.host??Xr();if(!ot.tryAcquire(Ur)){J(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:vi,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=we,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=eu(e,i,uw({...Ar,env:{...process.env}})),a=!1,o=setTimeout(()=>{if(!a){a=!0;try{r.kill(`SIGKILL`)}catch{}n(Error(`auth signout subprocess timed out after ${Kr}ms`))}},Kr);o.unref?.(),r.on(`close`,()=>{a||(a=!0,clearTimeout(o),t())}),r.on(`error`,e=>{a||(a=!0,clearTimeout(o),n(e))})}),Y(t,200,Zi,{},{handler:vi})}catch(e){J(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:vi,cause:e})}finally{ot.release(Ur)}},{handler:vi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vi})}),bi=`/api/local-op/auth/set-identity`,xi=`local-op-auth-set-identity`,Ci=X(Ft,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!k){J(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:xi});return}if(!ot.tryAcquire(bi)){J(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:xi,extraHeaders:{"Retry-After":`5`}});return}try{Dge(k,r,i),be?.()?.refreshIdentity().catch(()=>{}),Y(t,200,Zi,{},{handler:xi})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:xi,cause:e})}finally{ot.release(bi)}},{handler:xi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:xi})}),wi=X(yee,async(e,t,n)=>{if(n.out!==void 0&&!Tq(n.out)){J(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{Y(t,200,h,await QP({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});function Ti(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return J(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=V(l),o=i===``?a:V(a,i);if(o!==a&&!o.startsWith(`${a}${H}`))return J(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r}),null;try{let e=V(o,`.ok`);Yk(e,a),Yk(V(e,`templates`),a)}catch(e){return Zk(e)?(J(t,400,`urn:ok:error:path-escape`,`Path escapes content directory.`,{handler:r,cause:e}),null):(J(t,500,`urn:ok:error:internal-server-error`,`Failed to validate path.`,{handler:r,cause:e}),null)}return{folderRel:i,resolvedContentDir:a}}function Ei(e,t,n){let r=s.documents.get(e);return r&&cS(r)?(dS(n,new uS({file:`${e}.md`}),t),!0):!1}let Di=e=>{let{body:t}=Ko(e);return{frontmatter:ie(e)??{},body:t}};function Oi(e){return!!e&&e.length<=64&&Br.test(e)}function ki(e,t,n){return Oi(e)?!0:(J(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1)}function Ai(e,t,n){let r=io.safeParse(e??`project`);return r.success?r.data:(J(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let ji=je??Nu(),Mi=pxe({contentDir:l,skillsHome:ji,effectiveInstallMode:qi});function Pi(e){return V(e===`global`?ji:l,`.ok`,`skills`)}function Fi(e,t,n){let r=V(Pi(e),t);if(e===`global`){if(n!==void 0){let e=NF(ji).find(e=>e.name===t&&e.hosts.includes(n));return e?V(ji,e.dir):null}let e=PF(ji,t);return e===null?U(z(r,`SKILL.md`))?r:null:e}let i=MF(l).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?V(l,i.dir):n===void 0&&U(z(r,`SKILL.md`))?r:null}function Ii(e,t){let n=e.searchParams;return JI({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 Li(e,t){let n=e===`project`?k:ji;if(!n)return`symlink`;try{return Va(z(n,...WE)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function Ri(e){let t=e===`project`?k:ji;return t?z(t,...WE):null}function Bi(e,t,n,r={}){let i=Ri(e);return i?zK(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 Vi(e,t,n){let r=Ri(e),i=Ri(t);if(!r||!i)return!1;let a=LK(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await zK(i,e=>({...e,skills:{...e.skills,[n]:o}})),await zK(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function Hi(e,t,n){let r=Ri(e);return r?zK(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function Gi(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];J(e,r,i,t.error,{handler:n,detail:t.code})}function qi(e,t,n){let r=e===`project`?k:ji;return(r?Qve(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Ji(e){let t=Fi(`project`,e);return t?B(l,t).split(H).join(`/`):`${zr}/${e}`}let Yi=LD.project;function Xi(e,t,n){let r=[],i=null,a=[...zi.map(e=>({id:e,root:oi[e]??``})),{id:`agents`,root:g}];for(let{id:o,root:s}of a){if(!s)continue;let a=V(e,...s.split(`/`),t);U(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 Qi(e){let t=Vde(e.source,e.pluginProvider);return{source:e.source,...e.publisher===void 0?{}:{publisher:e.publisher},...e.skill===void 0?{}:{skill:e.skill},...t?{marketplaceUrl:t}:{},importedAt:e.importedAt,...e.autoUpdate===void 0?{}:{autoUpdate:e.autoUpdate}}}function $i(e,t){if(!zD(t))return null;let n=Xi(e,t);if(!n)return null;let r=eD(n.dir)?.contentHash??``,i;try{i=ku(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:Ki,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}let ea=null;function ta(e){let t=Date.now();if(ea&&ea.identity===e&&t-ea.at<3e4)return ea.byName;let n=new Map;try{n=Re(Yn(je===void 0?{}:{home:je}).skills,e=>eD(e)?.contentHash)}catch(e){jX.warn({err:e},`plugin upstream index failed; origins will be omitted`)}return ea={at:t,identity:e,byName:n},n}function na(e,t){return ta(t).get(e)?.contentHash??null}function ra(e,t,n){let r=ta(t).get(e);if(!r)return null;try{if(G(n)!==G(r.home))return null}catch{return null}return{name:r.plugin,marketplace:r.marketplace,provider:r.provider,...r.repositoryUrl?{url:r.repositoryUrl}:{}}}function ia(e,t,n){let r=ta(t).get(e);if(!r)return null;if(n!==void 0)try{if(G(n)===G(r.home))return null}catch{}let i;try{i=ku(z(r.home,`SKILL.md`)).mtime.toISOString()}catch(e){jX.warn({err:e,home:r.home},`plugin bundle unreadable; origin dated epoch`),i=new Date(0).toISOString()}return{source:r.home,skill:e,contentHash:r.contentHash,autoUpdate:!1,importedAt:i}}function aa(e,t){let n=BD.find(t=>LD[t]===e);if(n===void 0||t!==void 0&&VD[n]!==(t===`global`?`user`:`project`))return null;try{let e=V(GD(n,{checkDesktop:!0}),`SKILL.md`);return U(e)?e:null}catch(t){return jX.warn({name:e,err:t},`[skills] bundle asset dir unresolved for built-in ${e}`),null}}function oa(e,t,n){let r=Xi(e,t),i=r?.skillMd??aa(t);if(i===null)return null;let a;try{let{frontmatter:e}=Di(W(i,`utf-8`));typeof e.description==`string`&&(a=e.description)}catch{}let o=$i(e,t),s=eD(R(i));return{name:t,...a===void 0?{}:{description:a},scope:n,path:r?.relPath??i,absolutePath:i,installed:(r?.hosts.length??0)>0,hosts:r?.hosts??[],managed:!0,...s?{size:fe(s)}:{},...o?{origin:Qi(o)}:{}}}function sa(e,t,n){return zD(e)?(J(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 ca(e,t){return B(t===`global`?ji:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function la(e){return e===`global`?ji:k}async function ua(e,t,n,r={}){let i=await kA(e,t),a=n===`project`?l:ji;if(r.purge!==void 0){_F(t,e,zi,iF(n));for(let e of yhe(a,n,t,r.purge.contentHash))ac(e,{recursive:!0,force:!0});return i!==null}if(!U(V(Pi(n),t,`SKILL.md`))){let r=(n===`project`?MF(l):NF(ji)).find(e=>e.name===t);if(r){let a=n===`project`?l:ji,o=V(a,r.dir),s=V(a,`.agents`,`skills`),c=z(s,t);if(U(s)&&!U(z(c,`SKILL.md`))){let e=!1;try{e=G(o)===G(c)}catch{e=!1}e||ic(o,c,{recursive:!0,dereference:!0})}return gF({canonicalAbs:U(z(c,`SKILL.md`))?c:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...zi],roots:iF(n)}),i!==null}}return _F(t,e,zi,iF(n)),i!==null}function da(e,t){let n=[];if(!U(e))return{skills:n,truncated:!1};let r;try{r=wu(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()||!Br.test(a.name))continue;if(n.length>=500){i=!0;break}let r=V(e,a.name,`SKILL.md`);if(!U(r))continue;let o;try{let{frontmatter:e}=Di(W(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:ca(r,t),absolutePath:r})}return{skills:n,truncated:i}}function fa(e){return`!/${R(e).split(H).join(`/`)}/`}let pa=X(cee,JL(async(e,t,n)=>{if(!ki(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){J(t,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=MF(l).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=FX(V(l,r,`SKILL.md`),l)??`${r}/SKILL.md`,a=R(i),o=i,s=fa(a),c=`.gitignore`,u=V(l,c);if(ze&&!ze.isPathIgnored(o)){Y(t,200,Sa,{line:s,gitignorePath:c,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){Y(t,200,Sa,{line:s,gitignorePath:c,applied:!1},{handler:`skill-track-in-git`});return}let d=U(u)?W(u,`utf-8`):null;if((d??``).split(`
1191
1191
  `).some(e=>e.trim()===s)){J(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${c}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(ju(u,`${d===null||d.endsWith(`
1192
1192
  `)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),Jn(),await ze?.rebuildIgnorePatterns(),ze?.isPathIgnored(o)){d===null?Du(u,{force:!0}):ju(u,d,`utf-8`),Jn(),await ze.rebuildIgnorePatterns(),J(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${c} was left unchanged.`,{handler:`skill-track-in-git`});return}at?.(`files`),Y(t,200,Sa,{line:s,gitignorePath:c,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),ma={lastKey:null},ha=X(wa,JL(async(e,t)=>{let n=(ze?.peekFreshInPlaceSkillDirsFingerprint()??``)+``+(k?ZP(k).join(`,`):``)+``+XP(ji).map(e=>e.editorId).join(`,`)+``+NF(ji).map(e=>e.dir).sort().join(`,`);if(Wn!==null&&Wn.fp!==n&&Jn(),Wn!==null&&Wn.gen===Un&&Wn.fp===n&&Date.now()-Wn.at<5e3){Y(t,200,Qr,Wn.body,{handler:`skills-list`});return}let r=Pi(`project`),i=da(r,`project`),a=da(Pi(`global`),`global`),o=k?ZP(k):[],s=XP(ji).map(e=>e.editorId),c=k?DF(k,`project`,g,ji):!1,u=DF(ji,`global`,g,ji),d=k?EA(k).skills:{},f=EA(ji).skills,p=k?KE(U(z(k,...WE))?W(z(k,...WE),`utf-8`):``)??null:null,m=Qi,h=(e,t,n)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=n?p?.skills[e.name]:void 0,o=a?m(a):void 0,s=a?.localHash!==void 0&&Ha(r,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),_=k?jJ(k):{},v=(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=vu(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(G(t)===G(n))continue}catch{}r.push(i.path)}}return{drift:r}},y=k?CF(l,`project`):{},b=OF(y,`project`),x=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),S=Ad(k??l),C=Nye(l),w=EF(`project`),T=EF(`global`),E=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),D=new Set,ee=ofe(l),te=e=>{let t=cfe(ee,e);return t?{name:t.name,marketplace:t.marketplace,provider:`claude`,...t.url?{url:t.url}:{}}:null},O=k?MF(l).map(e=>{let t=!D.has(e.name);D.add(e.name);let n=V(l,e.dir),r=t?ra(e.name,S,n)??te(n):null,i=t&&r===null?p?.skills[e.name]??$i(l,e.name)??ia(e.name,S,n):void 0,a=i?m(i):void 0,s=i?.localHash===void 0?(()=>{if(!i||!t)return!1;let n=na(e.name,S);return n!==null&&C.isModified(`project`,e.name,e.contentHash,n)})():e.contentHash!==i.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:V(l,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:o,hubOffered:c,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(y).length>0?{hostAliases:y}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...r===null?{}:{plugin:r},...(()=>{let n=E(t?_[e.name]:void 0,b).filter(e=>!x(e.path,w));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=v(k,E(t?_[e.name]:void 0,b),V(l,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...qi(`project`,e.name,e)===`link`?{linkMode:!0}:{},...a?{origin:a}:{},...s?{modified:!0}:{},...i?.baselineRef===void 0?{}:{revertable:!0},...zD(e.name)?{managed:!0}:{}}}):[],ne=jJ(ji),re=Va(z(ji,...WE)),ie=CF(ji,`global`),ae=OF(ie,`global`),oe=new Set(NF(ji).map(e=>e.name));a.skills=a.skills.filter(e=>!oe.has(e.name));let se=new Set,ce=NF(ji).map(e=>{let t=!se.has(e.name);se.add(e.name);let n=t?ne[e.name]:void 0,r=PF(ji,e.name),i=r!==null&&V(ji,e.dir)!==V(r)?e.hosts[0]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:V(ji,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],...i===void 0?{}:{hostQualifier:i},size:e.size,installableEditors:s,hubOffered:u,...e.pack===void 0?{}:{pack:e.pack},...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(ie).length>0?{hostAliases:ie}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=v(ji,E(n,ae),V(ji,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=E(n,ae).filter(e=>!x(e.path,T));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...qi(`global`,e.name,e)===`link`?{linkMode:!0}:{},...zD(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=V(ji,e.dir),r=ra(e.name,S,n);if(r!==null)return{plugin:r};let i=re.skills[e.name]??$i(ji,e.name)??ia(e.name,S,n);if(!i)return{};let a=i.localHash===void 0?(()=>{let t=na(e.name,S);return t!==null&&C.isModified(`global`,e.name,e.contentHash,t)})():e.contentHash!==i.localHash;return{origin:m(i),...a?{modified:!0}:{}}})()}}),le=new Set(O.map(e=>e.name)),ue=k&&!i.skills.some(e=>e.name===Yi)&&!le.has(Yi)?oa(k,Yi,`project`):null,de=new Set(ce.map(e=>e.name)),fe=HD.map(e=>LD[e]).filter(e=>!a.skills.some(t=>t.name===e)&&!de.has(e)).map(e=>oa(ji,e,`global`)).filter(e=>e!==null),pe=new Set(O.map(e=>e.name)),me=[...h(i,d,!0).filter(e=>!pe.has(e.name)),...O,...h(a,f,!1),...ce,...ue?[ue]:[],...fe];C.flush();let he={skills:me.map(e=>{let t=e.scope===`project`&&e.absolutePath?FX(e.absolutePath,l):null,n=e.absolutePath?_he(R(e.absolutePath)):[],r=n.length>0?{...e,filePaths:n}:e,i=t===null||t===e.path?r:{...r,canonicalPath:t},a=t??e.path;return e.scope===`project`&&ze?.isPathIgnored(a)===!0?{...i,ignored:!0}:i}),truncated:i.truncated||a.truncated},ge=await wxe(O.map(e=>e.path),ze??null,ma)?{...he,skills:he.skills.map(e=>{if(e.scope!==`project`)return e;let t=e.canonicalPath??e.path,n=ze?.isPathIgnored(t)===!0;if(n===(e.ignored===!0))return e;if(n)return{...e,ignored:!0};let{ignored:r,...i}=e;return i})}:he;Wn={at:Date.now(),gen:Un,fp:n,body:ge},Y(t,200,Qr,ge,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),ga=X(wa,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ki(r,t,`skill-get`))return;let i=Ai(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(zD(r)){let e=i===`global`?ji:k,a=e?Xi(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=Di(await Bu(a.skillMd,`utf-8`));Y(t,200,Ze,{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:yF(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=Fi(i,r,a);if(o===null){J(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}=Di(await Bu(s,`utf-8`));Y(t,200,Ze,{skill:{name:r,scope:i,path:ca(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:yF(o)}},{handler:`skill-get`})}catch(e){J(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 _a(e,t){!pe||Yx(e)||(ze&&(Jn(),ze.refreshInPlaceSkillDirs(),Zn()),Xt(e,t,`skill-put`))}let va=X(Eee,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!ki(n.name,t,`skill-put`)||sa(n.name,t,`skill-put`))return;let r=gO({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){J(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`?l:ji,a=Fi(n.scope,n.name);if(a===null){let a=kF(i,n.scope);if(a===null){J(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let o=_O({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){J(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`&&(Hn(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),er(`skill-put`)),await _a(n.scope===`project`?`${a}/${n.name}/SKILL`:It(`global`,n.name),r.content),at?.(`files`),Y(t,200,it,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=B(i,a).split(H).join(`/`),s=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:It(n.scope,n.name);if(Ei(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=Pn(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{xb(h.dc.document,r.content,`agent`)},h.origin);let g=await Bt(u);if(g?.kind===`failure`){Vt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Ut(t,`skill-put`);return}n.scope===`project`&&(Hn(e,Vn(`skill`,``,n.name),`skill-edit: ${s}`),er(`skill-put`)),await _a(u,r.content),at?.(`files`),Y(t,200,it,{path:s,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function ya(e,t,n){let r=e===`project`?l:ji,i=Fi(e,t,n);return{root:i===null?Pi(e):R(i),dirRel:i===null?`.ok/skills/${t}`:B(r,i).split(H).join(`/`),realDir:i}}function ba(e,t){let n=e===`project`?l:ji,r=(e===`project`?MF(l):NF(ji)).find(e=>e.name===t);r&&gF({canonicalAbs:V(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>Ht(e)),roots:iF(e)})}let xa=X(wa,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ki(r,t,`skill-delete`))return;let i=Ai(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=n.searchParams.get(`host`)??void 0,{root:o,dirRel:s,realDir:c}=ya(i,r,a);if(a!==void 0&&c===null){J(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-delete`,detail:`No skill "${r}" (${i}) in ${a}.`});return}let l=Ii(n,De);if(l.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await mn(i===`project`?[...new Set([`${s}/SKILL`,It(i,r)])]:[It(i,r,a)],`deleted-upstream`),a===void 0&&ba(i,r);let u=SO({skillsRoot:o,name:r}),d=Pi(i);if(a===void 0&&u.ok&&d!==o&&U(V(d,r,`SKILL.md`))){let e=SO({skillsRoot:d,name:r});e.ok||jX.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!u.ok){let e=u.error.code===`UNLINK_FAILED`?500:400;J(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:u.error.code,cause:Error(u.error.message)});return}u.existed&&(i===`project`&&(Hn(l,s,`skill-delete: ${s}`),Jn(),tr(`skill-delete`)),at?.(`files`));let f=la(i);a===void 0&&f&&await ua(f,r,i),Y(t,200,Mee,{existed:u.existed,path:u.path},{handler:`skill-delete`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Ca=X(Ln,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!ki(n.fromName,t,`skill-move`)||!ki(n.toName,t,`skill-move`)||sa(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=ya(n.scope,n.fromName);if(Fi(n.scope,n.toName)!==null){J(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=la(n.scope),o=a?EA(a).skills[n.fromName]:void 0,s=n.scope===`project`?l:ji,c=(n.scope===`project`?MF(l):NF(ji)).find(e=>e.name===n.fromName),u=c?R(c.dir):null,d=u===null?[]:Object.entries(CF(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?eF(o.hosts):[],...c?eF(c.hosts):[],...eF(d)])];await mn(n.scope===`project`?[...new Set([`${i}/SKILL`,It(n.scope,n.fromName)])]:[It(n.scope,n.fromName)],`renamed`),ba(n.scope,n.fromName);let p=await Wfe({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await rZ(k,e,t);return n||nZ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){J(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){J(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;J(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=Di(W(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=_O({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=Ehe({base:n.scope===`project`?l:ji,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`)}n.scope===`project`&&!m&&(Jn(),ze?.refreshInPlaceSkillDirs(),Ia(r,n.fromName,n.toName).then(()=>La(x,n.toName)).catch(()=>{}),Zn());let S=ca(V(r,n.fromName),n.scope),C=ca(V(r,n.toName),n.scope),w=Ha(r,n.toName);if(await Bi(n.scope,n.fromName,n.toName,{localHash:w}),n.scope===`project`&&(Hn(e,Vn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),(async()=>{try{await tr(`skill-move`);let t=await Ua(Wa(e),C);t!==void 0&&await Hi(`project`,n.toName,{baselineRef:t})}catch(e){L(`skill-move`).warn({err:e,toName:n.toName},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()),a){await kA(a,n.fromName),_F(n.fromName,a,f,iF(n.scope));let e=V(r,n.toName);if(f.length>0){let t=lF(e,n.toName,a,f,Li(n.scope,n.toName),iF(n.scope));await OA(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??nF(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(at?.(`files`),m){let e=m.code===`WRITE_ERROR`;J(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,ft,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),Ta=X(ge,async(e,t,n)=>{let{name:r,home:i}=n;if(!ki(r,t,`skill-edit-external`))return;let a;try{a=G(i)}catch{J(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!ku(a).isDirectory()||!U(V(a,`SKILL.md`))){J(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}lge(r,a),Y(t,200,Kt,{docName:nee(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),Ea=X($n,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(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(!ki(r,t,`skill-move-scope`))return;if(zD(r)){J(t,400,`urn:ok:error:invalid-request`,`"${r}" is a built-in skill and always lives at its own scope.`,{handler:`skill-move-scope`,detail:`BUILTIN_SCOPE_FIXED`});return}if(i===a){J(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!k){J(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=ya(i,r),u=V(o,r),d=(()=>{try{return G(u)}catch{return u}})(),f=a===`project`?l:ji,p=kF(f,a);if(p===null){J(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available in the destination scope.`,{handler:`skill-move-scope`,detail:`NO_USABLE_SKILL_HOME`});return}let m=V(f,p),h=V(m,r);if(c===null||!U(u)){J(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(c)===V(h)||U(h)&&G(c)===G(h)){J(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(Fi(a,r)!==null||U(h)){J(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let g=la(i),_=la(a),v=g?EA(g).skills[r]:void 0,y=i===`project`?l:ji,b=(i===`project`?MF(l):NF(ji)).find(e=>e.name===r),x=b?R(b.dir):null,S=x===null?[]:Object.entries(CF(y,i)).filter(([,e])=>e===x).map(([e])=>e),C=[...new Set([...v?eF(v.hosts):[],...b?eF(b.hosts):[],...eF(S)])];await mn([...new Set([...i===`project`?[`${s}/SKILL`]:[],It(i,r),It(a,r)])],`renamed`),tc(m,{recursive:!0}),ic(d,h,{recursive:!0,dereference:!0}),ba(i,r);let w=SO({skillsRoot:o,name:r});if(w.ok&&d!==u){let e=B((()=>{try{return G(y)}catch{return y}})(),d);e!==``&&!e.startsWith(`..`)&&!ou(e)&&ac(d,{recursive:!0,force:!0})}if(!w.ok){SO({skillsRoot:m,name:r}),J(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:w.error.code,cause:Error(w.error.message)});return}let T=await Vi(i,a,r);if(g&&await ua(g,r,i,b?{purge:{contentHash:b.contentHash}}:{}),g&&await $ve(g,r),_&&C.length>0){let e=lF(h,r,_,C,Li(a,n.name),iF(a));await OA(_,r,{...v,scope:a,hosts:e,scripts:v?.scripts??nF(h,r).hasScripts,installedAt:v?.installedAt??new Date().toISOString()})}if(T&&await Hi(a,r,{localHash:Ha(m,r)}),i===`project`||a===`project`){Hn(e,i===`project`?s:B(l,h).split(H).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`);let t=B(l,h).split(H).join(`/`),n=!!T&&a===`project`;(async()=>{try{if(await tr(`skill-move-scope`),n){let n=await Ua(Wa(e),t);n!==void 0&&await Hi(a,r,{baselineRef:n})}}catch(e){L(`skill-move-scope`).warn({err:e,name:r},`deferred shadow flush / revert-baseline failed — Revert stays unarmed until the next flush`)}})()}if(!U(z(h,`SKILL.md`))){J(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,h).split(H).join(`/`)});return}Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),at?.(`files`),Y(t,200,Le,{scope:a,path:B(f,h).split(H).join(`/`)},{handler:`skill-move-scope`})}catch(e){J(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`}),Da=X(ree,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!ki(n.name,t,`skill-duplicate`)||!ki(n.toName,t,`skill-duplicate`)||sa(n.toName,t,`skill-duplicate`))return;let r=Fi(n.scope,n.name);if(r===null||!U(z(r,`SKILL.md`))){J(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?l:ji,a=kF(i,n.scope);if(a===null){J(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let o=V(i,a),s=V(o,n.toName);if(Fi(n.scope,n.toName)!==null||U(s)){J(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let c=eD(r);if(!c){J(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}tc(o,{recursive:!0}),ic(r,s,{recursive:!0,dereference:!0});let{fenced:u,body:d}=Ui(c.skillMd),f=p(u,{name:n.toName});if(!f.ok){SO({skillsRoot:o,name:n.toName}),J(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:f.error.kind});return}try{cc(z(s,`SKILL.md`),`${f.nextFenced}${d}`)}catch(e){throw SO({skillsRoot:o,name:n.toName}),e}if(n.scope===`project`){let t=B(l,s).split(H).join(`/`);Hn(e,Vn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),tr(`skill-duplicate`)}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Ce,{name:n.toName},{handler:`skill-duplicate`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),Oa=sR({GET:ga,PUT:va,POST:Ca,DELETE:xa},{handler:`skill`});function ka(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 Aa(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Ma(e,t){let n=V(e,t),r=B(l,e).split(H).join(`/`),i;try{i=wu(n,{recursive:!0,encoding:`utf-8`})}catch{return[]}return i.filter(e=>/\.md$/i.test(e)).map(e=>`${r}/${t}/${e.split(H).join(`/`).replace(/\.md$/i,``)}`)}function Pa(e,t){let n=t.replace(/\.md$/i,``);return`${_ee(e).replace(/\/SKILL$/,``)}/${n}`}function Fa(e,t){let n=V(e,t,`references`);if(!U(n))return[];let r=[],i=(e,t)=>{for(let n of wu(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 Ia(e,t,n){if(!pe){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=W(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(l,e).split(H).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 Fa(e,n))i(o(t,r),o(n,r),V(e,n,r));await pe.recordDirectMutations(r)}async function La(e,t){if(!pe||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 pe.recordDirectMutations(n)}let Ra=sR({GET:X(wa,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!ki(r,t,`skill-file-get`))return;let i=Ai(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=zD(r)?i===`global`?ji:k:void 0,s=n.searchParams.get(`host`)??void 0,c=o?Xi(o,r,s):null;if(a===``||a.includes(`\0`)){J(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:ka(a))??`reference`,u=s,d=o?c?.dir??null:Fi(i,r,u);if(d===null&&u!==void 0){J(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(Pi(i),r),p=V(f,a);if(p!==f&&!p.startsWith(`${f}${H}`)){J(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(!U(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?Na.map(t=>`${e[1]}${t}`).find(e=>e!==a&&U(V(f,e))):void 0;if(n===void 0){J(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)){J(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,y,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){J(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:X(vee,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!ki(n.name,t,`skill-file-put`)||sa(n.name,t,`skill-file-put`))return;let r=ka(n.path);if(r===null){J(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){J(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Fi(n.scope,n.name);if(i===null||!U(z(i,`SKILL.md`))){J(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`?l:ji,i).split(H).join(`/`),o=n.path.replace(/\\/g,`/`),s=Aa(n.scope,r,o),u;if(s){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(Ei(e,`skill-file-put`,t))return;if(u=!U(V(i,o)),u&&yO(i)>=50){J(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}=Pn(n),f=await c.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{xb(f.dc.document,n.content,`agent`)},f.origin);let p=await Bt(e);if(p?.kind===`failure`){Vt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Ut(t,`skill-file-put`);return}}else{let e=bO({skillsRoot:R(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;J(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`&&(Hn(e,Vn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),tr(`skill-file-put`)),at?.(`files`),Y(t,200,Ot,{path:o,created:u,kind:r,content:s},{handler:`skill-file-put`})}catch(e){J(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:X(wa,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!ki(i,t,`skill-file-delete`)||sa(i,t,`skill-file-delete`))return;let a=Ai(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=ka(o);if(s===null){J(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 c=Ii(n,De);if(c.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=Fi(a,i),d=u===null?Pi(a):R(u),f=V(u??z(d,i),o);if(U(f)&&Aa(a,s,o)){let e=o.replace(/\.md$/i,``);await mn([u===null?Pa(i,o):`${B(l,u).split(H).join(`/`)}/${e}`],`deleted-upstream`)}else if(a===`project`&&u!==null&&U(f)&&ku(f).isDirectory()){let e=Ma(u,o);e.length>0&&await mn(e,`deleted-upstream`)}let p=xO({skillsRoot:d,name:i,relPath:o});if(!p.ok){let e=p.error.code===`UNLINK_FAILED`?500:400;J(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:p.error.code,cause:Error(p.error.message)});return}p.existed&&a===`project`&&(Hn(c,Vn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${B(l,u).split(H).join(`/`)}/${o}`}`),tr(`skill-file-delete`)),p.existed&&at?.(`files`),Y(t,200,bee,{path:o,existed:p.existed,kind:s},{handler:`skill-file-delete`})}catch(e){J(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`}),za=X(Lt,async(e,t,n)=>{try{if(!ki(n.name,t,`skill-file-rename`)||sa(n.name,t,`skill-file-rename`))return;let e=JI(n,De);if(e.kind===`invalid-summary`){J(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=ka(r),o=ka(i);if(a===null||o===null){J(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let s=Fi(n.scope,n.name);if(s===null){J(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=R(s),u=Aa(n.scope,a,r),d=Aa(n.scope,o,i),f=B(l,s).split(H).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Ei(p,`skill-file-rename`,t))return;if(p!==null)await mn([p],`deleted-upstream`);else if(n.scope===`project`){let e=V(s,r);if(U(e)&&ku(e).isDirectory()){let e=Ma(s,r);e.length>0&&await mn(e,`deleted-upstream`)}}let h=Ufe({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;J(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(pe){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:W(V(c,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:W(V(c,n.name,i),`utf-8`)})}catch{}await Yt(e,`skill-file-rename`)}n.scope===`project`&&(Hn(e,Vn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),tr(`skill-file-rename`)),at?.(`files`),Y(t,200,tn,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){jX.error({err:e},`[skill-file-rename] failed`),t.headersSent||J(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function Ba(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let Va=LK;function Ha(e,t){return eD(V(e,t))?.contentHash}async function Ua(e,t){let n=ae?.current;if(!(!n||!e))try{let r=ix(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1193
- `).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 tr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Wa=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ga(e){try{let t=la(e.scope);if(!t)return;let n=rF(t);if(n.length===0)return;let r=lF(V(e.skillsRoot,e.name),e.name,t,n,`copy`,iF(e.scope));if(r.length===0)return;await OA(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){jX.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Ka(e,t){if(t.ok){Y(e,200,hn,t.body,{handler:`skill-import`});return}J(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 qa=fxe({contentDir:l,skillsHome:ji,...k===void 0?{}:{projectDir:k},resolveSkillDirForRead:Fi,parseFrontmatterDoc:Di,attributeOkArtifactWrite:Hn,commitOkArtifactWrite:tr,shadowHeadSha:Ua,artifactWriterId:Wa,effectiveInstallMode:qi,signalFiles:()=>at?.(`files`)}),Ja=_xe({contentDir:l,skillsHome:ji,...k===void 0?{}:{projectDir:k},legacyStoreRoot:zr,effectiveSkillRoot:ya,parseFrontmatterDoc:Di,attributeOkArtifactWrite:Hn,commitOkArtifactWrite:tr,shadowHeadSha:Ua,artifactWriterId:Wa,skillArtifactKey:e=>Vn(`skill`,``,e),captureAndCloseDocuments:mn,projectImportedSkillCopy:Ga,signalFiles:()=>at?.(`files`)});function Ya(e,t){if(t.ok){Y(e,200,or,t.body,{handler:`skill-reimport`});return}J(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function Xa(e,t,n){let r=e===`project`?l:ji,i=(e===`project`?MF(l):NF(ji)).find(e=>e.name===t);return i?V(r,i.dir):V(n,t)}function Za(e,t,n,r){let i=r.skills[t];if(i)return i;let a=Xa(e,t,n);return lde(t,eD(a)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:bxe(a)})??$i(e===`global`?ji:l,t)??ia(t,Ad(k??l),a)}let Qa=X(bt,async(e,t,n)=>{let r=()=>{};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(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 aD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??VE(d);if(!p){J(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(Dq(t,p,`skill-import`))return;let m=await UE(p);r=m.cleanup,s=m.ref;let h=tD(m.dir);if(h.length===0){J(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=>QE(e.dir)?.name===f)??h.find(e=>e.name===Pt[f]);if(!e){J(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){J(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??Ba(d)}catch(e){if(e instanceof NE){J(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){J(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await qa.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Oe(u))&&qP({source:u,skills:[d.body.name]},EP()),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),at?.(`files`),Ka(t,d)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),$a=X(See,async(e,t,n)=>{let r=()=>{};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(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 aD(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??VE(d);if(!f){J(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(Dq(t,f,`skills-import-bulk`))return;if(l=e?.publisher??Ba(d),f.kind===`well-known`)a=f,o=await zE(f.origin);else{let e=await UE(f);r=e.cleanup,c=e.ref,s=tD(e.dir)}}catch(e){if(e instanceof NE){J(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){J(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 UE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof NE?`not-found`:`failed`,warnings:[],...e instanceof NE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>eD(e.dir)?.name===t)??s.find(e=>e.name===Pt[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await qa.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||Oe(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&qP({source:u,skills:e},EP())}Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),at?.(`files`),Y(t,200,mo,{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){J(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`}),eo=8*1024*1024,to=32*1024*1024;function no(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+H)?null:r}function ro(e){return new Promise((t,n)=>{let r;try{r=HR(e,{files:200,fields:10,fieldSize:2*1024,fileSize:eo})}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>to){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 ao(e,t){return new Promise((n,r)=>{(0,hfe.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=no(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){tc(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>eo){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>to){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{tc(R(n),{recursive:!0}),cc(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 oo(e,t){let n=bu(z(Iu(),`ok-skill-upload-`)),r=()=>{try{ac(n,{recursive:!0,force:!0})}catch{}};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){J(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=Ai(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=JI({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},De);if(o.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ro(e)}catch(e){J(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){J(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 ao(c.data,n)}catch(e){J(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=no(n,e.relPath);if(!r){J(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}tc(R(r),{recursive:!0}),cc(r,e.data)}let u=tD(n);if(u.length===0){J(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){J(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];Ka(t,await qa.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let so=X(Wee,async(e,t,n)=>{try{let e=Pi(n.scope);if(!ki(n.name,t,`skill-install`))return;if(n.scope===`project`&&!k){J(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=la(n.scope),i=V(e,n.name),a=n.scope===`project`?l:ji,o=(n.scope===`project`?MF(l):NF(ji)).find(e=>e.name===n.name),s=zD(n.name)?aa(n.name,n.scope):null,c=o?V(a,o.dir):U(i)||s===null?i:R(s);if(!U(c)){J(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 Bt(n.scope===`project`?`${B(a,c).split(H).join(`/`)}/SKILL`:It(n.scope,n.name));let u=nF(c,n.name,{allowReservedName:zD(n.name)});if(!u.ok){J(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${u.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){J(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Mi.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:J(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:J(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:J(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`:J(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:J(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)}`)}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o.hosts.filter(Ht),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let d=n.setSource??n.source,f=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),p=n.targets,m=[],h=[];if(n.add!==void 0||n.remove!==void 0){if(!o){J(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 Mi.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`?J(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`}):J(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}p=e.targets.filter(Ht),m.push(...e.rootAdds),h.push(...e.rootRemoves)}if(d&&!o){let e=await Mi.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:d});if(!e.ok){J(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}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?k:ji;if(!e){J(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 _r.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?J(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):J(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||at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?k:ji;if(!e){J(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 _r.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:J(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:J(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:J(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`:J(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)}`)}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){J(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`?k:ji,s=await _r.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`:J(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:J(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`:J(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`:J(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)}`)}at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:[...o.hosts],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let g=n.scope===`global`?p===void 0?XP(ji).map(e=>e.editorId):uee.filter(e=>p?.some(t=>t===e)):p===void 0?rF(r):zi.filter(e=>p?.some(t=>t===e)),_=[],v=[];if(g.length===0&&p===void 0&&(_.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),v.push(`no-targets`)),u.hasScripts&&(_.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),v.push(`scripts-present`)),u.warnings.length>0&&(_.push(u.warnings[0]),v.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(p===void 0?n.scope===`global`&&U(z(ji,`.agents`)):p.includes(`agents`))?[...g,`agents`]:[...g],a=n.scope===`project`?k:ji,s=f===void 0?qi(n.scope,n.name,o):f?`link`:`copy`;if(d){let e=await Mi.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:d});if(!e.ok){e.kind===`invalid-target`?J(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}):J(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}at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let l=await Mi.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:p!==void 0,installMode:s,...f===void 0?{}:{linkModeReq:f},rootAdds:m,rootRemoves:h});if(!l.ok){J(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:l.reason});return}_.push(...l.warnings),v.push(...l.warningCodes),at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:l.hosts,scripts:u.hasScripts,warnings:_,warningCodes:v,...l.sourceMovedTo===void 0?{}:{sourceMovedTo:l.sourceMovedTo}},{handler:`skill-install`});return}let y=eF(EA(r).skills[n.name]?.hosts??[]).filter(e=>!g.includes(e));y.length>0&&_F(n.name,r,y,iF(n.scope));let b=z(r,...WE),x=U(b)?W(b,`utf-8`):null,S=x===null?null:KE(x);x!==null&&S===null&&jX.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let C=S?.skills[n.name]!==void 0,w=f===void 0?C?`copy`:`symlink`:f?`symlink`:`copy`,T=lF(c,n.name,r,g,w,iF(n.scope));T.length===0?await kA(r,n.name):await OA(r,n.name,{hosts:T,scope:n.scope,scripts:u.hasScripts,installedAt:new Date().toISOString(),projection:w}),at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:T,scripts:u.hasScripts,warnings:_,warningCodes:v},{handler:`skill-install`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),co=X(kee,async(e,t,n)=>{try{if(!ki(n.name,t,`skill-uninstall`))return;let e=la(n.scope);if(!e){J(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 ua(e,n.name,n.scope);at?.(`files`),Y(t,200,lee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),lo=X(oee,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ki(n.name,t,`skill-restore`)||sa(n.name,t,`skill-restore`))return;if(n.scope===`global`){J(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=ae?.current;if(!r){J(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 gX({shadow:r,contentDir:l,contentRoot:de??`.`,name:n.name,version:n.version,skillDirRel:Ji(n.name)});if(!i.ok){Gi(t,i,`skill-restore`);return}let a=[],o=nF(V(l,Ji(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),Hn(e,Vn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await tr(`skill-restore`),at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,cn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),fo=X(iee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!ki(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?ji:l,{root:a,dirRel:o,realDir:s}=ya(n.scope,n.name);if(s===null||!U(V(i,o,`SKILL.md`))){J(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let c=z(n.scope===`global`?ji:k,...WE),u=Za(n.scope,n.name,a,Va(c));if(!u){J(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 zK(c,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,or,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null;try{let e=u.skill??n.name,i=Pt[e],a=await aD(u.source,e).catch(async e=>{if(i===void 0)throw e;return aD(u.source,i)}),o=a?.source??DD(u.source,u.pluginProvider),s=a?.skill??u.skill,c=a?.spec??VE(o);if(!c){J(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:u.source});return}if(Dq(t,c,`skill-reimport`))return;let l=await UE(c);r=l.cleanup,d=l.ref;let p=tD(l.dir),m=pX(p,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>eD(e)?.name});if(!m){J(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:p.map(e=>e.name).join(`, `)});return}f=m.dir}catch(e){if(e instanceof NE){J(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){J(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let p=await Ja.runSkillReimport({acquiredDir:f,name:n.name,scope:n.scope,entry:u,lockPath:c,ref:d,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Ya(t,p)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),po=X(di,async(e,t,n)=>{try{if(n.scope===`project`&&!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let r=JI(n,De);if(r.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let i=z(n.scope===`global`?ji:k,...WE),a=Va(i),o=[],{bySource:s,unrecorded:c}=gxe([...new Set(n.names)].filter(e=>Oi(e)?!0:(o.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`}),!1)),e=>Za(n.scope,e,ya(n.scope,e).root,a));for(let e of c)o.push({requested:e,status:`not-found`,warnings:[]});for(let t of s){let s=()=>{};try{let c,l=[];try{let e=t.names[0],n=await aD(t.source,e).catch(async n=>{let r=Pt[e];if(r===void 0)throw n;return aD(t.source,r)}),r=n?.source??DD(t.source,a.skills[t.names[0]]?.pluginProvider),i=n?.spec??VE(r);if(!i||Eq(i)){for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:`INVALID_SOURCE`});continue}let u=await UE(i);s=u.cleanup,c=u.ref,l=tD(u.dir)}catch(n){L(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:tS(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)});continue}for(let s of t.names){let t=Za(n.scope,s,ya(n.scope,s).root,a);if(!t){o.push({requested:s,status:`not-found`,warnings:[]});continue}let u=pX(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:s,frontmatterNameOf:e=>eD(e)?.name});if(!u){o.push({requested:s,status:`not-found`,source:t.source,warnings:[]});continue}try{let a=await Ja.runSkillReimport({acquiredDir:u.dir,name:s,scope:n.scope,entry:t,lockPath:i,ref:c,actor:r});if(!a.ok){L(`skills-reimport-bulk`).warn({skill:s,err:a.cause,detail:a.detail,requestId:tS(e)},`bulk update: one skill failed (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:a.detail??a.title});continue}o.push({requested:s,status:a.body.updated?`updated`:`up-to-date`,source:a.body.source,warnings:a.body.warnings})}catch(n){L(`skills-reimport-bulk`).warn({skill:s,err:n,requestId:tS(e)},`bulk update: one skill threw (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)})}}}finally{s()}}Y(t,200,ja,{results:o,updated:o.filter(e=>e.status===`updated`).length,upToDate:o.filter(e=>e.status===`up-to-date`).length,failed:o.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{Jn(),ze?.refreshInPlaceSkillDirs(),Jn(),await ze?.rebuildIgnorePatterns()}catch(e){L(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),ho=X(u,async(e,t,n)=>{try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!ki(n.name,t,`skill-revert`)||sa(n.name,t,`skill-revert`))return;if(n.scope===`global`){J(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(k,...WE),i=Va(r).skills[n.name];if(!i?.baselineRef){J(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=ae?.current;if(!a){J(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 gX({shadow:a,contentDir:l,contentRoot:de??`.`,name:n.name,version:i.baselineRef,skillDirRel:Ji(n.name)});if(!o.ok){Gi(t,o,`skill-revert`);return}Hn(e,Vn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await tr(`skill-revert`);let s=V(l,Ji(n.name),`..`),c=Ha(s,n.name);await zK(r,e=>qE(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Pi(`project`)&&await Ga({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),at?.(`files`),Y(t,200,pee,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`}),go=uxe({contentDir:l,projectDir:k,getAllFilesIndex:x,getFileIndexGeneration:w,getSearchMaxEntries:Exe,semanticSearch:Ke,getSemanticSimilarityFloor:qe,ready:He,getProjectSkillsRoot:()=>Pi(`project`),parseFrontmatterDoc:Di});go.prewarm();let _o=`local-op-embeddings-set-key`,vo=`local-op-embeddings-clear-key`,yo=`/api/local-op/embeddings`;function bo(){let e=Ye?.();return{projectDir:k??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let xo=X(Xe,async(e,t,n)=>{if(!ot.tryAcquire(yo)){J(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:_o,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=bo();await new Ek(Je).setForProject(e,r,n.key),Ke?.reloadCredential(),Y(t,200,ke,{keyPresent:!0},{handler:_o,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:_o,cause:e})}finally{ot.release(yo)}},{handler:_o,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:_o})}),So=X(wa,async(e,t)=>{if(!ot.tryAcquire(yo)){J(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:vo,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=bo();await new Ek(Je).clearForProject(e,n),Ke?.reloadCredential(),Y(t,200,ke,{keyPresent:!1},{handler:vo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:vo,cause:e})}finally{ot.release(yo)}},{handler:vo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vo})}),Co=`local-op-embeddings-test`,wo=`/api/local-op/embeddings/test`,To=X(wa,async(e,t)=>{if(!ot.tryAcquire(wo)){J(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Co,extraHeaders:{"Retry-After":`5`}});return}try{let e=Ye?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await hk(new Ek(Je),k??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await _k({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,vt,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Co,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Co,cause:e})}finally{ot.release(wo)}},{handler:Co,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Co})}),Eo=0;function Do(){Eo+=1,at?.(`lint-config`)}let Oo=()=>`${Eo} ${t.getActiveBranch()} ${pe?.readLocalTargetGeneration?.()??0}`;async function ko(e,t){let n=Qe?.()??Yr;try{let r=await Dn(e,fN(l,n,{docName:t,projectDir:k??l,onProblem:e=>jX.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=$e?.()??`warning`;if(pe&&a!==`off`&&!Yx(t)){await Zt(t,e,`lint-validation`);let r=HN({projectDir:k??l,contentDir:l,baseConfig:n,derivedDocumentIndex:pe,linksValidation:a,admittedDocNames:Jt,docFilePathFor:e=>YX(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:YX(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return jX.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ao(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=hN({projectDir:k??l,contentDir:l});return FM(t.schemas,n)}let jo={"/api/asset":Sr,"/api/asset-text":wr,"/api/skill":Oa,"/api/skill-file":Ra,"/api/skill-file/rename":za,"/api/skills":ha,"/api/skill/import":Qa,"/api/skills/import-bulk":$a,"/api/skill/edit-external":Ta,"/api/skill/duplicate":Da,"/api/skill/move-scope":Ea,"/api/skill-upload":oo,"/api/skill/install":so,"/api/skill/uninstall":co,"/api/skill/restore":lo,"/api/skill/reimport":fo,"/api/skills/reimport-bulk":po,"/api/skill/revert":ho,"/api/skill/track-in-git":pa,"/api/lint/markdownlint-config":X(Tee,async(e,t,n)=>{let r;try{r=TN(V(l),n.ruleId,n.value)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){J(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}Do();try{let e=Qe?.()??Yr,n=[],r=lN(l,void 0,e=>n.push(e)),i=dN(k??l,uN(e,r),e=>n.push(e));n.push(...Ao(i)),Y(t,200,Nn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){J(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`}),"/api/lint/frontmatter-schema":X(C,async(e,t,n)=>{let r;try{let e=V(k??l),t=n.parentPath??[];r=n.delete?Upe(e,n.file):n.field!==void 0&&n.removeField?Vpe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Hpe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?zpe(e,n.file,n.field,n.constraint,t):Bpe(e,n.file)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){J(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`)&&at?.(`files`),Do();try{let e=Qe?.()??Yr,n=[],r=lN(l,void 0,e=>n.push(e)),i=dN(k??l,uN(e,r),e=>n.push(e));n.push(...Ao(i)),Y(t,200,Nn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){J(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`}),"/api/lint/fix":X(Pe,async(t,n,r)=>{try{let t=UX(r.docName,n,`lint-fix`);if(t===null)return;let i=jt(t),a=JI(r,De);if(a.kind===`invalid-summary`){J(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Hx(i)||Ux(i)){J(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=YX(l,i);if(f===null){J(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}Yk(V(l,f),l);let p=Qe?.()??Yr,{stored:m}=In(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),_=[],{cfg:v,before:y,fixed:b,ran:x,failures:S}=await Ipe({projectDir:k??l,contentDir:l,baseConfig:p,docRelPath:f,source:g,onConfigProblem:e=>_.push(e)}),C=y,w,T=[];if(b!==g){try{let t=ee(d),n=Ho[t]??No(u??o);ve?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{XC(h.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,JC(h))},h.origin),a.kind!==`anonymous`&&AO(i,o,s,u,void 0,a.kind===`agent`?Fn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ve?.touchMode(o,`idle`)}let t=await Bt(i);if(t?.kind===`failure`){Vt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Ut(n,`lint-fix`);return}zt(i,`lint-fix`);try{C=await Dn(h.dc.document.getText(`source`).toString(),v,f,e=>T.push(e))}catch(e){w=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,jX.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),C=y}}let E=C.filter(e=>e.severity===`error`).length,D=C.length-E,te=Math.max(0,y.length-C.length),O=[..._,...Wi([...S,...T]),...w?[w]:[]];Y(n,200,st,{file:f,fixedCount:te,diagnostics:C,errorCount:E,warningCount:D,ran:x,...O.length>0?{warnings:O}:{},...w?{warning:w}:{}},{handler:`lint-fix`})}catch(e){if(Zk(e)){J(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof uS){dS(n,e,`lint-fix`);return}if(e instanceof _S){bS(n,e,`lint-fix`);return}if(e instanceof ow){J(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}jX.error({err:e},`[lint-fix] handler failed`),J(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),"/api/agent-write":nr,"/api/agent-write-md":rr,"/api/agent-write-batch":ar,"/api/frontmatter-patch":sr,"/api/agent-patch":cr,"/api/agent-undo":lr,"/api/agent-activity":ur,"/api/agent-burst-diff":dr,"/api/save-version":vr,"/api/rollback":yr,"/api/local-op/clone":Mr,"/api/local-op/ok-init":Lr,"/api/local-op/auth/login":ni,"/api/local-op/auth/status":ui,"/api/local-op/auth/pat":mi,"/api/local-op/auth/gh-login":ai,"/api/local-op/auth/cancel":ci,"/api/local-op/auth/repos":gi,"/api/local-op/auth/signout":yi,"/api/local-op/auth/set-identity":Ci,"/api/local-op/embeddings/set-key":xo,"/api/local-op/embeddings/clear-key":So,"/api/local-op/embeddings/test":To,"/api/install-skill":wi};re&&(jo[`/api/test-reset`]=pr,jo[`/api/test-flush-git`]=fr,jo[`/api/test-rescan-backlinks`]=mr,jo[`/api/test-rescan-files`]=hr);let Mo=new Set(`/api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./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/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skills/reimport-bulk./api/skill/revert./api/skill/track-in-git`.split(`.`)),Po=[`/api/local-op/`],Fo=qL({log:jX,policy:n,ephemeral:et,table:{resolve(e){let t=jo[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>Mo.has(e)||Po.some(t=>e.startsWith(t))}}),Io=[cK({hocuspocus:s,derivedDocumentIndex:pe,getFileIndex:v,isSafeDocName:aZ,readPageTitleForDocName:St,readPageTitleForLinkedDocName:wt,readFrontmatterMetadataForLinkedDocName:kt,collectAdmittedDocNames:Jt,resolveAlias:jt,respondToDerivedIndexQueryFailure:en}),pK({hocuspocus:s,agentPresenceBroadcaster:ve,isAllowedWorkspaceHostHeader:i,log:jX}),ct,Yge({contentDir:l,projectDir:k,ephemeral:et,log:jX,ready:He,durabilityState:t,serverInstanceId:m,getDiskAckSVs:le,getCollabClientCount:ue,getConfigDiagnostics:rt,acpRegistry:Ne,loadAcpCustomAgents:Fe,acpHarnessAvailability:Ie,isRoutePeerAdmitted:o,isAllowedWorkspaceHostHeader:i,checkLocalOpSecurity:r,getPrincipal:De,semanticSearch:Ke,readSemanticProviderConfig:Ye,embeddingsSecretsFile:Je,getFileIndex:v,shadowRef:ae,getCurrentBranch:ce,installedAgentsCache:_t}),lK({hocuspocus:s,contentDir:l,projectDir:k,contentFilter:ze,isSafeDocName:aZ,resolveDocFilePath:YX,isValidRelativeContentPath:HX,streamShowAllEntries:VX,getLinterBaseConfig:Qe,getLinksValidationSetting:$e,derivedDocumentIndex:pe,collectAdmittedDocNames:Jt,unmatchedGlobProblems:Ao,readAuditGeneration:Oo}),eU({contentRoot:de,log:jX,shadowRef:ae,flushGitCommit:oe,commitOkArtifactWrite:tr,getCurrentBranch:ce,validateFolderRel:Ti,safeDocPath:MX,docTreePathCandidates:NX}),w_e({contentDir:l,projectDir:k,homeDirOverride:je,skillsHome:ji,isSafeDocName:aZ,commentService:xt,enumerateInstalledSkillsCached:Yn,checkLocalOpSecurity:r}),z_e({log:jX,skillsHome:ji,projectDir:k,contentDir:l,resolveSkillDirForRead:Fi}),tye({contentDir:l,projectDir:k,skillsHome:ji,homeDirOverride:je,savedThemeLockTimeoutMs:Me,ephemeral:et,log:jX,signalChannel:at,searchService:go,linkPreviewFetch:tt,getLinkPreviewsEnabled:nt,getGeneratedIndexSettingsStatus:d,setGeneratedIndexEnabled:f}),Gge({commentService:xt,getPrincipal:De,signalChannel:at}),H_e({projectDir:k,contentDir:l,getPrincipal:De,hocuspocus:s,log:jX,checkLocalOpSecurity:r,getSyncEngine:be,serializeDoc:We}),C_e({projectDir:k,contentDir:l,log:jX,checkLocalOpSecurity:r,localOpCliArgs:we,localOpGuard:ot,getSyncEngine:be,toGitRelativePath:ZX}),xV({projectDir:k,contentDir:l,contentFilter:ze,getFileIndex:v,checkLocalOpSecurity:r,getSyncEngine:be,getPrincipal:De,localOpCliArgs:we}),az({contentDir:l,projectDir:k,log:jX,getPrincipal:De,contentFilter:ze,signalChannel:at,hocuspocus:s,getSyncEngine:be,flushContributors:se,fileOpsService:Tr,assetService:br,extractAgentIdentity:Pn,recordDerivedDocumentBestEffort:Xt,invalidateReferencedAssetsCache:lt,listManagedDocNamesUnderFolderFromDisk:On,resolveContentEntryPath:WX,docNameForFileOperationPath:XX,withPeriod:fn,toManagedRenamePublicError:pn,attributeRenameWriteToActor:Bn,renameAttributionCounter:wX,_performAssetRename:An,_performDocumentToFileRename:jn,_performManagedRenameForDocs:Mn,isValidRelativeContentPath:HX}),g_e({contentDir:l,checkLocalOpSecurity:r}),J_e({contentDir:l,log:jX,checkLocalOpSecurity:r,installedAgentsCache:_t}),nV({contentDir:l,projectDir:k,ephemeral:et,log:jX,hocuspocus:s,sessionManager:c,getPrincipal:De,signalChannel:at,getSyncEngine:be,recentlyRemovedDocs:Ue,isSafeDocName:aZ,resolveAlias:jt,resolveContentEntryPath:WX,validateFolderRel:Ti,extractAgentIdentity:Pn,extractActorIdentityFromQuery:Ii,okArtifactKey:Vn,attributeOkArtifactWrite:Hn,scheduleOkArtifactFlush:er,flushDiskAndDetectOutcome:Bt,respondPersistenceFailure:Vt,respondDiskDivergence:Ut,registerWrittenDocInFileIndex:sn,captureAndCloseDocuments:mn,renameTrackedPathInGit:rZ,renamePathOnDisk:nZ,splitContentPath:GX,mutateFileIndex:S})],Lo=Io.flatMap(e=>[...e.paths]);FG(Lo,jo);let Ro=Io.map(e=>qL({log:jX,policy:n,ephemeral:et,table:e.table})),zo={paths:Lo,dispatch:async(e,t)=>{for(let n of Ro)if(await n(e,t))return!0;return!1}},Vo=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`]),Uo=Io.map(e=>e.table),Wo=e=>{for(let t of Uo){let n=t.resolve(e)?.dispatch;if(n!==void 0)return n}};for(let e of Vo)if(jo[e]===void 0&&Wo(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Fo(e,t)},nativeApi:zo,localApi:fK({resolve:e=>{if(!Vo.has(e))return;let t=jo[e];return t===void 0?Wo(e):t}})}}function sZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=au(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!zL(f,o)){J(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!BL(e.headers.host,o)){J(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:FL});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=nX(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=Ts.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function cZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Bxe(e){let t;try{t=wu(e.contentDir,{withFileTypes:!0})}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&kx(n.name,bs)&&e.basenameIndex.add(n.name)}async function lZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Vu(i,{withFileTypes:!0})}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=Uk(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await zu(a)}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Hu(a)}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Wk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Uu(i)}catch(t){let n=cZ(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()&&kx(a,gs)&&!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()&&kx(a,gs)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const uZ=I({principalId:P().optional(),tabSessionId:P().optional(),expectedServerInstanceId:P().optional(),expectedBranch:P().optional(),expectedDocLineageEpoch:P().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:P().optional(),clientKind:P().optional()}).loose(),dZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function fZ(e){return dZ.includes(e)}function pZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Vxe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!fZ(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 mZ=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=pZ(e,this.payload)}};function hZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=uZ.safeParse(t);return n.success?n.data:void 0}var gZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function _Z(e,t,n=``){e=une(`.`,e);let r=cne(e),i=0,a,o;for(;i<r.length;i++)a=Xu(e,r[i]),o=lne(a),o.isDirectory()?_Z(a,t,Xu(n,r[i])):t(Xu(n,r[i]),a,o)}function Hxe(e){let t=e.url;if(t==null)return;let n=e._parsedUrl;if(n&&n.raw===t)return n;let r=t,i=``,a,o;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(o=t.substring(e),r=t.substring(0,e)),e=r.indexOf(`?`,1),e!==-1&&(i=r.substring(e),r=r.substring(0,e),i.length>1&&(a=Sne.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const Uxe=()=>{};function Wxe(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function vZ(e,t){let n=0,r,i=e.length-1;e.charCodeAt(i)===47&&(e=e.substring(0,i));let a=[],o=`${e}/index`;for(;n<t.length;n++)r=t[n]?`.${t[n]}`:``,e&&a.push(e+r),a.push(o+r);return a}function Gxe(e,t,n){let r=0,i,a=vZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function Kxe(e,t,n,r){let i=0,a=vZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=su(z(e,c=a[i])),o.startsWith(e)&&fu.existsSync(o)){if(s=fu.statSync(o),s.isDirectory())continue;return l=yZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function qxe(e,t){return t.statusCode=404,t.end()}function Jxe(e,t,n,r,i){let a=200,o,s={};i={...i};for(let e in i)o=t.getHeader(e),o&&(i[e]=o);if((o=t.getHeader(`content-type`))&&(i[`Content-Type`]=o),e.headers.range){a=206;let[n,o]=e.headers.range.replace(`bytes=`,``).split(`-`),c=s.end=parseInt(o,10)||r.size-1,l=s.start=parseInt(n,10)||0;if(c>=r.size&&(c=r.size-1),l>=r.size)return t.setHeader(`Content-Range`,`bytes */${r.size}`),t.statusCode=416,t.end();i[`Content-Range`]=`bytes ${l}-${c}/${r.size}`,i[`Content-Length`]=c-l+1,i[`Accept-Ranges`]=`bytes`}t.writeHead(a,i),fu.createReadStream(n,s).pipe(t)}const Yxe={".br":`br`,".gz":`gzip`};function yZ(e,t,n){let r=Yxe[e.slice(-3)],i=Qbe(e.slice(0,r&&-3))||``;i===`text/html`&&(i+=`;charset=utf-8`);let a={"Content-Length":t.size,"Content-Type":i,"Last-Modified":t.mtime.toUTCString()};return r&&(a[`Content-Encoding`]=r),n&&(a.ETag=`W/"${t.size}-${t.mtime.getTime()}"`),a}function bZ(e,t={}){e=V(e||`.`);let n=t.onNoMatch||qxe,r=t.setHeaders||Uxe,i=t.extensions||[`html`,`htm`],a=t.gzip&&i.map(e=>`${e}.gz`).concat(`gz`),o=t.brotli&&i.map(e=>`${e}.br`).concat(`br`),s={},c=`/`,l=!!t.etag,u=!!t.single;if(typeof t.single==`string`){let e=t.single.lastIndexOf(`.`);c+=~e?t.single.substring(0,e):t.single}let d=[];t.ignores!==!1&&(d.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),t.dotfiles?d.push(/\/\.\w/):d.push(/\/\.well-known/),[].concat(t.ignores||[]).forEach(e=>{d.push(new RegExp(e,`i`))}));let f=t.maxAge!=null&&`public,max-age=${t.maxAge}`;f&&t.immutable?f+=`,immutable`:f&&t.maxAge===0&&(f+=`,must-revalidate`),t.dev||_Z(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=yZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?Kxe.bind(0,e+H,l):Gxe.bind(0,s);return function(e,t,s){let f=[``],m=Hxe(e).pathname,h=e.headers[`accept-encoding`]||``;if(a&&h.includes(`gzip`)&&f.unshift(...a),o&&/(br|brotli)/i.test(h)&&f.unshift(...o),f.push(...i),m.indexOf(`%`)!==-1)try{m=decodeURI(m)}catch{}let g=p(m,f)||u&&!Wxe(m,d)&&p(c,f);if(!g)return s?s():n(e,t);if(l&&e.headers[`if-none-match`]===g.headers.ETag)return t.writeHead(304),t.end();(a||o)&&t.setHeader(`Vary`,`Accept-Encoding`),r(t,m,g.stats),Jxe(e,t,g.abs,g.stats,g.headers)}}const xZ=L(`conflict-storage`);var SZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(lO(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!U(this.storePath)){this.conflicts=[];return}try{let e=W(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){xZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){xZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);U(e)||yu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return ju(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return xZ.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()||xZ.error({branch:this.branch},`[conflicts] cleared conflicts in memory but conflicts.json persist failed — the ledger will resurrect them on restart`)}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n){let r=this.conflicts.find(t=>t.file===e);if(!r)throw new pS({file:e});if(t===`content`&&n!==void 0&&age(n))throw new fS({file:e});if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-CgzfmB2x.mjs`),a=i(this.projectDir,{credentialConfig:[]});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!Wk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Pq(r,t,{allowShareableOkArtifact:dM}),cc(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}let o=new Map(this.list().map(e=>[e.file,e.detectedAt]));if(this.removeConflict(e)||xZ.error({file:e},`[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart`),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),xZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Ab(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:o.get(t)??n});r=e.length>0}catch(e){xZ.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:o.get(e)??n}),xZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n){let r=V(this.projectDir),i=V(r,e.file);if(!Wk(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);Pq(i,r,{allowShareableOkArtifact:dM});let a={...e};this.removeConflict(e.file)||xZ.error({file:e.file},`[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart`);try{await this.applyWorkingTreeStrategy(i,r,e,t,n)}catch(t){throw this.addConflict(a)||xZ.error({file:e.file,err:t},`[conflicts] resolve rolled back in memory but conflicts.json persist failed — the ledger will lose this conflict on restart`),t}}async applyWorkingTreeStrategy(e,t,n,r,i){switch(r){case`mine`:break;case`theirs`:{if(!n.theirsSha)throw Error(`[conflicts] working-tree conflict for ${n.file} has no pinned theirs blob`);let{createGitInstance:r}=await import(`./git-handle-CgzfmB2x.mjs`),i=await r(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,n.theirsSha]);Pq(e,t,{allowShareableOkArtifact:dM}),cc(e,i,`utf-8`);break}case`content`:if(i===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);cc(e,i,`utf-8`);break;case`delete`:U(e)&&Qs(e);break;default:throw Error(`[conflicts] unknown resolve strategy: ${r}`)}}};function Xxe(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 Zxe(e,t){let n=lO(e);try{yu(n,{recursive:!0}),ju(z(n,mte),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Dte(e);yu(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`};ju(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const CZ=new Map;let wZ=!1;function Qxe(e,t){try{let n=Xxe(e,t);for(let e of CZ.keys())Zxe(e,n)}catch{}}function $xe(e){CZ.set(e,(CZ.get(e)??0)+1),wZ||(wZ=!0,process.on(`uncaughtExceptionMonitor`,Qxe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=CZ.get(e)??0;n<=1?CZ.delete(e):CZ.set(e,n-1)}}}function TZ(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function EZ(e){let t=e.scheduler??Xa,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??TZ(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function DZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function OZ(e){if(!U(e))return{};let t;try{t=(0,pO.parse)(W(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(!DZ(t))return{};let n=t.telemetry;if(!DZ(n))return{};let r=n.localSink;return DZ(r)?r:{}}function kZ(e){return typeof e==`boolean`?e:void 0}function eSe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function AZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function jZ(e){if(DZ(e))return eSe(e.maxBytes)}function tSe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=OZ(Rs(`project`,e.projectDir)),n=OZ(Rs(`project-local`,e.projectDir));if((kZ(n.enabled)??kZ(t.enabled)??!0)===!1)return null;let r=jZ(n.spans)??jZ(t.spans)??52428800,i=jZ(n.logs)??jZ(t.logs)??26214400,a=AZ(n.attributeDenylist)??AZ(t.attributeDenylist)??Jee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var MZ;(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})(MZ||={});var nSe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(nSe||={});const NZ=MZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),PZ=e=>{switch(typeof e){case`undefined`:return NZ.undefined;case`string`:return NZ.string;case`number`:return Number.isNaN(e)?NZ.nan:NZ.number;case`boolean`:return NZ.boolean;case`function`:return NZ.function;case`bigint`:return NZ.bigint;case`symbol`:return NZ.symbol;case`object`:return Array.isArray(e)?NZ.array:e===null?NZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?NZ.promise:typeof Map<`u`&&e instanceof Map?NZ.map:typeof Set<`u`&&e instanceof Set?NZ.set:typeof Date<`u`&&e instanceof Date?NZ.date:NZ.object;default:return NZ.unknown}},Q=MZ.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 FZ=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,MZ.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()}};FZ.create=e=>new FZ(e);const IZ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===NZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,MZ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${MZ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${MZ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${MZ.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}"`:MZ.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,MZ.assertNever(e)}return{message:n}};let rSe=IZ;function LZ(){return rSe}const RZ=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 zZ(e,t){let n=LZ(),r=RZ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===IZ?void 0:IZ].filter(e=>!!e)});e.common.issues.push(r)}var BZ=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 VZ;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 VZ;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 VZ=Object.freeze({status:`aborted`}),HZ=e=>({status:`dirty`,value:e}),UZ=e=>({status:`valid`,value:e}),WZ=e=>e.status===`aborted`,GZ=e=>e.status===`dirty`,KZ=e=>e.status===`valid`,qZ=e=>typeof Promise<`u`&&e instanceof Promise;var JZ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(JZ||={});var YZ=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 XZ=(e,t)=>{if(KZ(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 FZ(e.common.issues);return this._error=t,this._error}}};function ZZ(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 QZ=class{get description(){return this._def.description}_getType(e){return PZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:PZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new BZ,ctx:{common:e.parent.common,data:e.data,parsedType:PZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qZ(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:PZ(e)};return XZ(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:PZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return KZ(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=>KZ(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:PZ(e)},r=this._parse({data:e,path:n.path,parent:n});return XZ(n,await(qZ(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 AQ({schema:this,typeName:zQ.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 jQ.create(this,this._def)}nullable(){return MQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mQ.create(this)}promise(){return kQ.create(this,this._def)}or(e){return _Q.create([this,e],this._def)}and(e){return bQ.create(this,e,this._def)}transform(e){return new AQ({...ZZ(this._def),schema:this,typeName:zQ.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new NQ({...ZZ(this._def),innerType:this,defaultValue:t,typeName:zQ.ZodDefault})}brand(){return new IQ({typeName:zQ.ZodBranded,type:this,...ZZ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new PQ({...ZZ(this._def),innerType:this,catchValue:t,typeName:zQ.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return LQ.create(this,e)}readonly(){return RQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const iSe=/^c[^\s-]{8,}$/i,aSe=/^[0-9a-z]+$/,oSe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sSe=/^[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,cSe=/^[a-z0-9_-]{21}$/i,lSe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uSe=/^[-+]?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)?)??$/,dSe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let $Z;const fSe=/^(?:(?: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])$/,pSe=/^(?:(?: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])$/,mSe=/^(([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]))$/,hSe=/^(([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])$/,gSe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_Se=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eQ=`((\\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])))`,vSe=RegExp(`^${eQ}$`);function tQ(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 ySe(e){return RegExp(`^${tQ(e)}$`)}function bSe(e){let t=`${eQ}T${tQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xSe(e,t){return!!((t===`v4`||!t)&&fSe.test(e)||(t===`v6`||!t)&&mSe.test(e))}function SSe(e,t){if(!lSe.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 CSe(e,t){return!!((t===`v4`||!t)&&pSe.test(e)||(t===`v6`||!t)&&hSe.test(e))}var nQ=class e extends QZ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==NZ.string){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.string,received:t.parsedType}),VZ}let t=new BZ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),zZ(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),zZ(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?zZ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&zZ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)dSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)$Z||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),$Z.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)sSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)cSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)iSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)aSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)oSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(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),zZ(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),zZ(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),zZ(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),zZ(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),zZ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bSe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?vSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ySe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?uSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xSe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?SSe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?CSe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?gSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?_Se.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):MZ.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,...JZ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...JZ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...JZ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...JZ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...JZ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...JZ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...JZ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...JZ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...JZ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...JZ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...JZ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...JZ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...JZ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...JZ.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,...JZ.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,...JZ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...JZ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...JZ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...JZ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...JZ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...JZ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...JZ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...JZ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...JZ.errToObj(t)})}nonempty(e){return this.min(1,JZ.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}};nQ.create=e=>new nQ({checks:[],typeName:zQ.ZodString,coerce:e?.coerce??!1,...ZZ(e)});function wSe(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 rQ=class e extends QZ{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)!==NZ.number){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.number,received:t.parsedType}),VZ}let t,n=new BZ;for(let r of this._def.checks)r.kind===`int`?MZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),zZ(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),zZ(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),zZ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?wSe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),zZ(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),zZ(t,{code:Q.not_finite,message:r.message}),n.dirty()):MZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,JZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JZ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:JZ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:JZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:JZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:JZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:JZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JZ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:JZ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:JZ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:JZ.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`&&MZ.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)}};rQ.create=e=>new rQ({checks:[],typeName:zQ.ZodNumber,coerce:e?.coerce||!1,...ZZ(e)});var iQ=class e extends QZ{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)!==NZ.bigint)return this._getInvalidInput(e);let t,n=new BZ;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),zZ(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),zZ(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),zZ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):MZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.bigint,received:t.parsedType}),VZ}gte(e,t){return this.setLimit(`min`,e,!0,JZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JZ.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:JZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:JZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:JZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:JZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JZ.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}};iQ.create=e=>new iQ({checks:[],typeName:zQ.ZodBigInt,coerce:e?.coerce??!1,...ZZ(e)});var aQ=class extends QZ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==NZ.boolean){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.boolean,received:t.parsedType}),VZ}return UZ(e.data)}};aQ.create=e=>new aQ({typeName:zQ.ZodBoolean,coerce:e?.coerce||!1,...ZZ(e)});var oQ=class e extends QZ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==NZ.date){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.date,received:t.parsedType}),VZ}if(Number.isNaN(e.data.getTime()))return zZ(this._getOrReturnCtx(e),{code:Q.invalid_date}),VZ;let t=new BZ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),zZ(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),zZ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):MZ.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:JZ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:JZ.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)}};oQ.create=e=>new oQ({checks:[],coerce:e?.coerce||!1,typeName:zQ.ZodDate,...ZZ(e)});var sQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.symbol){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.symbol,received:t.parsedType}),VZ}return UZ(e.data)}};sQ.create=e=>new sQ({typeName:zQ.ZodSymbol,...ZZ(e)});var cQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.undefined){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.undefined,received:t.parsedType}),VZ}return UZ(e.data)}};cQ.create=e=>new cQ({typeName:zQ.ZodUndefined,...ZZ(e)});var lQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.null){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.null,received:t.parsedType}),VZ}return UZ(e.data)}};lQ.create=e=>new lQ({typeName:zQ.ZodNull,...ZZ(e)});var uQ=class extends QZ{constructor(){super(...arguments),this._any=!0}_parse(e){return UZ(e.data)}};uQ.create=e=>new uQ({typeName:zQ.ZodAny,...ZZ(e)});var dQ=class extends QZ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return UZ(e.data)}};dQ.create=e=>new dQ({typeName:zQ.ZodUnknown,...ZZ(e)});var fQ=class extends QZ{_parse(e){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.never,received:t.parsedType}),VZ}};fQ.create=e=>new fQ({typeName:zQ.ZodNever,...ZZ(e)});var pQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.undefined){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.void,received:t.parsedType}),VZ}return UZ(e.data)}};pQ.create=e=>new pQ({typeName:zQ.ZodVoid,...ZZ(e)});var mQ=class e extends QZ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==NZ.array)return zZ(t,{code:Q.invalid_type,expected:NZ.array,received:t.parsedType}),VZ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(zZ(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&&(zZ(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&&(zZ(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 YZ(t,e,t.path,n)))).then(e=>BZ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new YZ(t,e,t.path,n)));return BZ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:JZ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:JZ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:JZ.toString(n)}})}nonempty(e){return this.min(1,e)}};mQ.create=(e,t)=>new mQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:zQ.ZodArray,...ZZ(t)});function hQ(e){if(e instanceof gQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=jQ.create(hQ(r))}return new gQ({...e._def,shape:()=>t})}else if(e instanceof mQ)return new mQ({...e._def,type:hQ(e.element)});else if(e instanceof jQ)return jQ.create(hQ(e.unwrap()));else if(e instanceof MQ)return MQ.create(hQ(e.unwrap()));else if(e instanceof xQ)return xQ.create(e.items.map(e=>hQ(e)));else return e}var gQ=class e extends QZ{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=MZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==NZ.object){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.object,received:t.parsedType}),VZ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fQ&&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 YZ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof fQ){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&&(zZ(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 YZ(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=>BZ.mergeObjectSync(t,e)):BZ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return JZ.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:JZ.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:zQ.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 MZ.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 MZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return hQ(this)}partial(t){let n={};for(let e of MZ.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 MZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof jQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return EQ(MZ.objectKeys(this.shape))}};gQ.create=(e,t)=>new gQ({shape:()=>e,unknownKeys:`strip`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)}),gQ.strictCreate=(e,t)=>new gQ({shape:()=>e,unknownKeys:`strict`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)}),gQ.lazycreate=(e,t)=>new gQ({shape:e,unknownKeys:`strip`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)});var _Q=class extends QZ{_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 FZ(e.ctx.common.issues));return zZ(t,{code:Q.invalid_union,unionErrors:n}),VZ}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 FZ(e));return zZ(t,{code:Q.invalid_union,unionErrors:i}),VZ}}get options(){return this._def.options}};_Q.create=(e,t)=>new _Q({options:e,typeName:zQ.ZodUnion,...ZZ(t)});const vQ=e=>e instanceof wQ?vQ(e.schema):e instanceof AQ?vQ(e.innerType()):e instanceof TQ?[e.value]:e instanceof DQ?e.options:e instanceof OQ?MZ.objectValues(e.enum):e instanceof NQ?vQ(e._def.innerType):e instanceof cQ?[void 0]:e instanceof lQ?[null]:e instanceof jQ?[void 0,...vQ(e.unwrap())]:e instanceof MQ?[null,...vQ(e.unwrap())]:e instanceof IQ||e instanceof RQ?vQ(e.unwrap()):e instanceof PQ?vQ(e._def.innerType):[];var TSe=class e extends QZ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==NZ.object)return zZ(t,{code:Q.invalid_type,expected:NZ.object,received:t.parsedType}),VZ;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}):(zZ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),VZ)}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=vQ(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:zQ.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...ZZ(r)})}};function yQ(e,t){let n=PZ(e),r=PZ(t);if(e===t)return{valid:!0,data:e};if(n===NZ.object&&r===NZ.object){let n=MZ.objectKeys(t),r=MZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=yQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===NZ.array&&r===NZ.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=yQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===NZ.date&&r===NZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var bQ=class extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(WZ(e)||WZ(r))return VZ;let i=yQ(e.value,r.value);return i.valid?((GZ(e)||GZ(r))&&t.dirty(),{status:t.value,value:i.data}):(zZ(n,{code:Q.invalid_intersection_types}),VZ)};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}))}};bQ.create=(e,t,n)=>new bQ({left:e,right:t,typeName:zQ.ZodIntersection,...ZZ(n)});var xQ=class e extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==NZ.array)return zZ(n,{code:Q.invalid_type,expected:NZ.array,received:n.parsedType}),VZ;if(n.data.length<this._def.items.length)return zZ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),VZ;!this._def.rest&&n.data.length>this._def.items.length&&(zZ(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 YZ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>BZ.mergeArray(t,e)):BZ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};xQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new xQ({items:e,typeName:zQ.ZodTuple,rest:null,...ZZ(t)})};var ESe=class e extends QZ{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!==NZ.object)return zZ(n,{code:Q.invalid_type,expected:NZ.object,received:n.parsedType}),VZ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new YZ(n,e,n.path,e)),value:a._parse(new YZ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?BZ.mergeObjectAsync(t,r):BZ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof QZ?new e({keyType:t,valueType:n,typeName:zQ.ZodRecord,...ZZ(r)}):new e({keyType:nQ.create(),valueType:t,typeName:zQ.ZodRecord,...ZZ(n)})}},SQ=class extends QZ{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!==NZ.map)return zZ(n,{code:Q.invalid_type,expected:NZ.map,received:n.parsedType}),VZ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new YZ(n,e,n.path,[a,`key`])),value:i._parse(new YZ(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 VZ;(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 VZ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};SQ.create=(e,t,n)=>new SQ({valueType:t,keyType:e,typeName:zQ.ZodMap,...ZZ(n)});var CQ=class e extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==NZ.set)return zZ(n,{code:Q.invalid_type,expected:NZ.set,received:n.parsedType}),VZ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(zZ(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&&(zZ(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 VZ;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 YZ(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:JZ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:JZ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};CQ.create=(e,t)=>new CQ({valueType:e,minSize:null,maxSize:null,typeName:zQ.ZodSet,...ZZ(t)});var DSe=class e extends QZ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==NZ.function)return zZ(t,{code:Q.invalid_type,expected:NZ.function,received:t.parsedType}),VZ;function n(e,n){return RZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LZ(),IZ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return RZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LZ(),IZ].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 kQ){let e=this;return UZ(async function(...t){let o=new FZ([]),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 UZ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new FZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new FZ([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:xQ.create(t).rest(dQ.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||xQ.create([]).rest(dQ.create()),returns:n||dQ.create(),typeName:zQ.ZodFunction,...ZZ(r)})}},wQ=class extends QZ{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})}};wQ.create=(e,t)=>new wQ({getter:e,typeName:zQ.ZodLazy,...ZZ(t)});var TQ=class extends QZ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return zZ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),VZ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};TQ.create=(e,t)=>new TQ({value:e,typeName:zQ.ZodLiteral,...ZZ(t)});function EQ(e,t){return new DQ({values:e,typeName:zQ.ZodEnum,...ZZ(t)})}var DQ=class e extends QZ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return zZ(t,{expected:MZ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),VZ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return zZ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),VZ}return UZ(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})}};DQ.create=EQ;var OQ=class extends QZ{_parse(e){let t=MZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==NZ.string&&n.parsedType!==NZ.number){let e=MZ.objectValues(t);return zZ(n,{expected:MZ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),VZ}if(this._cache||=new Set(MZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=MZ.objectValues(t);return zZ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),VZ}return UZ(e.data)}get enum(){return this._def.values}};OQ.create=(e,t)=>new OQ({values:e,typeName:zQ.ZodNativeEnum,...ZZ(t)});var kQ=class extends QZ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==NZ.promise&&t.common.async===!1?(zZ(t,{code:Q.invalid_type,expected:NZ.promise,received:t.parsedType}),VZ):UZ((t.parsedType===NZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kQ.create=(e,t)=>new kQ({type:e,typeName:zQ.ZodPromise,...ZZ(t)});var AQ=class extends QZ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===zQ.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=>{zZ(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 VZ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?VZ:r.status===`dirty`||t.value===`dirty`?HZ(r.value):r});{if(t.value===`aborted`)return VZ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?VZ:r.status===`dirty`||t.value===`dirty`?HZ(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`?VZ:(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`?VZ:(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(!KZ(e))return VZ;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=>KZ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):VZ);MZ.assertNever(r)}};AQ.create=(e,t,n)=>new AQ({schema:e,typeName:zQ.ZodEffects,effect:t,...ZZ(n)}),AQ.createWithPreprocess=(e,t,n)=>new AQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:zQ.ZodEffects,...ZZ(n)});var jQ=class extends QZ{_parse(e){return this._getType(e)===NZ.undefined?UZ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jQ.create=(e,t)=>new jQ({innerType:e,typeName:zQ.ZodOptional,...ZZ(t)});var MQ=class extends QZ{_parse(e){return this._getType(e)===NZ.null?UZ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};MQ.create=(e,t)=>new MQ({innerType:e,typeName:zQ.ZodNullable,...ZZ(t)});var NQ=class extends QZ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===NZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};NQ.create=(e,t)=>new NQ({innerType:e,typeName:zQ.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...ZZ(t)});var PQ=class extends QZ{_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 qZ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new FZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new FZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};PQ.create=(e,t)=>new PQ({innerType:e,typeName:zQ.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...ZZ(t)});var FQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.nan){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.nan,received:t.parsedType}),VZ}return{status:`valid`,value:e.data}}};FQ.create=e=>new FQ({typeName:zQ.ZodNaN,...ZZ(e)});var IQ=class extends QZ{_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}},LQ=class e extends QZ{_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`?VZ:e.status===`dirty`?(t.dirty(),HZ(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`?VZ: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:zQ.ZodPipeline})}},RQ=class extends QZ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(KZ(e)&&(e.value=Object.freeze(e.value)),e);return qZ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};RQ.create=(e,t)=>new RQ({innerType:e,typeName:zQ.ZodReadonly,...ZZ(t)}),gQ.lazycreate;var zQ;(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`})(zQ||={}),nQ.create,rQ.create,FQ.create,iQ.create,aQ.create,oQ.create,sQ.create,cQ.create,lQ.create,uQ.create,dQ.create,fQ.create,pQ.create,mQ.create;const OSe=gQ.create;gQ.strictCreate,_Q.create,TSe.create,bQ.create,xQ.create,ESe.create,SQ.create,CQ.create,DSe.create,wQ.create,TQ.create,DQ.create,OQ.create,kQ.create,AQ.create,jQ.create,MQ.create,AQ.createWithPreprocess,LQ.create;const kSe=hs(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Gee.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ote(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ws(e,t,n),e.parseAsync=async(t,n)=>_te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Es(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)=>ite(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ASe=hs(`ZodMiniObject`,(e,t)=>{Zee.init(e,t),kSe.init(e,t),dte(e,`shape`,()=>t.shape)});function BQ(e,t){return new ASe({type:`object`,shape:e??{},...hte(t)})}function VQ(e){return!!e._zod}function HQ(e){let t=Object.values(e);if(t.length===0)return BQ({});let n=t.every(VQ),r=t.every(e=>!VQ(e));if(n)return BQ(e);if(r)return OSe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function UQ(e,t){return VQ(e)?ws(e,t):e.safeParse(t)}async function WQ(e,t){return VQ(e)?await Es(e,t):await e.safeParseAsync(t)}function GQ(e){if(!e)return;let t;if(t=VQ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function KQ(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 HQ(e)}}if(VQ(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 qQ(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 jSe(e){return e.description}function MSe(e){if(VQ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function JQ(e){if(VQ(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 YQ=`2025-11-25`,XQ=[YQ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],ZQ=`io.modelcontextprotocol/related-task`,QQ=lte(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),$Q=ds([P(),N().int()]),e$=P();rs({ttl:N().optional(),pollInterval:N().optional()});const NSe=I({ttl:N().optional()}),PSe=I({taskId:P()}),t$=rs({progressToken:$Q.optional(),[ZQ]:PSe.optional()}),n$=I({_meta:t$.optional()}),r$=n$.extend({task:NSe.optional()}),FSe=e=>r$.safeParse(e).success,i$=I({method:P(),params:n$.loose().optional()}),a$=I({_meta:t$.optional()}),o$=I({method:P(),params:a$.loose().optional()}),s$=rs({_meta:t$.optional()}),c$=ds([P(),N().int()]),l$=I({jsonrpc:M(`2.0`),id:c$,...i$.shape}).strict(),u$=e=>l$.safeParse(e).success,d$=I({jsonrpc:M(`2.0`),...o$.shape}).strict(),ISe=e=>d$.safeParse(e).success,f$=I({jsonrpc:M(`2.0`),id:c$,result:s$}).strict(),p$=e=>f$.safeParse(e).success;var m$;(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`})(m$||={});const h$=I({jsonrpc:M(`2.0`),id:c$.optional(),error:I({code:N().int(),message:P(),data:A().optional()})}).strict(),g$=e=>h$.safeParse(e).success,_$=ds([l$,d$,f$,h$]);ds([f$,h$]);const v$=s$.strict(),LSe=a$.extend({requestId:c$.optional(),reason:P().optional()}),y$=o$.extend({method:M(`notifications/cancelled`),params:LSe}),b$=I({icons:F(I({src:P(),mimeType:P().optional(),sizes:F(P()).optional(),theme:$o([`light`,`dark`]).optional()})).optional()}),x$=I({name:P(),title:P().optional()}),S$=x$.extend({...x$.shape,...b$.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),RSe=ls(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ss(I({form:ss(I({applyDefaults:Yo().optional()}),j(P(),A())).optional(),url:QQ.optional()}),j(P(),A()).optional())),zSe=rs({list:QQ.optional(),cancel:QQ.optional(),requests:rs({sampling:rs({createMessage:QQ.optional()}).optional(),elicitation:rs({create:QQ.optional()}).optional()}).optional()}),BSe=rs({list:QQ.optional(),cancel:QQ.optional(),requests:rs({tools:rs({call:QQ.optional()}).optional()}).optional()}),VSe=I({experimental:j(P(),QQ).optional(),sampling:I({context:QQ.optional(),tools:QQ.optional()}).optional(),elicitation:RSe.optional(),roots:I({listChanged:Yo().optional()}).optional(),tasks:zSe.optional(),extensions:j(P(),QQ).optional()}),HSe=n$.extend({protocolVersion:P(),capabilities:VSe,clientInfo:S$}),C$=i$.extend({method:M(`initialize`),params:HSe}),w$=e=>C$.safeParse(e).success,USe=I({experimental:j(P(),QQ).optional(),logging:QQ.optional(),completions:QQ.optional(),prompts:I({listChanged:Yo().optional()}).optional(),resources:I({subscribe:Yo().optional(),listChanged:Yo().optional()}).optional(),tools:I({listChanged:Yo().optional()}).optional(),tasks:BSe.optional(),extensions:j(P(),QQ).optional()}),WSe=s$.extend({protocolVersion:P(),capabilities:USe,serverInfo:S$,instructions:P().optional()}),T$=o$.extend({method:M(`notifications/initialized`),params:a$.optional()}),GSe=e=>T$.safeParse(e).success,E$=i$.extend({method:M(`ping`),params:n$.optional()}),KSe=I({progress:N(),total:Zo(N()),message:Zo(P())}),qSe=I({...a$.shape,...KSe.shape,progressToken:$Q}),D$=o$.extend({method:M(`notifications/progress`),params:qSe}),JSe=n$.extend({cursor:e$.optional()}),O$=i$.extend({params:JSe.optional()}),k$=s$.extend({nextCursor:e$.optional()}),YSe=$o([`working`,`input_required`,`completed`,`failed`,`cancelled`]),A$=I({taskId:P(),status:YSe,ttl:ds([N(),Qo()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Zo(N()),statusMessage:Zo(P())}),j$=s$.extend({task:A$}),XSe=a$.merge(A$),M$=o$.extend({method:M(`notifications/tasks/status`),params:XSe}),N$=i$.extend({method:M(`tasks/get`),params:n$.extend({taskId:P()})}),P$=s$.merge(A$),F$=i$.extend({method:M(`tasks/result`),params:n$.extend({taskId:P()})});s$.loose();const I$=O$.extend({method:M(`tasks/list`)}),L$=k$.extend({tasks:F(A$)}),R$=i$.extend({method:M(`tasks/cancel`),params:n$.extend({taskId:P()})}),ZSe=s$.merge(A$),z$=I({uri:P(),mimeType:Zo(P()),_meta:j(P(),A()).optional()}),B$=z$.extend({text:P()}),V$=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),H$=z$.extend({blob:V$}),U$=$o([`user`,`assistant`]),W$=I({audience:F(U$).optional(),priority:N().min(0).max(1).optional(),lastModified:ts({offset:!0}).optional()}),G$=I({...x$.shape,...b$.shape,uri:P(),description:Zo(P()),mimeType:Zo(P()),size:Zo(N()),annotations:W$.optional(),_meta:Zo(rs({}))}),QSe=I({...x$.shape,...b$.shape,uriTemplate:P(),description:Zo(P()),mimeType:Zo(P()),annotations:W$.optional(),_meta:Zo(rs({}))}),K$=O$.extend({method:M(`resources/list`)}),$Se=k$.extend({resources:F(G$)}),q$=O$.extend({method:M(`resources/templates/list`)}),eCe=k$.extend({resourceTemplates:F(QSe)}),J$=n$.extend({uri:P()}),tCe=J$,Y$=i$.extend({method:M(`resources/read`),params:tCe}),nCe=s$.extend({contents:F(ds([B$,H$]))}),rCe=o$.extend({method:M(`notifications/resources/list_changed`),params:a$.optional()}),iCe=J$,aCe=i$.extend({method:M(`resources/subscribe`),params:iCe}),oCe=J$,sCe=i$.extend({method:M(`resources/unsubscribe`),params:oCe}),cCe=a$.extend({uri:P()}),lCe=o$.extend({method:M(`notifications/resources/updated`),params:cCe}),uCe=I({name:P(),description:Zo(P()),required:Zo(Yo())}),dCe=I({...x$.shape,...b$.shape,description:Zo(P()),arguments:Zo(F(uCe)),_meta:Zo(rs({}))}),X$=O$.extend({method:M(`prompts/list`)}),fCe=k$.extend({prompts:F(dCe)}),pCe=n$.extend({name:P(),arguments:j(P(),P()).optional()}),Z$=i$.extend({method:M(`prompts/get`),params:pCe}),Q$=I({type:M(`text`),text:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),$$=I({type:M(`image`),data:V$,mimeType:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),e1=I({type:M(`audio`),data:V$,mimeType:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),mCe=I({type:M(`tool_use`),name:P(),id:P(),input:j(P(),A()),_meta:j(P(),A()).optional()}),hCe=I({type:M(`resource`),resource:ds([B$,H$]),annotations:W$.optional(),_meta:j(P(),A()).optional()}),t1=ds([Q$,$$,e1,G$.extend({type:M(`resource_link`)}),hCe]),gCe=I({role:U$,content:t1}),_Ce=s$.extend({description:P().optional(),messages:F(gCe)}),vCe=o$.extend({method:M(`notifications/prompts/list_changed`),params:a$.optional()}),yCe=I({title:P().optional(),readOnlyHint:Yo().optional(),destructiveHint:Yo().optional(),idempotentHint:Yo().optional(),openWorldHint:Yo().optional()}),bCe=I({taskSupport:$o([`required`,`optional`,`forbidden`]).optional()}),n1=I({...x$.shape,...b$.shape,description:P().optional(),inputSchema:I({type:M(`object`),properties:j(P(),QQ).optional(),required:F(P()).optional()}).catchall(A()),outputSchema:I({type:M(`object`),properties:j(P(),QQ).optional(),required:F(P()).optional()}).catchall(A()).optional(),annotations:yCe.optional(),execution:bCe.optional(),_meta:j(P(),A()).optional()}),r1=O$.extend({method:M(`tools/list`)}),xCe=k$.extend({tools:F(n1)}),i1=s$.extend({content:F(t1).default([]),structuredContent:j(P(),A()).optional(),isError:Yo().optional()});i1.or(s$.extend({toolResult:A()}));const SCe=r$.extend({name:P(),arguments:j(P(),A()).optional()}),a1=i$.extend({method:M(`tools/call`),params:SCe}),CCe=o$.extend({method:M(`notifications/tools/list_changed`),params:a$.optional()});I({autoRefresh:Yo().default(!0),debounceMs:N().int().nonnegative().default(300)});const o1=$o([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wCe=n$.extend({level:o1}),s1=i$.extend({method:M(`logging/setLevel`),params:wCe}),TCe=a$.extend({level:o1,logger:P().optional(),data:A()}),ECe=o$.extend({method:M(`notifications/message`),params:TCe}),DCe=I({hints:F(I({name:P().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),OCe=I({mode:$o([`auto`,`required`,`none`]).optional()}),kCe=I({type:M(`tool_result`),toolUseId:P().describe(`The unique identifier for the corresponding tool call.`),content:F(t1).default([]),structuredContent:I({}).loose().optional(),isError:Yo().optional(),_meta:j(P(),A()).optional()}),ACe=is(`type`,[Q$,$$,e1]),c1=is(`type`,[Q$,$$,e1,mCe,kCe]),jCe=I({role:U$,content:ds([c1,F(c1)]),_meta:j(P(),A()).optional()}),MCe=r$.extend({messages:F(jCe),modelPreferences:DCe.optional(),systemPrompt:P().optional(),includeContext:$o([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:F(P()).optional(),metadata:QQ.optional(),tools:F(n1).optional(),toolChoice:OCe.optional()}),NCe=i$.extend({method:M(`sampling/createMessage`),params:MCe}),l1=s$.extend({model:P(),stopReason:Zo($o([`endTurn`,`stopSequence`,`maxTokens`]).or(P())),role:U$,content:ACe}),u1=s$.extend({model:P(),stopReason:Zo($o([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(P())),role:U$,content:ds([c1,F(c1)])}),PCe=I({type:M(`boolean`),title:P().optional(),description:P().optional(),default:Yo().optional()}),FCe=I({type:M(`string`),title:P().optional(),description:P().optional(),minLength:N().optional(),maxLength:N().optional(),format:$o([`email`,`uri`,`date`,`date-time`]).optional(),default:P().optional()}),ICe=I({type:$o([`number`,`integer`]),title:P().optional(),description:P().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),LCe=I({type:M(`string`),title:P().optional(),description:P().optional(),enum:F(P()),default:P().optional()}),RCe=I({type:M(`string`),title:P().optional(),description:P().optional(),oneOf:F(I({const:P(),title:P()})),default:P().optional()}),zCe=ds([ds([I({type:M(`string`),title:P().optional(),description:P().optional(),enum:F(P()),enumNames:F(P()).optional(),default:P().optional()}),ds([LCe,RCe]),ds([I({type:M(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:I({type:M(`string`),enum:F(P())}),default:F(P()).optional()}),I({type:M(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:I({anyOf:F(I({const:P(),title:P()}))}),default:F(P()).optional()})])]),PCe,FCe,ICe]),BCe=ds([r$.extend({mode:M(`form`).optional(),message:P(),requestedSchema:I({type:M(`object`),properties:j(P(),zCe),required:F(P()).optional()})}),r$.extend({mode:M(`url`),message:P(),elicitationId:P(),url:P().url()})]),VCe=i$.extend({method:M(`elicitation/create`),params:BCe}),HCe=a$.extend({elicitationId:P()}),UCe=o$.extend({method:M(`notifications/elicitation/complete`),params:HCe}),d1=s$.extend({action:$o([`accept`,`decline`,`cancel`]),content:ls(e=>e===null?void 0:e,j(P(),ds([P(),N(),Yo(),F(P())])).optional())}),WCe=I({type:M(`ref/resource`),uri:P()}),GCe=I({type:M(`ref/prompt`),name:P()}),KCe=n$.extend({ref:ds([GCe,WCe]),argument:I({name:P(),value:P()}),context:I({arguments:j(P(),P()).optional()}).optional()}),f1=i$.extend({method:M(`completion/complete`),params:KCe});function qCe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function JCe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const YCe=s$.extend({completion:rs({values:F(P()).max(100),total:Zo(N().int()),hasMore:Zo(Yo())})}),XCe=I({uri:P().startsWith(`file://`),name:P().optional(),_meta:j(P(),A()).optional()}),ZCe=i$.extend({method:M(`roots/list`),params:n$.optional()}),p1=s$.extend({roots:F(XCe)}),QCe=o$.extend({method:M(`notifications/roots/list_changed`),params:a$.optional()});ds([E$,C$,f1,s1,Z$,X$,K$,q$,Y$,aCe,sCe,a1,r1,N$,F$,I$,R$]),ds([y$,D$,T$,QCe,M$]),ds([v$,l1,u1,d1,p1,P$,L$,j$]),ds([E$,NCe,VCe,ZCe,N$,F$,I$,R$]),ds([y$,D$,ECe,lCe,rCe,CCe,vCe,M$,UCe]),ds([v$,WSe,YCe,_Ce,fCe,$Se,eCe,nCe,i1,xCe,P$,L$,j$]);var m1=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===m$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new $Ce(e.elicitations,n)}return new e(t,n,r)}},$Ce=class extends m1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(m$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function h1(e){return e===`completed`||e===`failed`||e===`cancelled`}const ewe=Symbol(`Let zodToJsonSchema decide on which parser to use`),g1={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`},twe=e=>typeof e==`string`?{...g1,name:e}:{...g1,...e},nwe=e=>{let t=twe(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 _1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function v1(e,t,n,r,i){e[t]=n,_1(e,t,r,i)}const y1=(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 b1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?y1(t,e.currentPath):t.join(`/`)}}function rwe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==zQ.ZodAny&&(n.items=N1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&v1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&v1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(v1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),v1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function iwe(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?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function awe(){return{type:`boolean`}}function x1(e,t){return N1(e.type._def,t)}const owe=(e,t)=>N1(e.innerType._def,t);function S1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>S1(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 swe(e,t)}}const swe=(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`:v1(n,`minimum`,r.value,r.message,t);break;case`max`:v1(n,`maximum`,r.value,r.message,t);break}return n};function cwe(e,t){return{...N1(e.innerType._def,t),default:e.defaultValue()}}function lwe(e,t){return t.effectStrategy===`input`?N1(e.schema._def,t):b1(t)}function uwe(e){return{type:`string`,enum:Array.from(e.values)}}const dwe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function fwe(e,t){let n=[N1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),N1(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(dwe(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 pwe(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 C1;const w1={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:()=>(C1===void 0&&(C1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),C1),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 T1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:v1(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`:D1(n,`email`,r.message,t);break;case`format:idn-email`:D1(n,`idn-email`,r.message,t);break;case`pattern:zod`:O1(n,w1.email,r.message,t);break}break;case`url`:D1(n,`uri`,r.message,t);break;case`uuid`:D1(n,`uuid`,r.message,t);break;case`regex`:O1(n,r.regex,r.message,t);break;case`cuid`:O1(n,w1.cuid,r.message,t);break;case`cuid2`:O1(n,w1.cuid2,r.message,t);break;case`startsWith`:O1(n,RegExp(`^${E1(r.value,t)}`),r.message,t);break;case`endsWith`:O1(n,RegExp(`${E1(r.value,t)}$`),r.message,t);break;case`datetime`:D1(n,`date-time`,r.message,t);break;case`date`:D1(n,`date`,r.message,t);break;case`time`:D1(n,`time`,r.message,t);break;case`duration`:D1(n,`duration`,r.message,t);break;case`length`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),v1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:O1(n,RegExp(E1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&D1(n,`ipv4`,r.message,t),r.version!==`v4`&&D1(n,`ipv6`,r.message,t);break;case`base64url`:O1(n,w1.base64url,r.message,t);break;case`jwt`:O1(n,w1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&O1(n,w1.ipv4Cidr,r.message,t),r.version!==`v4`&&O1(n,w1.ipv6Cidr,r.message,t);break;case`emoji`:O1(n,w1.emoji(),r.message,t);break;case`ulid`:O1(n,w1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:D1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:v1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:O1(n,w1.base64,r.message,t);break}break;case`nanoid`:O1(n,w1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function E1(e,t){return t.patternStrategy===`escape`?hwe(e):e}const mwe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function hwe(e){let t=``;for(let n=0;n<e.length;n++)mwe.has(e[n])||(t+=`\\`),t+=e[n];return t}function D1(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}}})):v1(e,`format`,t,n,r)}function O1(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:k1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):v1(e,`pattern`,k1(t,r),n,r)}function k1(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
1193
+ `).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 tr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Wa=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Ga(e){try{let t=la(e.scope);if(!t)return;let n=rF(t);if(n.length===0)return;let r=lF(V(e.skillsRoot,e.name),e.name,t,n,`copy`,iF(e.scope));if(r.length===0)return;await OA(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){jX.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function Ka(e,t){if(t.ok){Y(e,200,hn,t.body,{handler:`skill-import`});return}J(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 qa=fxe({contentDir:l,skillsHome:ji,...k===void 0?{}:{projectDir:k},resolveSkillDirForRead:Fi,parseFrontmatterDoc:Di,attributeOkArtifactWrite:Hn,commitOkArtifactWrite:tr,shadowHeadSha:Ua,artifactWriterId:Wa,effectiveInstallMode:qi,signalFiles:()=>at?.(`files`)}),Ja=_xe({contentDir:l,skillsHome:ji,...k===void 0?{}:{projectDir:k},legacyStoreRoot:zr,effectiveSkillRoot:ya,parseFrontmatterDoc:Di,attributeOkArtifactWrite:Hn,commitOkArtifactWrite:tr,shadowHeadSha:Ua,artifactWriterId:Wa,skillArtifactKey:e=>Vn(`skill`,``,e),captureAndCloseDocuments:mn,projectImportedSkillCopy:Ga,signalFiles:()=>at?.(`files`)});function Ya(e,t){if(t.ok){Y(e,200,or,t.body,{handler:`skill-reimport`});return}J(e,t.status,t.urn,t.title,{handler:`skill-reimport`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}function Xa(e,t,n){let r=e===`project`?l:ji,i=(e===`project`?MF(l):NF(ji)).find(e=>e.name===t);return i?V(r,i.dir):V(n,t)}function Za(e,t,n,r){let i=r.skills[t];if(i)return i;let a=Xa(e,t,n);return lde(t,eD(a)?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:bxe(a)})??$i(e===`global`?ji:l,t)??ia(t,Ad(k??l),a)}let Qa=X(bt,async(e,t,n)=>{let r=()=>{};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(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 aD(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??VE(d);if(!p){J(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(Dq(t,p,`skill-import`))return;let m=await UE(p);r=m.cleanup,s=m.ref;let h=tD(m.dir);if(h.length===0){J(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=>QE(e.dir)?.name===f)??h.find(e=>e.name===Pt[f]);if(!e){J(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){J(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??Ba(d)}catch(e){if(e instanceof NE){J(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){J(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await qa.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||Oe(u))&&qP({source:u,skills:[d.body.name]},EP()),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),at?.(`files`),Ka(t,d)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),$a=X(See,async(e,t,n)=>{let r=()=>{};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(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 aD(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??VE(d);if(!f){J(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(Dq(t,f,`skills-import-bulk`))return;if(l=e?.publisher??Ba(d),f.kind===`well-known`)a=f,o=await zE(f.origin);else{let e=await UE(f);r=e.cleanup,c=e.ref,s=tD(e.dir)}}catch(e){if(e instanceof NE){J(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){J(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 UE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof NE?`not-found`:`failed`,warnings:[],...e instanceof NE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>eD(e.dir)?.name===t)??s.find(e=>e.name===Pt[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await qa.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||Oe(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&qP({source:u,skills:e},EP())}Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),at?.(`files`),Y(t,200,mo,{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){J(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`}),eo=8*1024*1024,to=32*1024*1024;function no(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+H)?null:r}function ro(e){return new Promise((t,n)=>{let r;try{r=HR(e,{files:200,fields:10,fieldSize:2*1024,fileSize:eo})}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>to){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 ao(e,t){return new Promise((n,r)=>{(0,hfe.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=no(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){tc(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>eo){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>to){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{tc(R(n),{recursive:!0}),cc(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 oo(e,t){let n=bu(z(Iu(),`ok-skill-upload-`)),r=()=>{try{ac(n,{recursive:!0,force:!0})}catch{}};try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){J(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=Ai(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=JI({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},De);if(o.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ro(e)}catch(e){J(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){J(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 ao(c.data,n)}catch(e){J(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=no(n,e.relPath);if(!r){J(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}tc(R(r),{recursive:!0}),cc(r,e.data)}let u=tD(n);if(u.length===0){J(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){J(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];Ka(t,await qa.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let so=X(Wee,async(e,t,n)=>{try{let e=Pi(n.scope);if(!ki(n.name,t,`skill-install`))return;if(n.scope===`project`&&!k){J(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=la(n.scope),i=V(e,n.name),a=n.scope===`project`?l:ji,o=(n.scope===`project`?MF(l):NF(ji)).find(e=>e.name===n.name),s=zD(n.name)?aa(n.name,n.scope):null,c=o?V(a,o.dir):U(i)||s===null?i:R(s);if(!U(c)){J(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 Bt(n.scope===`project`?`${B(a,c).split(H).join(`/`)}/SKILL`:It(n.scope,n.name));let u=nF(c,n.name,{allowReservedName:zD(n.name)});if(!u.ok){J(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${u.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){J(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Mi.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:J(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:J(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:J(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`:J(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:J(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)}`)}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o.hosts.filter(Ht),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let d=n.setSource??n.source,f=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),p=n.targets,m=[],h=[];if(n.add!==void 0||n.remove!==void 0){if(!o){J(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 Mi.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`?J(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`}):J(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}p=e.targets.filter(Ht),m.push(...e.rootAdds),h.push(...e.rootRemoves)}if(d&&!o){let e=await Mi.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:c,newSource:d});if(!e.ok){J(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}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?k:ji;if(!e){J(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 _r.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:c,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?J(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):J(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||at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?k:ji;if(!e){J(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 _r.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:c});if(!r.ok)switch(r.kind){case`not-recorded`:J(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:J(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:J(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`:J(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)}`)}at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,Gn,{name:n.name,hosts:o?[...o.hosts]:[],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){J(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`?k:ji,s=await _r.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`:J(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:J(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`:J(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`:J(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)}`)}at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:[...o.hosts],scripts:u.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let g=n.scope===`global`?p===void 0?XP(ji).map(e=>e.editorId):uee.filter(e=>p?.some(t=>t===e)):p===void 0?rF(r):zi.filter(e=>p?.some(t=>t===e)),_=[],v=[];if(g.length===0&&p===void 0&&(_.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),v.push(`no-targets`)),u.hasScripts&&(_.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),v.push(`scripts-present`)),u.warnings.length>0&&(_.push(u.warnings[0]),v.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(p===void 0?n.scope===`global`&&U(z(ji,`.agents`)):p.includes(`agents`))?[...g,`agents`]:[...g],a=n.scope===`project`?k:ji,s=f===void 0?qi(n.scope,n.name,o):f?`link`:`copy`;if(d){let e=await Mi.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,newSource:d});if(!e.ok){e.kind===`invalid-target`?J(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}):J(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}at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:e.hosts,scripts:u.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let l=await Mi.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:c,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:p!==void 0,installMode:s,...f===void 0?{}:{linkModeReq:f},rootAdds:m,rootRemoves:h});if(!l.ok){J(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:l.reason});return}_.push(...l.warnings),v.push(...l.warningCodes),at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:l.hosts,scripts:u.hasScripts,warnings:_,warningCodes:v,...l.sourceMovedTo===void 0?{}:{sourceMovedTo:l.sourceMovedTo}},{handler:`skill-install`});return}let y=eF(EA(r).skills[n.name]?.hosts??[]).filter(e=>!g.includes(e));y.length>0&&_F(n.name,r,y,iF(n.scope));let b=z(r,...WE),x=U(b)?W(b,`utf-8`):null,S=x===null?null:KE(x);x!==null&&S===null&&jX.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let C=S?.skills[n.name]!==void 0,w=f===void 0?C?`copy`:`symlink`:f?`symlink`:`copy`,T=lF(c,n.name,r,g,w,iF(n.scope));T.length===0?await kA(r,n.name):await OA(r,n.name,{hosts:T,scope:n.scope,scripts:u.hasScripts,installedAt:new Date().toISOString(),projection:w}),at?.(`files`),Y(t,200,Gn,{name:n.name,hosts:T,scripts:u.hasScripts,warnings:_,warningCodes:v},{handler:`skill-install`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),co=X(kee,async(e,t,n)=>{try{if(!ki(n.name,t,`skill-uninstall`))return;let e=la(n.scope);if(!e){J(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 ua(e,n.name,n.scope);at?.(`files`),Y(t,200,lee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),lo=X(oee,async(e,t,n)=>{try{let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!ki(n.name,t,`skill-restore`)||sa(n.name,t,`skill-restore`))return;if(n.scope===`global`){J(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=ae?.current;if(!r){J(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 gX({shadow:r,contentDir:l,contentRoot:de??`.`,name:n.name,version:n.version,skillDirRel:Ji(n.name)});if(!i.ok){Gi(t,i,`skill-restore`);return}let a=[],o=nF(V(l,Ji(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),Hn(e,Vn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await tr(`skill-restore`),at?.(`files`),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,cn,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),fo=X(iee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!ki(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?ji:l,{root:a,dirRel:o,realDir:s}=ya(n.scope,n.name);if(s===null||!U(V(i,o,`SKILL.md`))){J(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let c=z(n.scope===`global`?ji:k,...WE),u=Za(n.scope,n.name,a,Va(c));if(!u){J(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 zK(c,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??u,autoUpdate:n.setAutoUpdate}}})),Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Y(t,200,or,{name:n.name,updated:!1,source:u.source,warnings:[]},{handler:`skill-reimport`});return}let d,f=null;try{let e=u.skill??n.name,i=Pt[e],a=await aD(u.source,e).catch(async e=>{if(i===void 0)throw e;return aD(u.source,i)}),o=a?.source??DD(u.source,u.pluginProvider),s=a?.skill??u.skill,c=a?.spec??VE(o);if(!c){J(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:u.source});return}if(Dq(t,c,`skill-reimport`))return;let l=await UE(c);r=l.cleanup,d=l.ref;let p=tD(l.dir),m=pX(p,{...s===void 0?{}:{recordedSkill:s},localName:n.name,frontmatterNameOf:e=>eD(e)?.name});if(!m){J(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:p.map(e=>e.name).join(`, `)});return}f=m.dir}catch(e){if(e instanceof NE){J(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!f){J(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let p=await Ja.runSkillReimport({acquiredDir:f,name:n.name,scope:n.scope,entry:u,lockPath:c,ref:d,actor:e,...n.dryRun===void 0?{}:{dryRun:n.dryRun}});Jn(),ze?.refreshInPlaceSkillDirs(),Zn(),Ya(t,p)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),po=X(di,async(e,t,n)=>{try{if(n.scope===`project`&&!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-reimport-bulk`,detail:`NO_PROJECT_ROOT`});return}let r=JI(n,De);if(r.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-reimport-bulk`});return}let i=z(n.scope===`global`?ji:k,...WE),a=Va(i),o=[],{bySource:s,unrecorded:c}=gxe([...new Set(n.names)].filter(e=>Oi(e)?!0:(o.push({requested:e,status:`failed`,warnings:[],error:`INVALID_NAME`}),!1)),e=>Za(n.scope,e,ya(n.scope,e).root,a));for(let e of c)o.push({requested:e,status:`not-found`,warnings:[]});for(let t of s){let s=()=>{};try{let c,l=[];try{let e=t.names[0],n=await aD(t.source,e).catch(async n=>{let r=Pt[e];if(r===void 0)throw n;return aD(t.source,r)}),r=n?.source??DD(t.source,a.skills[t.names[0]]?.pluginProvider),i=n?.spec??VE(r);if(!i||Eq(i)){for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:`INVALID_SOURCE`});continue}let u=await UE(i);s=u.cleanup,c=u.ref,l=tD(u.dir)}catch(n){L(`skills-reimport-bulk`).warn({source:t.source,err:n,requestId:tS(e)},`bulk update: one source could not be fetched (rest continue)`);for(let e of t.names)o.push({requested:e,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)});continue}for(let s of t.names){let t=Za(n.scope,s,ya(n.scope,s).root,a);if(!t){o.push({requested:s,status:`not-found`,warnings:[]});continue}let u=pX(l,{...t.skill===void 0?{}:{recordedSkill:t.skill},localName:s,frontmatterNameOf:e=>eD(e)?.name});if(!u){o.push({requested:s,status:`not-found`,source:t.source,warnings:[]});continue}try{let a=await Ja.runSkillReimport({acquiredDir:u.dir,name:s,scope:n.scope,entry:t,lockPath:i,ref:c,actor:r});if(!a.ok){L(`skills-reimport-bulk`).warn({skill:s,err:a.cause,detail:a.detail,requestId:tS(e)},`bulk update: one skill failed (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:a.detail??a.title});continue}o.push({requested:s,status:a.body.updated?`updated`:`up-to-date`,source:a.body.source,warnings:a.body.warnings})}catch(n){L(`skills-reimport-bulk`).warn({skill:s,err:n,requestId:tS(e)},`bulk update: one skill threw (rest continue)`),o.push({requested:s,status:`failed`,source:t.source,warnings:[],error:n instanceof Error?n.message:String(n)})}}}finally{s()}}Y(t,200,ja,{results:o,updated:o.filter(e=>e.status===`updated`).length,upToDate:o.filter(e=>e.status===`up-to-date`).length,failed:o.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-reimport-bulk`});try{Jn(),ze?.refreshInPlaceSkillDirs(),Jn(),await ze?.rebuildIgnorePatterns()}catch(e){L(`skills-reimport-bulk`).warn({err:e},`bulk update: ignore-pattern rebuild failed after a reported success`)}}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to update skills.`,{handler:`skills-reimport-bulk`,cause:e})}},{handler:`skills-reimport-bulk`,method:`POST`}),ho=X(u,async(e,t,n)=>{try{if(!k){J(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=JI(n,De);if(e.kind===`invalid-summary`){J(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!ki(n.name,t,`skill-revert`)||sa(n.name,t,`skill-revert`))return;if(n.scope===`global`){J(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(k,...WE),i=Va(r).skills[n.name];if(!i?.baselineRef){J(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=ae?.current;if(!a){J(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 gX({shadow:a,contentDir:l,contentRoot:de??`.`,name:n.name,version:i.baselineRef,skillDirRel:Ji(n.name)});if(!o.ok){Gi(t,o,`skill-revert`);return}Hn(e,Vn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await tr(`skill-revert`);let s=V(l,Ji(n.name),`..`),c=Ha(s,n.name);await zK(r,e=>qE(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Pi(`project`)&&await Ga({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),at?.(`files`),Y(t,200,pee,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`}),go=uxe({contentDir:l,projectDir:k,getAllFilesIndex:x,getFileIndexGeneration:w,getSearchMaxEntries:Exe,semanticSearch:Ke,getSemanticSimilarityFloor:qe,ready:He,getProjectSkillsRoot:()=>Pi(`project`),parseFrontmatterDoc:Di});go.prewarm();let _o=`local-op-embeddings-set-key`,vo=`local-op-embeddings-clear-key`,yo=`/api/local-op/embeddings`;function bo(){let e=Ye?.();return{projectDir:k??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let xo=X(Xe,async(e,t,n)=>{if(!ot.tryAcquire(yo)){J(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:_o,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=bo();await new Ek(Je).setForProject(e,r,n.key),Ke?.reloadCredential(),Y(t,200,ke,{keyPresent:!0},{handler:_o,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:_o,cause:e})}finally{ot.release(yo)}},{handler:_o,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:_o})}),So=X(wa,async(e,t)=>{if(!ot.tryAcquire(yo)){J(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:vo,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=bo();await new Ek(Je).clearForProject(e,n),Ke?.reloadCredential(),Y(t,200,ke,{keyPresent:!1},{handler:vo,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:vo,cause:e})}finally{ot.release(yo)}},{handler:vo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:vo})}),Co=`local-op-embeddings-test`,wo=`/api/local-op/embeddings/test`,To=X(wa,async(e,t)=>{if(!ot.tryAcquire(wo)){J(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Co,extraHeaders:{"Retry-After":`5`}});return}try{let e=Ye?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await hk(new Ek(Je),k??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await _k({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,vt,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Co,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Co,cause:e})}finally{ot.release(wo)}},{handler:Co,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Co})}),Eo=0;function Do(){Eo+=1,at?.(`lint-config`)}let Oo=()=>`${Eo} ${t.getActiveBranch()} ${pe?.readLocalTargetGeneration?.()??0}`;async function ko(e,t){let n=Qe?.()??Yr;try{let r=await Dn(e,fN(l,n,{docName:t,projectDir:k??l,onProblem:e=>jX.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=$e?.()??`warning`;if(pe&&a!==`off`&&!Yx(t)){await Zt(t,e,`lint-validation`);let r=HN({projectDir:k??l,contentDir:l,baseConfig:n,derivedDocumentIndex:pe,linksValidation:a,admittedDocNames:Jt,docFilePathFor:e=>YX(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:YX(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return jX.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ao(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=hN({projectDir:k??l,contentDir:l});return FM(t.schemas,n)}let jo={"/api/asset":Sr,"/api/asset-text":wr,"/api/skill":Oa,"/api/skill-file":Ra,"/api/skill-file/rename":za,"/api/skills":ha,"/api/skill/import":Qa,"/api/skills/import-bulk":$a,"/api/skill/edit-external":Ta,"/api/skill/duplicate":Da,"/api/skill/move-scope":Ea,"/api/skill-upload":oo,"/api/skill/install":so,"/api/skill/uninstall":co,"/api/skill/restore":lo,"/api/skill/reimport":fo,"/api/skills/reimport-bulk":po,"/api/skill/revert":ho,"/api/skill/track-in-git":pa,"/api/lint/markdownlint-config":X(Tee,async(e,t,n)=>{let r;try{r=TN(V(l),n.ruleId,n.value)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){J(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}Do();try{let e=Qe?.()??Yr,n=[],r=lN(l,void 0,e=>n.push(e)),i=dN(k??l,uN(e,r),e=>n.push(e));n.push(...Ao(i)),Y(t,200,Nn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){J(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`}),"/api/lint/frontmatter-schema":X(C,async(e,t,n)=>{let r;try{let e=V(k??l),t=n.parentPath??[];r=n.delete?Upe(e,n.file):n.field!==void 0&&n.removeField?Vpe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Hpe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?zpe(e,n.file,n.field,n.constraint,t):Bpe(e,n.file)}catch(e){J(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){J(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`)&&at?.(`files`),Do();try{let e=Qe?.()??Yr,n=[],r=lN(l,void 0,e=>n.push(e)),i=dN(k??l,uN(e,r),e=>n.push(e));n.push(...Ao(i)),Y(t,200,Nn,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){J(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`}),"/api/lint/fix":X(Pe,async(t,n,r)=>{try{let t=UX(r.docName,n,`lint-fix`);if(t===null)return;let i=jt(t),a=JI(r,De);if(a.kind===`invalid-summary`){J(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Hx(i)||Ux(i)){J(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=YX(l,i);if(f===null){J(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}Yk(V(l,f),l);let p=Qe?.()??Yr,{stored:m}=In(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),_=[],{cfg:v,before:y,fixed:b,ran:x,failures:S}=await Ipe({projectDir:k??l,contentDir:l,baseConfig:p,docRelPath:f,source:g,onConfigProblem:e=>_.push(e)}),C=y,w,T=[];if(b!==g){try{let t=ee(d),n=Ho[t]??No(u??o);ve?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{XC(h.dc.document,b,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,JC(h))},h.origin),a.kind!==`anonymous`&&AO(i,o,s,u,void 0,a.kind===`agent`?Fn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{ve?.touchMode(o,`idle`)}let t=await Bt(i);if(t?.kind===`failure`){Vt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Ut(n,`lint-fix`);return}zt(i,`lint-fix`);try{C=await Dn(h.dc.document.getText(`source`).toString(),v,f,e=>T.push(e))}catch(e){w=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,jX.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),C=y}}let E=C.filter(e=>e.severity===`error`).length,D=C.length-E,te=Math.max(0,y.length-C.length),O=[..._,...Wi([...S,...T]),...w?[w]:[]];Y(n,200,st,{file:f,fixedCount:te,diagnostics:C,errorCount:E,warningCount:D,ran:x,...O.length>0?{warnings:O}:{},...w?{warning:w}:{}},{handler:`lint-fix`})}catch(e){if(Zk(e)){J(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof uS){dS(n,e,`lint-fix`);return}if(e instanceof _S){bS(n,e,`lint-fix`);return}if(e instanceof ow){J(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}jX.error({err:e},`[lint-fix] handler failed`),J(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),"/api/agent-write":nr,"/api/agent-write-md":rr,"/api/agent-write-batch":ar,"/api/frontmatter-patch":sr,"/api/agent-patch":cr,"/api/agent-undo":lr,"/api/agent-activity":ur,"/api/agent-burst-diff":dr,"/api/save-version":vr,"/api/rollback":yr,"/api/local-op/clone":Mr,"/api/local-op/ok-init":Lr,"/api/local-op/auth/login":ni,"/api/local-op/auth/status":ui,"/api/local-op/auth/pat":mi,"/api/local-op/auth/gh-login":ai,"/api/local-op/auth/cancel":ci,"/api/local-op/auth/repos":gi,"/api/local-op/auth/signout":yi,"/api/local-op/auth/set-identity":Ci,"/api/local-op/embeddings/set-key":xo,"/api/local-op/embeddings/clear-key":So,"/api/local-op/embeddings/test":To,"/api/install-skill":wi};re&&(jo[`/api/test-reset`]=pr,jo[`/api/test-flush-git`]=fr,jo[`/api/test-rescan-backlinks`]=mr,jo[`/api/test-rescan-files`]=hr);let Mo=new Set(`/api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./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/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skills/reimport-bulk./api/skill/revert./api/skill/track-in-git`.split(`.`)),Po=[`/api/local-op/`],Fo=qL({log:jX,policy:n,ephemeral:et,table:{resolve(e){let t=jo[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:{template:`/api/*`}},isMutating:e=>Mo.has(e)||Po.some(t=>e.startsWith(t))}}),Io=[cK({hocuspocus:s,derivedDocumentIndex:pe,getFileIndex:v,isSafeDocName:aZ,readPageTitleForDocName:St,readPageTitleForLinkedDocName:wt,readFrontmatterMetadataForLinkedDocName:kt,collectAdmittedDocNames:Jt,resolveAlias:jt,respondToDerivedIndexQueryFailure:en}),pK({hocuspocus:s,agentPresenceBroadcaster:ve,isAllowedWorkspaceHostHeader:i,log:jX}),ct,Yge({contentDir:l,projectDir:k,ephemeral:et,log:jX,ready:He,durabilityState:t,serverInstanceId:m,getDiskAckSVs:le,getCollabClientCount:ue,getConfigDiagnostics:rt,acpRegistry:Ne,loadAcpCustomAgents:Fe,acpHarnessAvailability:Ie,isRoutePeerAdmitted:o,isAllowedWorkspaceHostHeader:i,checkLocalOpSecurity:r,getPrincipal:De,semanticSearch:Ke,readSemanticProviderConfig:Ye,embeddingsSecretsFile:Je,getFileIndex:v,shadowRef:ae,getCurrentBranch:ce,installedAgentsCache:_t}),lK({hocuspocus:s,contentDir:l,projectDir:k,contentFilter:ze,isSafeDocName:aZ,resolveDocFilePath:YX,isValidRelativeContentPath:HX,streamShowAllEntries:VX,getLinterBaseConfig:Qe,getLinksValidationSetting:$e,derivedDocumentIndex:pe,collectAdmittedDocNames:Jt,unmatchedGlobProblems:Ao,readAuditGeneration:Oo}),eU({contentRoot:de,log:jX,shadowRef:ae,flushGitCommit:oe,commitOkArtifactWrite:tr,getCurrentBranch:ce,validateFolderRel:Ti,safeDocPath:MX,docTreePathCandidates:NX}),w_e({contentDir:l,projectDir:k,homeDirOverride:je,skillsHome:ji,isSafeDocName:aZ,commentService:xt,enumerateInstalledSkillsCached:Yn,checkLocalOpSecurity:r}),z_e({log:jX,skillsHome:ji,projectDir:k,contentDir:l,resolveSkillDirForRead:Fi}),tye({contentDir:l,projectDir:k,skillsHome:ji,homeDirOverride:je,savedThemeLockTimeoutMs:Me,ephemeral:et,log:jX,signalChannel:at,searchService:go,linkPreviewFetch:tt,getLinkPreviewsEnabled:nt,getGeneratedIndexSettingsStatus:d,setGeneratedIndexEnabled:f}),Gge({commentService:xt,getPrincipal:De,signalChannel:at}),H_e({projectDir:k,contentDir:l,getPrincipal:De,hocuspocus:s,log:jX,checkLocalOpSecurity:r,getSyncEngine:be,serializeDoc:We}),C_e({projectDir:k,contentDir:l,log:jX,checkLocalOpSecurity:r,localOpCliArgs:we,localOpGuard:ot,getSyncEngine:be,toGitRelativePath:ZX}),xV({projectDir:k,contentDir:l,contentFilter:ze,getFileIndex:v,checkLocalOpSecurity:r,getSyncEngine:be,getPrincipal:De,localOpCliArgs:we}),az({contentDir:l,projectDir:k,log:jX,getPrincipal:De,contentFilter:ze,signalChannel:at,hocuspocus:s,getSyncEngine:be,flushContributors:se,fileOpsService:Tr,assetService:br,extractAgentIdentity:Pn,recordDerivedDocumentBestEffort:Xt,invalidateReferencedAssetsCache:lt,listManagedDocNamesUnderFolderFromDisk:On,resolveContentEntryPath:WX,docNameForFileOperationPath:XX,withPeriod:fn,toManagedRenamePublicError:pn,attributeRenameWriteToActor:Bn,renameAttributionCounter:wX,_performAssetRename:An,_performDocumentToFileRename:jn,_performManagedRenameForDocs:Mn,isValidRelativeContentPath:HX}),g_e({contentDir:l,checkLocalOpSecurity:r}),J_e({contentDir:l,log:jX,checkLocalOpSecurity:r,installedAgentsCache:_t}),nV({contentDir:l,projectDir:k,ephemeral:et,log:jX,hocuspocus:s,sessionManager:c,getPrincipal:De,signalChannel:at,getSyncEngine:be,recentlyRemovedDocs:Ue,isSafeDocName:aZ,resolveAlias:jt,resolveContentEntryPath:WX,validateFolderRel:Ti,extractAgentIdentity:Pn,extractActorIdentityFromQuery:Ii,okArtifactKey:Vn,attributeOkArtifactWrite:Hn,scheduleOkArtifactFlush:er,flushDiskAndDetectOutcome:Bt,respondPersistenceFailure:Vt,respondDiskDivergence:Ut,registerWrittenDocInFileIndex:sn,captureAndCloseDocuments:mn,renameTrackedPathInGit:rZ,renamePathOnDisk:nZ,splitContentPath:GX,mutateFileIndex:S})],Lo=Io.flatMap(e=>[...e.paths]);FG(Lo,jo);let Ro=Io.map(e=>qL({log:jX,policy:n,ephemeral:et,table:e.table})),zo={paths:Lo,dispatch:async(e,t)=>{for(let n of Ro)if(await n(e,t))return!0;return!1}},Vo=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`]),Uo=Io.map(e=>e.table),Wo=e=>{for(let t of Uo){let n=t.resolve(e)?.dispatch;if(n!==void 0)return n}};for(let e of Vo)if(jo[e]===void 0&&Wo(e)===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await Fo(e,t)},nativeApi:zo,localApi:fK({resolve:e=>{if(!Vo.has(e))return;let t=jo[e];return t===void 0?Wo(e):t}})}}function sZ(e){let{contentFilter:t,contentSirv:n,inlineExtensions:r,assetExtensions:i,blocklistExtensions:a,ingressPolicy:o}=e;return(e,s,c)=>{let l;try{l=decodeURIComponent(e.url?.split(`?`)[0]?.replace(/^\//,``)??``)}catch{return c()}let u=au(l).slice(1).toLowerCase(),d=u===`md`||u===`mdx`;if(!l||t.isPathIgnored(l)||!d&&!i.has(u))return c();let f=e.socket?.remoteAddress;if(f!==void 0&&!zL(f,o)){J(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!BL(e.headers.host,o)){J(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:FL});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=nX(u,r);d||s.setHeader(`Content-Disposition`,p.disposition),p.csp!==null&&s.setHeader(`Content-Security-Policy`,p.csp),p.sandboxedHtml&&s.setHeader(`Cache-Control`,`no-store`),n(e,s,()=>{if(s.headersSent)return;let e=Ts.has(u);if(!e&&(i.has(u)||a.has(u))){s.statusCode=404,s.end();return}e&&(s.removeHeader(`Content-Security-Policy`),s.removeHeader(`Content-Disposition`),s.removeHeader(`X-Content-Type-Options`),s.removeHeader(`Cache-Control`)),c()})}}function cZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function Bxe(e){let t;try{t=wu(e.contentDir,{withFileTypes:!0})}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&kx(n.name,bs)&&e.basenameIndex.add(n.name)}async function lZ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await Vu(i,{withFileTypes:!0})}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=z(i,o.name),s=Uk(B(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await zu(a)}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Hu(a)}catch(t){let n=cZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Wk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Uu(i)}catch(t){let n=cZ(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()&&kx(a,gs)&&!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()&&kx(a,gs)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const uZ=I({principalId:P().optional(),tabSessionId:P().optional(),expectedServerInstanceId:P().optional(),expectedBranch:P().optional(),expectedDocLineageEpoch:P().optional(),clientProtocolVersion:N().optional(),clientRuntimeVersion:P().optional(),clientKind:P().optional()}).loose(),dZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function fZ(e){return dZ.includes(e)}function pZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Vxe(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!fZ(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 mZ=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=pZ(e,this.payload)}};function hZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=uZ.safeParse(t);return n.success?n.data:void 0}var gZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function _Z(e,t,n=``){e=une(`.`,e);let r=cne(e),i=0,a,o;for(;i<r.length;i++)a=Xu(e,r[i]),o=lne(a),o.isDirectory()?_Z(a,t,Xu(n,r[i])):t(Xu(n,r[i]),a,o)}function Hxe(e){let t=e.url;if(t==null)return;let n=e._parsedUrl;if(n&&n.raw===t)return n;let r=t,i=``,a,o;if(t.length>1){let e=t.indexOf(`#`,1);e!==-1&&(o=t.substring(e),r=t.substring(0,e)),e=r.indexOf(`?`,1),e!==-1&&(i=r.substring(e),r=r.substring(0,e),i.length>1&&(a=Sne.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const Uxe=()=>{};function Wxe(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function vZ(e,t){let n=0,r,i=e.length-1;e.charCodeAt(i)===47&&(e=e.substring(0,i));let a=[],o=`${e}/index`;for(;n<t.length;n++)r=t[n]?`.${t[n]}`:``,e&&a.push(e+r),a.push(o+r);return a}function Gxe(e,t,n){let r=0,i,a=vZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function Kxe(e,t,n,r){let i=0,a=vZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=su(z(e,c=a[i])),o.startsWith(e)&&fu.existsSync(o)){if(s=fu.statSync(o),s.isDirectory())continue;return l=yZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function qxe(e,t){return t.statusCode=404,t.end()}function Jxe(e,t,n,r,i){let a=200,o,s={};i={...i};for(let e in i)o=t.getHeader(e),o&&(i[e]=o);if((o=t.getHeader(`content-type`))&&(i[`Content-Type`]=o),e.headers.range){a=206;let[n,o]=e.headers.range.replace(`bytes=`,``).split(`-`),c=s.end=parseInt(o,10)||r.size-1,l=s.start=parseInt(n,10)||0;if(c>=r.size&&(c=r.size-1),l>=r.size)return t.setHeader(`Content-Range`,`bytes */${r.size}`),t.statusCode=416,t.end();i[`Content-Range`]=`bytes ${l}-${c}/${r.size}`,i[`Content-Length`]=c-l+1,i[`Accept-Ranges`]=`bytes`}t.writeHead(a,i),fu.createReadStream(n,s).pipe(t)}const Yxe={".br":`br`,".gz":`gzip`};function yZ(e,t,n){let r=Yxe[e.slice(-3)],i=Qbe(e.slice(0,r&&-3))||``;i===`text/html`&&(i+=`;charset=utf-8`);let a={"Content-Length":t.size,"Content-Type":i,"Last-Modified":t.mtime.toUTCString()};return r&&(a[`Content-Encoding`]=r),n&&(a.ETag=`W/"${t.size}-${t.mtime.getTime()}"`),a}function bZ(e,t={}){e=V(e||`.`);let n=t.onNoMatch||qxe,r=t.setHeaders||Uxe,i=t.extensions||[`html`,`htm`],a=t.gzip&&i.map(e=>`${e}.gz`).concat(`gz`),o=t.brotli&&i.map(e=>`${e}.br`).concat(`br`),s={},c=`/`,l=!!t.etag,u=!!t.single;if(typeof t.single==`string`){let e=t.single.lastIndexOf(`.`);c+=~e?t.single.substring(0,e):t.single}let d=[];t.ignores!==!1&&(d.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),t.dotfiles?d.push(/\/\.\w/):d.push(/\/\.well-known/),[].concat(t.ignores||[]).forEach(e=>{d.push(new RegExp(e,`i`))}));let f=t.maxAge!=null&&`public,max-age=${t.maxAge}`;f&&t.immutable?f+=`,immutable`:f&&t.maxAge===0&&(f+=`,must-revalidate`),t.dev||_Z(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=yZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?Kxe.bind(0,e+H,l):Gxe.bind(0,s);return function(e,t,s){let f=[``],m=Hxe(e).pathname,h=e.headers[`accept-encoding`]||``;if(a&&h.includes(`gzip`)&&f.unshift(...a),o&&/(br|brotli)/i.test(h)&&f.unshift(...o),f.push(...i),m.indexOf(`%`)!==-1)try{m=decodeURI(m)}catch{}let g=p(m,f)||u&&!Wxe(m,d)&&p(c,f);if(!g)return s?s():n(e,t);if(l&&e.headers[`if-none-match`]===g.headers.ETag)return t.writeHead(304),t.end();(a||o)&&t.setHeader(`Vary`,`Accept-Encoding`),r(t,m,g.stats),Jxe(e,t,g.abs,g.stats,g.headers)}}const xZ=L(`conflict-storage`);var SZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=z(lO(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!U(this.storePath)){this.conflicts=[];return}try{let e=W(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){xZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){xZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=R(this.storePath);U(e)||yu(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return ju(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return xZ.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()||xZ.error({branch:this.branch},`[conflicts] cleared conflicts in memory but conflicts.json persist failed — the ledger will resurrect them on restart`)}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n){let r=this.conflicts.find(t=>t.file===e);if(!r)throw new pS({file:e});if(t===`content`&&n!==void 0&&age(n))throw new fS({file:e});if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-CzN6a5i1.mjs`),a=i(this.projectDir,{credentialConfig:[]});switch(t){case`mine`:await a.git.raw([`checkout`,`--ours`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`theirs`:await a.git.raw([`checkout`,`--theirs`,`--`,e]),await a.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=V(this.projectDir),r=V(t,e);if(!Wk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Pq(r,t,{allowShareableOkArtifact:dM}),cc(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}let o=new Map(this.list().map(e=>[e.file,e.detectedAt]));if(this.removeConflict(e)||xZ.error({file:e},`[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart`),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),xZ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Ab(a.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:o.get(t)??n});r=e.length>0}catch(e){xZ.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:o.get(e)??n}),xZ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n){let r=V(this.projectDir),i=V(r,e.file);if(!Wk(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);Pq(i,r,{allowShareableOkArtifact:dM});let a={...e};this.removeConflict(e.file)||xZ.error({file:e.file},`[conflicts] resolve dropped the conflict in memory but conflicts.json persist failed — the ledger will resurrect this conflict on restart`);try{await this.applyWorkingTreeStrategy(i,r,e,t,n)}catch(t){throw this.addConflict(a)||xZ.error({file:e.file,err:t},`[conflicts] resolve rolled back in memory but conflicts.json persist failed — the ledger will lose this conflict on restart`),t}}async applyWorkingTreeStrategy(e,t,n,r,i){switch(r){case`mine`:break;case`theirs`:{if(!n.theirsSha)throw Error(`[conflicts] working-tree conflict for ${n.file} has no pinned theirs blob`);let{createGitInstance:r}=await import(`./git-handle-CzN6a5i1.mjs`),i=await r(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,n.theirsSha]);Pq(e,t,{allowShareableOkArtifact:dM}),cc(e,i,`utf-8`);break}case`content`:if(i===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);cc(e,i,`utf-8`);break;case`delete`:U(e)&&Qs(e);break;default:throw Error(`[conflicts] unknown resolve strategy: ${r}`)}}};function Xxe(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 Zxe(e,t){let n=lO(e);try{yu(n,{recursive:!0}),ju(z(n,mte),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Dte(e);yu(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`};ju(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const CZ=new Map;let wZ=!1;function Qxe(e,t){try{let n=Xxe(e,t);for(let e of CZ.keys())Zxe(e,n)}catch{}}function $xe(e){CZ.set(e,(CZ.get(e)??0)+1),wZ||(wZ=!0,process.on(`uncaughtExceptionMonitor`,Qxe));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=CZ.get(e)??0;n<=1?CZ.delete(e):CZ.set(e,n-1)}}}function TZ(e,t){let n=0,r=!1,i=new Set;t&&i.add(t);let a=e=>{for(let t of i)t(e)},o=(e,t)=>{e.url?.startsWith(`/collab`)&&(n++,a(n),t.once(`close`,()=>{n--,n<0&&(n=0),a(n)}))};return e.on(`upgrade`,o),{getCount:()=>n,subscribe:e=>(i.add(e),()=>i.delete(e)),detach:()=>{r||(r=!0,e.off(`upgrade`,o))}}}function EZ(e){let t=e.scheduler??Xa,n=e.warnBeforeMs??3e5,r=null,i=null,a=!1,o=!1;function s(){r!==null&&(t.clearTimeout(r),r=null),i!==null&&(t.clearTimeout(i),i=null)}function c(){s(),!(o||a)&&d.getCount()===0&&(n>0&&n<e.thresholdMs&&(i=t.setTimeout(()=>{i=null,d.getCount()===0&&!a&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),r=t.setTimeout(()=>{if(r=null,!(o||a)&&d.getCount()===0){a=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let l=e=>{e===0?c():s()},u=e.counter===void 0,d=e.counter??TZ(e.httpServer),f=d.subscribe(l);return c(),{detach:()=>{o||(o=!0,f(),u&&d.detach(),s())}}}function DZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function OZ(e){if(!U(e))return{};let t;try{t=(0,pO.parse)(W(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(!DZ(t))return{};let n=t.telemetry;if(!DZ(n))return{};let r=n.localSink;return DZ(r)?r:{}}function kZ(e){return typeof e==`boolean`?e:void 0}function eSe(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function AZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function jZ(e){if(DZ(e))return eSe(e.maxBytes)}function tSe(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=OZ(Rs(`project`,e.projectDir)),n=OZ(Rs(`project-local`,e.projectDir));if((kZ(n.enabled)??kZ(t.enabled)??!0)===!1)return null;let r=jZ(n.spans)??jZ(t.spans)??52428800,i=jZ(n.logs)??jZ(t.logs)??26214400,a=AZ(n.attributeDenylist)??AZ(t.attributeDenylist)??Jee;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var MZ;(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})(MZ||={});var nSe;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(nSe||={});const NZ=MZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),PZ=e=>{switch(typeof e){case`undefined`:return NZ.undefined;case`string`:return NZ.string;case`number`:return Number.isNaN(e)?NZ.nan:NZ.number;case`boolean`:return NZ.boolean;case`function`:return NZ.function;case`bigint`:return NZ.bigint;case`symbol`:return NZ.symbol;case`object`:return Array.isArray(e)?NZ.array:e===null?NZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?NZ.promise:typeof Map<`u`&&e instanceof Map?NZ.map:typeof Set<`u`&&e instanceof Set?NZ.set:typeof Date<`u`&&e instanceof Date?NZ.date:NZ.object;default:return NZ.unknown}},Q=MZ.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 FZ=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,MZ.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()}};FZ.create=e=>new FZ(e);const IZ=(e,t)=>{let n;switch(e.code){case Q.invalid_type:n=e.received===NZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Q.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,MZ.jsonStringifyReplacer)}`;break;case Q.unrecognized_keys:n=`Unrecognized key(s) in object: ${MZ.joinValues(e.keys,`, `)}`;break;case Q.invalid_union:n=`Invalid input`;break;case Q.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${MZ.joinValues(e.options)}`;break;case Q.invalid_enum_value:n=`Invalid enum value. Expected ${MZ.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}"`:MZ.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,MZ.assertNever(e)}return{message:n}};let rSe=IZ;function LZ(){return rSe}const RZ=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 zZ(e,t){let n=LZ(),r=RZ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===IZ?void 0:IZ].filter(e=>!!e)});e.common.issues.push(r)}var BZ=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 VZ;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 VZ;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 VZ=Object.freeze({status:`aborted`}),HZ=e=>({status:`dirty`,value:e}),UZ=e=>({status:`valid`,value:e}),WZ=e=>e.status===`aborted`,GZ=e=>e.status===`dirty`,KZ=e=>e.status===`valid`,qZ=e=>typeof Promise<`u`&&e instanceof Promise;var JZ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(JZ||={});var YZ=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 XZ=(e,t)=>{if(KZ(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 FZ(e.common.issues);return this._error=t,this._error}}};function ZZ(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 QZ=class{get description(){return this._def.description}_getType(e){return PZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:PZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new BZ,ctx:{common:e.parent.common,data:e.data,parsedType:PZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qZ(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:PZ(e)};return XZ(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:PZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return KZ(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=>KZ(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:PZ(e)},r=this._parse({data:e,path:n.path,parent:n});return XZ(n,await(qZ(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 AQ({schema:this,typeName:zQ.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 jQ.create(this,this._def)}nullable(){return MQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mQ.create(this)}promise(){return kQ.create(this,this._def)}or(e){return _Q.create([this,e],this._def)}and(e){return bQ.create(this,e,this._def)}transform(e){return new AQ({...ZZ(this._def),schema:this,typeName:zQ.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new NQ({...ZZ(this._def),innerType:this,defaultValue:t,typeName:zQ.ZodDefault})}brand(){return new IQ({typeName:zQ.ZodBranded,type:this,...ZZ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new PQ({...ZZ(this._def),innerType:this,catchValue:t,typeName:zQ.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return LQ.create(this,e)}readonly(){return RQ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const iSe=/^c[^\s-]{8,}$/i,aSe=/^[0-9a-z]+$/,oSe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sSe=/^[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,cSe=/^[a-z0-9_-]{21}$/i,lSe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uSe=/^[-+]?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)?)??$/,dSe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let $Z;const fSe=/^(?:(?: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])$/,pSe=/^(?:(?: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])$/,mSe=/^(([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]))$/,hSe=/^(([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])$/,gSe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_Se=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,eQ=`((\\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])))`,vSe=RegExp(`^${eQ}$`);function tQ(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 ySe(e){return RegExp(`^${tQ(e)}$`)}function bSe(e){let t=`${eQ}T${tQ(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function xSe(e,t){return!!((t===`v4`||!t)&&fSe.test(e)||(t===`v6`||!t)&&mSe.test(e))}function SSe(e,t){if(!lSe.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 CSe(e,t){return!!((t===`v4`||!t)&&pSe.test(e)||(t===`v6`||!t)&&hSe.test(e))}var nQ=class e extends QZ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==NZ.string){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.string,received:t.parsedType}),VZ}let t=new BZ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),zZ(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),zZ(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?zZ(n,{code:Q.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&zZ(n,{code:Q.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)dSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`email`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)$Z||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),$Z.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`emoji`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)sSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`uuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)cSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`nanoid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)iSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cuid`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)aSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cuid2`,code:Q.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)oSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(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),zZ(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),zZ(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),zZ(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),zZ(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),zZ(n,{code:Q.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?bSe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?vSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?ySe(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{code:Q.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?uSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`duration`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?xSe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`ip`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?SSe(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`jwt`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?CSe(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`cidr`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?gSe.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`base64`,code:Q.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?_Se.test(e.data)||(n=this._getOrReturnCtx(e,n),zZ(n,{validation:`base64url`,code:Q.invalid_string,message:r.message}),t.dirty()):MZ.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,...JZ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...JZ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...JZ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...JZ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...JZ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...JZ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...JZ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...JZ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...JZ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...JZ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...JZ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...JZ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...JZ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...JZ.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,...JZ.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,...JZ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...JZ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...JZ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...JZ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...JZ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...JZ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...JZ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...JZ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...JZ.errToObj(t)})}nonempty(e){return this.min(1,JZ.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}};nQ.create=e=>new nQ({checks:[],typeName:zQ.ZodString,coerce:e?.coerce??!1,...ZZ(e)});function wSe(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 rQ=class e extends QZ{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)!==NZ.number){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.number,received:t.parsedType}),VZ}let t,n=new BZ;for(let r of this._def.checks)r.kind===`int`?MZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),zZ(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),zZ(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),zZ(t,{code:Q.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?wSe(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),zZ(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),zZ(t,{code:Q.not_finite,message:r.message}),n.dirty()):MZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,JZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JZ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:JZ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:JZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:JZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:JZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:JZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JZ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:JZ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:JZ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:JZ.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`&&MZ.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)}};rQ.create=e=>new rQ({checks:[],typeName:zQ.ZodNumber,coerce:e?.coerce||!1,...ZZ(e)});var iQ=class e extends QZ{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)!==NZ.bigint)return this._getInvalidInput(e);let t,n=new BZ;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),zZ(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),zZ(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),zZ(t,{code:Q.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):MZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.bigint,received:t.parsedType}),VZ}gte(e,t){return this.setLimit(`min`,e,!0,JZ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JZ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JZ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JZ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JZ.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:JZ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:JZ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:JZ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:JZ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JZ.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}};iQ.create=e=>new iQ({checks:[],typeName:zQ.ZodBigInt,coerce:e?.coerce??!1,...ZZ(e)});var aQ=class extends QZ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==NZ.boolean){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.boolean,received:t.parsedType}),VZ}return UZ(e.data)}};aQ.create=e=>new aQ({typeName:zQ.ZodBoolean,coerce:e?.coerce||!1,...ZZ(e)});var oQ=class e extends QZ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==NZ.date){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.date,received:t.parsedType}),VZ}if(Number.isNaN(e.data.getTime()))return zZ(this._getOrReturnCtx(e),{code:Q.invalid_date}),VZ;let t=new BZ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),zZ(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),zZ(n,{code:Q.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):MZ.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:JZ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:JZ.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)}};oQ.create=e=>new oQ({checks:[],coerce:e?.coerce||!1,typeName:zQ.ZodDate,...ZZ(e)});var sQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.symbol){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.symbol,received:t.parsedType}),VZ}return UZ(e.data)}};sQ.create=e=>new sQ({typeName:zQ.ZodSymbol,...ZZ(e)});var cQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.undefined){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.undefined,received:t.parsedType}),VZ}return UZ(e.data)}};cQ.create=e=>new cQ({typeName:zQ.ZodUndefined,...ZZ(e)});var lQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.null){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.null,received:t.parsedType}),VZ}return UZ(e.data)}};lQ.create=e=>new lQ({typeName:zQ.ZodNull,...ZZ(e)});var uQ=class extends QZ{constructor(){super(...arguments),this._any=!0}_parse(e){return UZ(e.data)}};uQ.create=e=>new uQ({typeName:zQ.ZodAny,...ZZ(e)});var dQ=class extends QZ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return UZ(e.data)}};dQ.create=e=>new dQ({typeName:zQ.ZodUnknown,...ZZ(e)});var fQ=class extends QZ{_parse(e){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.never,received:t.parsedType}),VZ}};fQ.create=e=>new fQ({typeName:zQ.ZodNever,...ZZ(e)});var pQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.undefined){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.void,received:t.parsedType}),VZ}return UZ(e.data)}};pQ.create=e=>new pQ({typeName:zQ.ZodVoid,...ZZ(e)});var mQ=class e extends QZ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==NZ.array)return zZ(t,{code:Q.invalid_type,expected:NZ.array,received:t.parsedType}),VZ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(zZ(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&&(zZ(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&&(zZ(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 YZ(t,e,t.path,n)))).then(e=>BZ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new YZ(t,e,t.path,n)));return BZ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:JZ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:JZ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:JZ.toString(n)}})}nonempty(e){return this.min(1,e)}};mQ.create=(e,t)=>new mQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:zQ.ZodArray,...ZZ(t)});function hQ(e){if(e instanceof gQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=jQ.create(hQ(r))}return new gQ({...e._def,shape:()=>t})}else if(e instanceof mQ)return new mQ({...e._def,type:hQ(e.element)});else if(e instanceof jQ)return jQ.create(hQ(e.unwrap()));else if(e instanceof MQ)return MQ.create(hQ(e.unwrap()));else if(e instanceof xQ)return xQ.create(e.items.map(e=>hQ(e)));else return e}var gQ=class e extends QZ{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=MZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==NZ.object){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.object,received:t.parsedType}),VZ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof fQ&&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 YZ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof fQ){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&&(zZ(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 YZ(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=>BZ.mergeObjectSync(t,e)):BZ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return JZ.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:JZ.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:zQ.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 MZ.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 MZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return hQ(this)}partial(t){let n={};for(let e of MZ.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 MZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof jQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return EQ(MZ.objectKeys(this.shape))}};gQ.create=(e,t)=>new gQ({shape:()=>e,unknownKeys:`strip`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)}),gQ.strictCreate=(e,t)=>new gQ({shape:()=>e,unknownKeys:`strict`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)}),gQ.lazycreate=(e,t)=>new gQ({shape:e,unknownKeys:`strip`,catchall:fQ.create(),typeName:zQ.ZodObject,...ZZ(t)});var _Q=class extends QZ{_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 FZ(e.ctx.common.issues));return zZ(t,{code:Q.invalid_union,unionErrors:n}),VZ}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 FZ(e));return zZ(t,{code:Q.invalid_union,unionErrors:i}),VZ}}get options(){return this._def.options}};_Q.create=(e,t)=>new _Q({options:e,typeName:zQ.ZodUnion,...ZZ(t)});const vQ=e=>e instanceof wQ?vQ(e.schema):e instanceof AQ?vQ(e.innerType()):e instanceof TQ?[e.value]:e instanceof DQ?e.options:e instanceof OQ?MZ.objectValues(e.enum):e instanceof NQ?vQ(e._def.innerType):e instanceof cQ?[void 0]:e instanceof lQ?[null]:e instanceof jQ?[void 0,...vQ(e.unwrap())]:e instanceof MQ?[null,...vQ(e.unwrap())]:e instanceof IQ||e instanceof RQ?vQ(e.unwrap()):e instanceof PQ?vQ(e._def.innerType):[];var TSe=class e extends QZ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==NZ.object)return zZ(t,{code:Q.invalid_type,expected:NZ.object,received:t.parsedType}),VZ;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}):(zZ(t,{code:Q.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),VZ)}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=vQ(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:zQ.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...ZZ(r)})}};function yQ(e,t){let n=PZ(e),r=PZ(t);if(e===t)return{valid:!0,data:e};if(n===NZ.object&&r===NZ.object){let n=MZ.objectKeys(t),r=MZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=yQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===NZ.array&&r===NZ.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=yQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===NZ.date&&r===NZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var bQ=class extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(WZ(e)||WZ(r))return VZ;let i=yQ(e.value,r.value);return i.valid?((GZ(e)||GZ(r))&&t.dirty(),{status:t.value,value:i.data}):(zZ(n,{code:Q.invalid_intersection_types}),VZ)};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}))}};bQ.create=(e,t,n)=>new bQ({left:e,right:t,typeName:zQ.ZodIntersection,...ZZ(n)});var xQ=class e extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==NZ.array)return zZ(n,{code:Q.invalid_type,expected:NZ.array,received:n.parsedType}),VZ;if(n.data.length<this._def.items.length)return zZ(n,{code:Q.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),VZ;!this._def.rest&&n.data.length>this._def.items.length&&(zZ(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 YZ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>BZ.mergeArray(t,e)):BZ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};xQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new xQ({items:e,typeName:zQ.ZodTuple,rest:null,...ZZ(t)})};var ESe=class e extends QZ{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!==NZ.object)return zZ(n,{code:Q.invalid_type,expected:NZ.object,received:n.parsedType}),VZ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new YZ(n,e,n.path,e)),value:a._parse(new YZ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?BZ.mergeObjectAsync(t,r):BZ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof QZ?new e({keyType:t,valueType:n,typeName:zQ.ZodRecord,...ZZ(r)}):new e({keyType:nQ.create(),valueType:t,typeName:zQ.ZodRecord,...ZZ(n)})}},SQ=class extends QZ{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!==NZ.map)return zZ(n,{code:Q.invalid_type,expected:NZ.map,received:n.parsedType}),VZ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new YZ(n,e,n.path,[a,`key`])),value:i._parse(new YZ(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 VZ;(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 VZ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};SQ.create=(e,t,n)=>new SQ({valueType:t,keyType:e,typeName:zQ.ZodMap,...ZZ(n)});var CQ=class e extends QZ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==NZ.set)return zZ(n,{code:Q.invalid_type,expected:NZ.set,received:n.parsedType}),VZ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(zZ(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&&(zZ(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 VZ;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 YZ(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:JZ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:JZ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};CQ.create=(e,t)=>new CQ({valueType:e,minSize:null,maxSize:null,typeName:zQ.ZodSet,...ZZ(t)});var DSe=class e extends QZ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==NZ.function)return zZ(t,{code:Q.invalid_type,expected:NZ.function,received:t.parsedType}),VZ;function n(e,n){return RZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LZ(),IZ].filter(e=>!!e),issueData:{code:Q.invalid_arguments,argumentsError:n}})}function r(e,n){return RZ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LZ(),IZ].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 kQ){let e=this;return UZ(async function(...t){let o=new FZ([]),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 UZ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new FZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new FZ([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:xQ.create(t).rest(dQ.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||xQ.create([]).rest(dQ.create()),returns:n||dQ.create(),typeName:zQ.ZodFunction,...ZZ(r)})}},wQ=class extends QZ{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})}};wQ.create=(e,t)=>new wQ({getter:e,typeName:zQ.ZodLazy,...ZZ(t)});var TQ=class extends QZ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return zZ(t,{received:t.data,code:Q.invalid_literal,expected:this._def.value}),VZ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};TQ.create=(e,t)=>new TQ({value:e,typeName:zQ.ZodLiteral,...ZZ(t)});function EQ(e,t){return new DQ({values:e,typeName:zQ.ZodEnum,...ZZ(t)})}var DQ=class e extends QZ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return zZ(t,{expected:MZ.joinValues(n),received:t.parsedType,code:Q.invalid_type}),VZ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return zZ(t,{received:t.data,code:Q.invalid_enum_value,options:n}),VZ}return UZ(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})}};DQ.create=EQ;var OQ=class extends QZ{_parse(e){let t=MZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==NZ.string&&n.parsedType!==NZ.number){let e=MZ.objectValues(t);return zZ(n,{expected:MZ.joinValues(e),received:n.parsedType,code:Q.invalid_type}),VZ}if(this._cache||=new Set(MZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=MZ.objectValues(t);return zZ(n,{received:n.data,code:Q.invalid_enum_value,options:e}),VZ}return UZ(e.data)}get enum(){return this._def.values}};OQ.create=(e,t)=>new OQ({values:e,typeName:zQ.ZodNativeEnum,...ZZ(t)});var kQ=class extends QZ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==NZ.promise&&t.common.async===!1?(zZ(t,{code:Q.invalid_type,expected:NZ.promise,received:t.parsedType}),VZ):UZ((t.parsedType===NZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};kQ.create=(e,t)=>new kQ({type:e,typeName:zQ.ZodPromise,...ZZ(t)});var AQ=class extends QZ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===zQ.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=>{zZ(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 VZ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?VZ:r.status===`dirty`||t.value===`dirty`?HZ(r.value):r});{if(t.value===`aborted`)return VZ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?VZ:r.status===`dirty`||t.value===`dirty`?HZ(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`?VZ:(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`?VZ:(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(!KZ(e))return VZ;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=>KZ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):VZ);MZ.assertNever(r)}};AQ.create=(e,t,n)=>new AQ({schema:e,typeName:zQ.ZodEffects,effect:t,...ZZ(n)}),AQ.createWithPreprocess=(e,t,n)=>new AQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:zQ.ZodEffects,...ZZ(n)});var jQ=class extends QZ{_parse(e){return this._getType(e)===NZ.undefined?UZ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};jQ.create=(e,t)=>new jQ({innerType:e,typeName:zQ.ZodOptional,...ZZ(t)});var MQ=class extends QZ{_parse(e){return this._getType(e)===NZ.null?UZ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};MQ.create=(e,t)=>new MQ({innerType:e,typeName:zQ.ZodNullable,...ZZ(t)});var NQ=class extends QZ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===NZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};NQ.create=(e,t)=>new NQ({innerType:e,typeName:zQ.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...ZZ(t)});var PQ=class extends QZ{_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 qZ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new FZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new FZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};PQ.create=(e,t)=>new PQ({innerType:e,typeName:zQ.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...ZZ(t)});var FQ=class extends QZ{_parse(e){if(this._getType(e)!==NZ.nan){let t=this._getOrReturnCtx(e);return zZ(t,{code:Q.invalid_type,expected:NZ.nan,received:t.parsedType}),VZ}return{status:`valid`,value:e.data}}};FQ.create=e=>new FQ({typeName:zQ.ZodNaN,...ZZ(e)});var IQ=class extends QZ{_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}},LQ=class e extends QZ{_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`?VZ:e.status===`dirty`?(t.dirty(),HZ(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`?VZ: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:zQ.ZodPipeline})}},RQ=class extends QZ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(KZ(e)&&(e.value=Object.freeze(e.value)),e);return qZ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};RQ.create=(e,t)=>new RQ({innerType:e,typeName:zQ.ZodReadonly,...ZZ(t)}),gQ.lazycreate;var zQ;(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`})(zQ||={}),nQ.create,rQ.create,FQ.create,iQ.create,aQ.create,oQ.create,sQ.create,cQ.create,lQ.create,uQ.create,dQ.create,fQ.create,pQ.create,mQ.create;const OSe=gQ.create;gQ.strictCreate,_Q.create,TSe.create,bQ.create,xQ.create,ESe.create,SQ.create,CQ.create,DSe.create,wQ.create,TQ.create,DQ.create,OQ.create,kQ.create,AQ.create,jQ.create,MQ.create,AQ.createWithPreprocess,LQ.create;const kSe=hs(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);Gee.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>ote(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>ws(e,t,n),e.parseAsync=async(t,n)=>_te(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Es(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)=>ite(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ASe=hs(`ZodMiniObject`,(e,t)=>{Zee.init(e,t),kSe.init(e,t),dte(e,`shape`,()=>t.shape)});function BQ(e,t){return new ASe({type:`object`,shape:e??{},...hte(t)})}function VQ(e){return!!e._zod}function HQ(e){let t=Object.values(e);if(t.length===0)return BQ({});let n=t.every(VQ),r=t.every(e=>!VQ(e));if(n)return BQ(e);if(r)return OSe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function UQ(e,t){return VQ(e)?ws(e,t):e.safeParse(t)}async function WQ(e,t){return VQ(e)?await Es(e,t):await e.safeParseAsync(t)}function GQ(e){if(!e)return;let t;if(t=VQ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function KQ(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 HQ(e)}}if(VQ(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 qQ(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 jSe(e){return e.description}function MSe(e){if(VQ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function JQ(e){if(VQ(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 YQ=`2025-11-25`,XQ=[YQ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],ZQ=`io.modelcontextprotocol/related-task`,QQ=lte(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),$Q=ds([P(),N().int()]),e$=P();rs({ttl:N().optional(),pollInterval:N().optional()});const NSe=I({ttl:N().optional()}),PSe=I({taskId:P()}),t$=rs({progressToken:$Q.optional(),[ZQ]:PSe.optional()}),n$=I({_meta:t$.optional()}),r$=n$.extend({task:NSe.optional()}),FSe=e=>r$.safeParse(e).success,i$=I({method:P(),params:n$.loose().optional()}),a$=I({_meta:t$.optional()}),o$=I({method:P(),params:a$.loose().optional()}),s$=rs({_meta:t$.optional()}),c$=ds([P(),N().int()]),l$=I({jsonrpc:M(`2.0`),id:c$,...i$.shape}).strict(),u$=e=>l$.safeParse(e).success,d$=I({jsonrpc:M(`2.0`),...o$.shape}).strict(),ISe=e=>d$.safeParse(e).success,f$=I({jsonrpc:M(`2.0`),id:c$,result:s$}).strict(),p$=e=>f$.safeParse(e).success;var m$;(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`})(m$||={});const h$=I({jsonrpc:M(`2.0`),id:c$.optional(),error:I({code:N().int(),message:P(),data:A().optional()})}).strict(),g$=e=>h$.safeParse(e).success,_$=ds([l$,d$,f$,h$]);ds([f$,h$]);const v$=s$.strict(),LSe=a$.extend({requestId:c$.optional(),reason:P().optional()}),y$=o$.extend({method:M(`notifications/cancelled`),params:LSe}),b$=I({icons:F(I({src:P(),mimeType:P().optional(),sizes:F(P()).optional(),theme:$o([`light`,`dark`]).optional()})).optional()}),x$=I({name:P(),title:P().optional()}),S$=x$.extend({...x$.shape,...b$.shape,version:P(),websiteUrl:P().optional(),description:P().optional()}),RSe=ls(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ss(I({form:ss(I({applyDefaults:Yo().optional()}),j(P(),A())).optional(),url:QQ.optional()}),j(P(),A()).optional())),zSe=rs({list:QQ.optional(),cancel:QQ.optional(),requests:rs({sampling:rs({createMessage:QQ.optional()}).optional(),elicitation:rs({create:QQ.optional()}).optional()}).optional()}),BSe=rs({list:QQ.optional(),cancel:QQ.optional(),requests:rs({tools:rs({call:QQ.optional()}).optional()}).optional()}),VSe=I({experimental:j(P(),QQ).optional(),sampling:I({context:QQ.optional(),tools:QQ.optional()}).optional(),elicitation:RSe.optional(),roots:I({listChanged:Yo().optional()}).optional(),tasks:zSe.optional(),extensions:j(P(),QQ).optional()}),HSe=n$.extend({protocolVersion:P(),capabilities:VSe,clientInfo:S$}),C$=i$.extend({method:M(`initialize`),params:HSe}),w$=e=>C$.safeParse(e).success,USe=I({experimental:j(P(),QQ).optional(),logging:QQ.optional(),completions:QQ.optional(),prompts:I({listChanged:Yo().optional()}).optional(),resources:I({subscribe:Yo().optional(),listChanged:Yo().optional()}).optional(),tools:I({listChanged:Yo().optional()}).optional(),tasks:BSe.optional(),extensions:j(P(),QQ).optional()}),WSe=s$.extend({protocolVersion:P(),capabilities:USe,serverInfo:S$,instructions:P().optional()}),T$=o$.extend({method:M(`notifications/initialized`),params:a$.optional()}),GSe=e=>T$.safeParse(e).success,E$=i$.extend({method:M(`ping`),params:n$.optional()}),KSe=I({progress:N(),total:Zo(N()),message:Zo(P())}),qSe=I({...a$.shape,...KSe.shape,progressToken:$Q}),D$=o$.extend({method:M(`notifications/progress`),params:qSe}),JSe=n$.extend({cursor:e$.optional()}),O$=i$.extend({params:JSe.optional()}),k$=s$.extend({nextCursor:e$.optional()}),YSe=$o([`working`,`input_required`,`completed`,`failed`,`cancelled`]),A$=I({taskId:P(),status:YSe,ttl:ds([N(),Qo()]),createdAt:P(),lastUpdatedAt:P(),pollInterval:Zo(N()),statusMessage:Zo(P())}),j$=s$.extend({task:A$}),XSe=a$.merge(A$),M$=o$.extend({method:M(`notifications/tasks/status`),params:XSe}),N$=i$.extend({method:M(`tasks/get`),params:n$.extend({taskId:P()})}),P$=s$.merge(A$),F$=i$.extend({method:M(`tasks/result`),params:n$.extend({taskId:P()})});s$.loose();const I$=O$.extend({method:M(`tasks/list`)}),L$=k$.extend({tasks:F(A$)}),R$=i$.extend({method:M(`tasks/cancel`),params:n$.extend({taskId:P()})}),ZSe=s$.merge(A$),z$=I({uri:P(),mimeType:Zo(P()),_meta:j(P(),A()).optional()}),B$=z$.extend({text:P()}),V$=P().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),H$=z$.extend({blob:V$}),U$=$o([`user`,`assistant`]),W$=I({audience:F(U$).optional(),priority:N().min(0).max(1).optional(),lastModified:ts({offset:!0}).optional()}),G$=I({...x$.shape,...b$.shape,uri:P(),description:Zo(P()),mimeType:Zo(P()),size:Zo(N()),annotations:W$.optional(),_meta:Zo(rs({}))}),QSe=I({...x$.shape,...b$.shape,uriTemplate:P(),description:Zo(P()),mimeType:Zo(P()),annotations:W$.optional(),_meta:Zo(rs({}))}),K$=O$.extend({method:M(`resources/list`)}),$Se=k$.extend({resources:F(G$)}),q$=O$.extend({method:M(`resources/templates/list`)}),eCe=k$.extend({resourceTemplates:F(QSe)}),J$=n$.extend({uri:P()}),tCe=J$,Y$=i$.extend({method:M(`resources/read`),params:tCe}),nCe=s$.extend({contents:F(ds([B$,H$]))}),rCe=o$.extend({method:M(`notifications/resources/list_changed`),params:a$.optional()}),iCe=J$,aCe=i$.extend({method:M(`resources/subscribe`),params:iCe}),oCe=J$,sCe=i$.extend({method:M(`resources/unsubscribe`),params:oCe}),cCe=a$.extend({uri:P()}),lCe=o$.extend({method:M(`notifications/resources/updated`),params:cCe}),uCe=I({name:P(),description:Zo(P()),required:Zo(Yo())}),dCe=I({...x$.shape,...b$.shape,description:Zo(P()),arguments:Zo(F(uCe)),_meta:Zo(rs({}))}),X$=O$.extend({method:M(`prompts/list`)}),fCe=k$.extend({prompts:F(dCe)}),pCe=n$.extend({name:P(),arguments:j(P(),P()).optional()}),Z$=i$.extend({method:M(`prompts/get`),params:pCe}),Q$=I({type:M(`text`),text:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),$$=I({type:M(`image`),data:V$,mimeType:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),e1=I({type:M(`audio`),data:V$,mimeType:P(),annotations:W$.optional(),_meta:j(P(),A()).optional()}),mCe=I({type:M(`tool_use`),name:P(),id:P(),input:j(P(),A()),_meta:j(P(),A()).optional()}),hCe=I({type:M(`resource`),resource:ds([B$,H$]),annotations:W$.optional(),_meta:j(P(),A()).optional()}),t1=ds([Q$,$$,e1,G$.extend({type:M(`resource_link`)}),hCe]),gCe=I({role:U$,content:t1}),_Ce=s$.extend({description:P().optional(),messages:F(gCe)}),vCe=o$.extend({method:M(`notifications/prompts/list_changed`),params:a$.optional()}),yCe=I({title:P().optional(),readOnlyHint:Yo().optional(),destructiveHint:Yo().optional(),idempotentHint:Yo().optional(),openWorldHint:Yo().optional()}),bCe=I({taskSupport:$o([`required`,`optional`,`forbidden`]).optional()}),n1=I({...x$.shape,...b$.shape,description:P().optional(),inputSchema:I({type:M(`object`),properties:j(P(),QQ).optional(),required:F(P()).optional()}).catchall(A()),outputSchema:I({type:M(`object`),properties:j(P(),QQ).optional(),required:F(P()).optional()}).catchall(A()).optional(),annotations:yCe.optional(),execution:bCe.optional(),_meta:j(P(),A()).optional()}),r1=O$.extend({method:M(`tools/list`)}),xCe=k$.extend({tools:F(n1)}),i1=s$.extend({content:F(t1).default([]),structuredContent:j(P(),A()).optional(),isError:Yo().optional()});i1.or(s$.extend({toolResult:A()}));const SCe=r$.extend({name:P(),arguments:j(P(),A()).optional()}),a1=i$.extend({method:M(`tools/call`),params:SCe}),CCe=o$.extend({method:M(`notifications/tools/list_changed`),params:a$.optional()});I({autoRefresh:Yo().default(!0),debounceMs:N().int().nonnegative().default(300)});const o1=$o([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wCe=n$.extend({level:o1}),s1=i$.extend({method:M(`logging/setLevel`),params:wCe}),TCe=a$.extend({level:o1,logger:P().optional(),data:A()}),ECe=o$.extend({method:M(`notifications/message`),params:TCe}),DCe=I({hints:F(I({name:P().optional()})).optional(),costPriority:N().min(0).max(1).optional(),speedPriority:N().min(0).max(1).optional(),intelligencePriority:N().min(0).max(1).optional()}),OCe=I({mode:$o([`auto`,`required`,`none`]).optional()}),kCe=I({type:M(`tool_result`),toolUseId:P().describe(`The unique identifier for the corresponding tool call.`),content:F(t1).default([]),structuredContent:I({}).loose().optional(),isError:Yo().optional(),_meta:j(P(),A()).optional()}),ACe=is(`type`,[Q$,$$,e1]),c1=is(`type`,[Q$,$$,e1,mCe,kCe]),jCe=I({role:U$,content:ds([c1,F(c1)]),_meta:j(P(),A()).optional()}),MCe=r$.extend({messages:F(jCe),modelPreferences:DCe.optional(),systemPrompt:P().optional(),includeContext:$o([`none`,`thisServer`,`allServers`]).optional(),temperature:N().optional(),maxTokens:N().int(),stopSequences:F(P()).optional(),metadata:QQ.optional(),tools:F(n1).optional(),toolChoice:OCe.optional()}),NCe=i$.extend({method:M(`sampling/createMessage`),params:MCe}),l1=s$.extend({model:P(),stopReason:Zo($o([`endTurn`,`stopSequence`,`maxTokens`]).or(P())),role:U$,content:ACe}),u1=s$.extend({model:P(),stopReason:Zo($o([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(P())),role:U$,content:ds([c1,F(c1)])}),PCe=I({type:M(`boolean`),title:P().optional(),description:P().optional(),default:Yo().optional()}),FCe=I({type:M(`string`),title:P().optional(),description:P().optional(),minLength:N().optional(),maxLength:N().optional(),format:$o([`email`,`uri`,`date`,`date-time`]).optional(),default:P().optional()}),ICe=I({type:$o([`number`,`integer`]),title:P().optional(),description:P().optional(),minimum:N().optional(),maximum:N().optional(),default:N().optional()}),LCe=I({type:M(`string`),title:P().optional(),description:P().optional(),enum:F(P()),default:P().optional()}),RCe=I({type:M(`string`),title:P().optional(),description:P().optional(),oneOf:F(I({const:P(),title:P()})),default:P().optional()}),zCe=ds([ds([I({type:M(`string`),title:P().optional(),description:P().optional(),enum:F(P()),enumNames:F(P()).optional(),default:P().optional()}),ds([LCe,RCe]),ds([I({type:M(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:I({type:M(`string`),enum:F(P())}),default:F(P()).optional()}),I({type:M(`array`),title:P().optional(),description:P().optional(),minItems:N().optional(),maxItems:N().optional(),items:I({anyOf:F(I({const:P(),title:P()}))}),default:F(P()).optional()})])]),PCe,FCe,ICe]),BCe=ds([r$.extend({mode:M(`form`).optional(),message:P(),requestedSchema:I({type:M(`object`),properties:j(P(),zCe),required:F(P()).optional()})}),r$.extend({mode:M(`url`),message:P(),elicitationId:P(),url:P().url()})]),VCe=i$.extend({method:M(`elicitation/create`),params:BCe}),HCe=a$.extend({elicitationId:P()}),UCe=o$.extend({method:M(`notifications/elicitation/complete`),params:HCe}),d1=s$.extend({action:$o([`accept`,`decline`,`cancel`]),content:ls(e=>e===null?void 0:e,j(P(),ds([P(),N(),Yo(),F(P())])).optional())}),WCe=I({type:M(`ref/resource`),uri:P()}),GCe=I({type:M(`ref/prompt`),name:P()}),KCe=n$.extend({ref:ds([GCe,WCe]),argument:I({name:P(),value:P()}),context:I({arguments:j(P(),P()).optional()}).optional()}),f1=i$.extend({method:M(`completion/complete`),params:KCe});function qCe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function JCe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const YCe=s$.extend({completion:rs({values:F(P()).max(100),total:Zo(N().int()),hasMore:Zo(Yo())})}),XCe=I({uri:P().startsWith(`file://`),name:P().optional(),_meta:j(P(),A()).optional()}),ZCe=i$.extend({method:M(`roots/list`),params:n$.optional()}),p1=s$.extend({roots:F(XCe)}),QCe=o$.extend({method:M(`notifications/roots/list_changed`),params:a$.optional()});ds([E$,C$,f1,s1,Z$,X$,K$,q$,Y$,aCe,sCe,a1,r1,N$,F$,I$,R$]),ds([y$,D$,T$,QCe,M$]),ds([v$,l1,u1,d1,p1,P$,L$,j$]),ds([E$,NCe,VCe,ZCe,N$,F$,I$,R$]),ds([y$,D$,ECe,lCe,rCe,CCe,vCe,M$,UCe]),ds([v$,WSe,YCe,_Ce,fCe,$Se,eCe,nCe,i1,xCe,P$,L$,j$]);var m1=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===m$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new $Ce(e.elicitations,n)}return new e(t,n,r)}},$Ce=class extends m1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(m$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function h1(e){return e===`completed`||e===`failed`||e===`cancelled`}const ewe=Symbol(`Let zodToJsonSchema decide on which parser to use`),g1={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`},twe=e=>typeof e==`string`?{...g1,name:e}:{...g1,...e},nwe=e=>{let t=twe(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 _1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function v1(e,t,n,r,i){e[t]=n,_1(e,t,r,i)}const y1=(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 b1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?y1(t,e.currentPath):t.join(`/`)}}function rwe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==zQ.ZodAny&&(n.items=N1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&v1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&v1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(v1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),v1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function iwe(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?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function awe(){return{type:`boolean`}}function x1(e,t){return N1(e.type._def,t)}const owe=(e,t)=>N1(e.innerType._def,t);function S1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>S1(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 swe(e,t)}}const swe=(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`:v1(n,`minimum`,r.value,r.message,t);break;case`max`:v1(n,`maximum`,r.value,r.message,t);break}return n};function cwe(e,t){return{...N1(e.innerType._def,t),default:e.defaultValue()}}function lwe(e,t){return t.effectStrategy===`input`?N1(e.schema._def,t):b1(t)}function uwe(e){return{type:`string`,enum:Array.from(e.values)}}const dwe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function fwe(e,t){let n=[N1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),N1(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(dwe(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 pwe(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 C1;const w1={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:()=>(C1===void 0&&(C1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),C1),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 T1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:v1(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`:D1(n,`email`,r.message,t);break;case`format:idn-email`:D1(n,`idn-email`,r.message,t);break;case`pattern:zod`:O1(n,w1.email,r.message,t);break}break;case`url`:D1(n,`uri`,r.message,t);break;case`uuid`:D1(n,`uuid`,r.message,t);break;case`regex`:O1(n,r.regex,r.message,t);break;case`cuid`:O1(n,w1.cuid,r.message,t);break;case`cuid2`:O1(n,w1.cuid2,r.message,t);break;case`startsWith`:O1(n,RegExp(`^${E1(r.value,t)}`),r.message,t);break;case`endsWith`:O1(n,RegExp(`${E1(r.value,t)}$`),r.message,t);break;case`datetime`:D1(n,`date-time`,r.message,t);break;case`date`:D1(n,`date`,r.message,t);break;case`time`:D1(n,`time`,r.message,t);break;case`duration`:D1(n,`duration`,r.message,t);break;case`length`:v1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),v1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:O1(n,RegExp(E1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&D1(n,`ipv4`,r.message,t),r.version!==`v4`&&D1(n,`ipv6`,r.message,t);break;case`base64url`:O1(n,w1.base64url,r.message,t);break;case`jwt`:O1(n,w1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&O1(n,w1.ipv4Cidr,r.message,t),r.version!==`v4`&&O1(n,w1.ipv6Cidr,r.message,t);break;case`emoji`:O1(n,w1.emoji(),r.message,t);break;case`ulid`:O1(n,w1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:D1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:v1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:O1(n,w1.base64,r.message,t);break}break;case`nanoid`:O1(n,w1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function E1(e,t){return t.patternStrategy===`escape`?hwe(e):e}const mwe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function hwe(e){let t=``;for(let n=0;n<e.length;n++)mwe.has(e[n])||(t+=`\\`),t+=e[n];return t}function D1(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}}})):v1(e,`format`,t,n,r)}function O1(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:k1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):v1(e,`pattern`,k1(t,r),n,r)}function k1(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
1194
1194
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1195
1195
  ]))`;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 A1(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===zQ.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:N1(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??b1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:N1(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===zQ.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=T1(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===zQ.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===zQ.ZodBranded&&e.keyType._def.type._def.typeName===zQ.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=x1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function gwe(e,t){return t.mapStrategy===`record`?A1(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[N1(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||b1(t),N1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||b1(t)],minItems:2,maxItems:2}}}function _we(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 vwe(e){return e.target===`openAi`?void 0:{not:b1({...e,currentPath:[...e.currentPath,`not`]})}}function ywe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const j1={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function bwe(e,t){if(t.target===`openApi3`)return M1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in j1&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=j1[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 M1(e,t)}const M1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>N1(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 xwe(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:j1[e.innerType._def.typeName],nullable:!0}:{type:[j1[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=N1(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=N1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Swe(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`,_1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?v1(n,`minimum`,r.value,r.message,t):v1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),v1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?v1(n,`maximum`,r.value,r.message,t):v1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),v1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:v1(n,`multipleOf`,r.value,r.message,t);break}return n}function Cwe(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=Twe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=N1(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=wwe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function wwe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return N1(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 Twe(e){try{return e.isOptional()}catch{return!0}}const Ewe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return N1(e.innerType._def,t);let n=N1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:b1(t)},n]}:b1(t)},Dwe=(e,t)=>{if(t.pipeStrategy===`input`)return N1(e.in._def,t);if(t.pipeStrategy===`output`)return N1(e.out._def,t);let n=N1(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,N1(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Owe(e,t){return N1(e.type._def,t)}function kwe(e,t){let n={type:`array`,uniqueItems:!0,items:N1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&v1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&v1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Awe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>N1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:N1(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>N1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function jwe(e){return{not:b1(e)}}function Mwe(e){return b1(e)}const Nwe=(e,t)=>N1(e.innerType._def,t),Pwe=(e,t,n)=>{switch(t){case zQ.ZodString:return T1(e,n);case zQ.ZodNumber:return Swe(e,n);case zQ.ZodObject:return Cwe(e,n);case zQ.ZodBigInt:return iwe(e,n);case zQ.ZodBoolean:return awe();case zQ.ZodDate:return S1(e,n);case zQ.ZodUndefined:return jwe(n);case zQ.ZodNull:return ywe(n);case zQ.ZodArray:return rwe(e,n);case zQ.ZodUnion:case zQ.ZodDiscriminatedUnion:return bwe(e,n);case zQ.ZodIntersection:return fwe(e,n);case zQ.ZodTuple:return Awe(e,n);case zQ.ZodRecord:return A1(e,n);case zQ.ZodLiteral:return pwe(e,n);case zQ.ZodEnum:return uwe(e);case zQ.ZodNativeEnum:return _we(e);case zQ.ZodNullable:return xwe(e,n);case zQ.ZodOptional:return Ewe(e,n);case zQ.ZodMap:return gwe(e,n);case zQ.ZodSet:return kwe(e,n);case zQ.ZodLazy:return()=>e.getter()._def;case zQ.ZodPromise:return Owe(e,n);case zQ.ZodNaN:case zQ.ZodNever:return vwe(n);case zQ.ZodEffects:return lwe(e,n);case zQ.ZodAny:return b1(n);case zQ.ZodUnknown:return Mwe(n);case zQ.ZodDefault:return cwe(e,n);case zQ.ZodBranded:return x1(e,n);case zQ.ZodReadonly:return Nwe(e,n);case zQ.ZodCatch:return owe(e,n);case zQ.ZodPipeline:return Dwe(e,n);case zQ.ZodFunction:case zQ.ZodVoid:case zQ.ZodSymbol:return;default:return(e=>void 0)(t)}};function N1(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==ewe)return i}if(r&&!n){let e=Fwe(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=Pwe(e,e.typeName,t),o=typeof a==`function`?N1(a(),t):a;if(o&&Iwe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Fwe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:y1(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`),b1(t)):t.$refStrategy===`seen`?b1(t):void 0}},Iwe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),Lwe=(e,t)=>{let n=nwe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:N1(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??b1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=N1(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??b1(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Rwe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function P1(e,t){return VQ(e)?nte(e,{target:Rwe(t?.target),io:t?.pipeStrategy??`input`}):Lwe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function F1(e){let t=GQ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=JQ(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function I1(e,t){let n=UQ(e,t);if(!n.success)throw n.error;return n.data}var zwe=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(y$,e=>{this._oncancel(e)}),this.setNotificationHandler(D$,e=>{this._onprogress(e)}),this.setRequestHandler(E$,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(N$,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new m1(m$.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(F$,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 m1(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 m1(m$.InvalidParams,`Task not found: ${r}`);if(!h1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(h1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[ZQ]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(I$,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 m1(m$.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(R$,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new m1(m$.InvalidParams,`Task not found: ${e.params.taskId}`);if(h1(n.status))throw new m1(m$.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 m1(m$.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof m1?e:new m1(m$.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),m1.fromError(m$.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),p$(e)||g$(e)?this._onresponse(e):u$(e)?this._onrequest(e,t):ISe(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=m1.fromError(m$.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?.[ZQ]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:m$.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=FSe(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 m1(m$.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:m$.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),p$(e)?n(e):n(new m1(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(p$(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),p$(e)?r(e):r(m1.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 m1?e:new m1(m$.InternalError,String(e))}}return}let i;try{let r=await this.request(e,j$,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new m1(m$.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},h1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new m1(m$.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new m1(m$.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 m1?e:new m1(m$.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||{},[ZQ]: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 m1?e:new m1(m$.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=UQ(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(m1.fromError(m$.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},P$,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},L$,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},ZSe,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||{},[ZQ]: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||{},[ZQ]: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||{},[ZQ]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=F1(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=I1(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=F1(e);this._notificationHandlers.set(n,n=>{let r=I1(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`&&u$(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new m1(m$.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 m1(m$.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new m1(m$.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 m1(m$.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=M$.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),h1(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 m1(m$.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(h1(a.status))throw new m1(m$.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=M$.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),h1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function L1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bwe(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];L1(a)&&L1(i)?n[r]={...a,...i}:n[r]=i}return n}var Vwe=t(Oo(),1),Hwe=t(te(),1);function Uwe(){let e=new Vwe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Hwe.default)(e),e}var Wwe=class{constructor(e){this._ajv=e??Uwe()}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)}}},Gwe=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},l1,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},d1,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 Kwe(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 qwe(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 Jwe=class extends zwe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(o1.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 Wwe,this.setRequestHandler(C$,e=>this._oninitialize(e)),this.setNotificationHandler(T$,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(s1,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=o1.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Gwe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Bwe(this._capabilities,e)}setRequestHandler(e,t){let n=GQ(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(VQ(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=UQ(a1,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new m1(m$.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=UQ(j$,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new m1(m$.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=UQ(i1,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new m1(m$.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){qwe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&Kwe(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:XQ.includes(t)?t:YQ,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`},v$)}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},u1,t):this.request({method:`sampling/createMessage`,params:e},l1,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},d1,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},d1,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new m1(m$.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof m1?e:new m1(m$.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},p1,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 R1=Symbol.for(`mcp.completable`);function z1(e){return!!e&&typeof e==`object`&&R1 in e}function Ywe(e){return e[R1]?.complete}var Xwe;(function(e){e.Completable=`McpCompletable`})(Xwe||={});const Zwe=/^[A-Za-z0-9._-]{1,128}$/;function Qwe(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`),!Zwe.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 $we(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 B1(e){let t=Qwe(e);return $we(e,t.warnings),t.isValid}var eTe=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)}},V1=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 Jwe(e,t)}get experimental(){return this._experimental||={tasks:new eTe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(K1(r1)),this.server.assertCanSetRequestHandler(K1(a1)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(r1,()=>({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=KQ(t.inputSchema);return e?P1(e,{strictUnions:!0,pipeStrategy:`input`}):tTe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=KQ(t.outputSchema);e&&(n.outputSchema=P1(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(a1,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new m1(m$.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new m1(m$.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 m1(m$.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new m1(m$.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 m1&&e.code===m$.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 WQ(KQ(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=qQ(`error`in r?r.error:`Unknown error`);throw new m1(m$.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 m1(m$.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await WQ(KQ(e.outputSchema),t.structuredContent);if(!r.success){let e=qQ(`error`in r?r.error:`Unknown error`);throw new m1(m$.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 m1(m$.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(K1(f1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(f1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return qCe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return JCe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new m1(m$.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new m1(m$.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new m1(m$.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return J1;let r=GQ(n.argsSchema)?.[e.params.argument.name];if(!z1(r))return J1;let i=Ywe(r);return i?q1(await i(e.params.argument.value,e.params.context)):J1}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 J1;throw new m1(m$.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?q1(await r(e.params.argument.value,e.params.context)):J1}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(K1(K$)),this.server.assertCanSetRequestHandler(K1(q$)),this.server.assertCanSetRequestHandler(K1(Y$)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(K$,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(q$,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(Y$,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new m1(m$.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 m1(m$.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(K1(X$)),this.server.assertCanSetRequestHandler(K1(Z$)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(X$,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?nTe(t.argsSchema):void 0}))})),this.server.setRequestHandler(Z$,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new m1(m$.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new m1(m$.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await WQ(KQ(n.argsSchema),e.params.arguments);if(!r.success){let t=qQ(`error`in r?r.error:`Unknown error`);throw new m1(m$.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:HQ(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=HQ(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=>z1(e instanceof ete?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){B1(e);let l={title:t,description:n,inputSchema:G1(r),outputSchema:G1(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`&&B1(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=HQ(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=HQ(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(W1(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!W1(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 tTe={type:`object`,properties:{}};function H1(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function U1(e){return`_def`in e||`_zod`in e||H1(e)}function W1(e){return typeof e!=`object`||!e||U1(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(H1)}function G1(e){if(e){if(W1(e))return HQ(e);if(!U1(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function nTe(e){let t=GQ(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:jSe(t),required:!MSe(t)})):[]}function K1(e){let t=GQ(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=JQ(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function q1(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const J1={completion:{values:[],hasMore:!1}};var Y1=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},rTe=e=>e instanceof Y1?e:new Y1(e.message,{cause:e}),iTe=global.Request,X1=class extends iTe{constructor(e,t){typeof e==`object`&&Q1 in e&&(e=e[Q1]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},aTe=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)},Z1=Symbol(`wrapBodyStream`),oTe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new X1(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[Z1]){let e;a.body=new ReadableStream({async pull(t){try{e||=Yu.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=Yu.toWeb(r);return new X1(t,a)},Q1=Symbol(`getRequestCache`),$1=Symbol(`requestCache`),e0=Symbol(`incomingKey`),t0=Symbol(`urlKey`),sTe=Symbol(`headersKey`),n0=Symbol(`abortControllerKey`),r0={get method(){return this[e0].method||`GET`},get url(){return this[t0]},get headers(){return this[sTe]||=aTe(this[e0])},[Symbol(`getAbortController`)](){return this[Q1](),this[n0]},[Q1](){return this[n0]||=new AbortController,this[$1]||=oTe(this.method,this[t0],this.headers,this[e0],this[n0])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(r0,e,{get(){return this[Q1]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(r0,e,{value:function(){return this[Q1]()[e]()}})}),Object.defineProperty(r0,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[$1]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(r0,X1.prototype);var cTe=(e,t)=>{let n=Object.create(r0);n[e0]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof nd)throw new Y1(`Absolute URL for :path is not allowed in HTTP/2`);try{n[t0]=new URL(r).href}catch(e){throw new Y1(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof nd?e.authority:e.headers.host)||t;if(!i)throw new Y1(`Missing host header`);let a;if(e instanceof nd){if(a=e.scheme,!(a===`http`||a===`https`))throw new Y1(`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 Y1(`Invalid host header`);return n[t0]=o.href,n},i0=Symbol(`responseCache`),a0=Symbol(`getResponseCache`),o0=Symbol(`cache`),s0=global.Response,c0=class e{#e;#t;[a0](){return delete this[o0],this[i0]||=new s0(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[i0];if(e){this.#t=e,this[a0]();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[o0]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[o0];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[a0]().headers}get status(){return this[o0]?.[0]??this[a0]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(c0.prototype,e,{get(){return this[a0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(c0.prototype,e,{value:function(){return this[a0]()[e]()}})}),Object.defineProperty(c0.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[i0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(c0,s0),Object.setPrototypeOf(c0.prototype,s0.prototype);async function lTe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function l0(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 uTe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:l0(e.getReader(),t)}var u0=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},dTe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=one);var d0=Symbol(`outgoingEnded`),f0=Symbol(`incomingDraining`),fTe=500,pTe=64*1024*1024,p0=e=>{let t=e;if(e.destroyed||t[f0])return;if(t[f0]=!0,e instanceof nd){try{e.stream?.close?.(Cne.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,fTe);a.unref?.();let o=e=>{n+=e.length,n>pTe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},mTe=()=>new Response(null,{status:400}),m0=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),h0=(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))},g0=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},_0=async(e,t)=>{let[n,r,i]=e[o0],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=u0(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=u0(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())):(g0(t),await uTe(r,t)?.catch(e=>h0(e,t))),t[d0]?.()},hTe=e=>typeof e.then==`function`,gTe=async(e,t,n={})=>{if(hTe(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(m0);if(o0 in e)return _0(e,t);let r=u0(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 lTe(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&&g0(t),await l0(n,t,o))}else r[dTe]||(t.writeHead(e.status,r),t.end());t[d0]?.()},v0=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==X1&&(Object.defineProperty(global,`Request`,{value:X1}),Object.defineProperty(global,`Response`,{value:c0})),async(r,i)=>{let a,o;try{o=cTe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[Z1]=!0,r.on(`end`,()=>{s=!0}),r instanceof nd&&(i[d0]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{p0(r)})})}),i.on(`finish`,()=>{s||p0(r)})),i.on(`close`,()=>{o[n0]&&(r.errored?o[n0].abort(r.errored.toString()):i.writableFinished||o[n0].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{p0(r)})})}),a=e(o,{incoming:r,outgoing:i}),o0 in a)return _0(a,i)}catch(e){if(a)return h0(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:rTe(e)),!a)return}else a=o?m0(e):mTe()}try{return await gTe(a,i,t)}catch(e){return h0(e,i)}}},_Te=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
1196
1196
  `;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=>_$.parse(e)):[_$.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(w$);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(u$)){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=>w$(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)u$(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)u$(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;u$(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&&!XQ.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${XQ.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${XQ.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((p$(e)||g$(e))&&(n=e.id),n===void 0){if(p$(e)||g$(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(p$(e)||g$(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)}}}},vTe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new _Te(e),this._requestListener=v0(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 v0(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const y0=`https://json-schema.org/draft/2020-12/schema`,b0=`tools/list`;function x0(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(b0);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${b0} handler found. Either the SDK internals changed, or this ran before tools were registered. Tool schemas will keep the SDK's draft-07 dialect.`);return}e.server.setRequestHandler(r1,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=y0),e.outputSchema&&(e.outputSchema.$schema=y0);return r}),t.__jsonSchemaDialectInstalled=!0}function S0(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||!yTe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=cte(i.error);throw new m1(m$.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function yTe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const C0=2e3,w0=2e3,bTe=[/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 T0(e){return bTe.some(t=>t.test(e))}function xTe(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 ou(e)?e:null}catch{return null}}function STe(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&&ou(a)?a:null}function CTe(e){let t=[];for(let n of e.split(`
@@ -2039,7 +2039,7 @@ native-divergence-injected
2039
2039
  `)),`${n}${o}`}function SIe(e,t){let{bom:n,body:r}=R7(e),i=[],a=QM(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(xIe(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=$M(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=eN(s);if(!I7(c))return{kind:`declined`,reason:`foreign-entry`};let l=He(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:$M(a,[...o,e])})).filter(e=>e.node!==void 0).sort((e,t)=>t.node.offset-e.node.offset);for(let{key:e,node:n}of d){let r=JSON.stringify(B7(t,e));u=`${u.slice(0,n.offset)}${r}${u.slice(n.offset+n.length)}`}return{kind:`managed`,raw:e,shell:`${n}${u}`,entry:c,descriptor:l.descriptor}}function B7(e,t){return e.topLevelKey===`mcp`&&t===`type`?`__ok_managed_type__`:t===`command`&&e.topLevelKey===`mcp`?[`__ok_managed_command__`]:t===`command`?`__ok_managed_command__`:[`__ok_managed_args__`]}function CIe(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=R7(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=I7(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!I7(s))return{kind:`declined`,reason:`foreign-entry`};let c=He(s);if(c.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let l;try{l=n.upsertEntry(i,`open-knowledge`,Object.fromEntries(t.managedKeys.map(e=>[e,B7(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=z7(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function V7(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?SIe(e,t):CIe(e,t,n)}function wIe(e,t,n){let{bom:r,body:i}=R7(e),a=i;for(let e of t.managedKeys){let r=QM(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?$M(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(eN(o))===JSON.stringify(n[e])||(a=nN(a,tN(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:bIe(i)})))}return`${r}${a}`}function H7(e,t,n,r){if(t.format===`json`)return wIe(e,t,n);if(!r)return null;let{body:i}=R7(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return z7(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function TIe(e){let t=L7(e.target);return t?H7(e.raw,t,e.entry,e.tomlEditor):null}function U7(e){let t=L7(e.target);if(!t)return null;let n=V7(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function EIe(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function W7(e){let t=L7(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:V7(e.layers.base,t,e.tomlEditor),head:V7(e.layers.head,t,e.tomlEditor),index:V7(e.layers.index,t,e.tomlEditor),worktree:V7(e.layers.worktree,t,e.tomlEditor),incoming:V7(e.layers.incoming,t,e.tomlEditor)},r=Object.values(n),i=r.find(e=>e.kind===`declined`);if(i?.kind===`declined`)return i;if(r.some(e=>e.kind===`absent`))return r.every(e=>e.kind===`absent`)?{kind:`unchanged`}:{kind:`declined`,reason:`file-deletion-ambiguity`};if(r.some(e=>e.kind===`no-entry`))return r.every(e=>e.kind===`no-entry`)?{kind:`declined`,reason:`no-entry`}:{kind:`declined`,reason:`entry-deletion-ambiguity`};let a=n;if(a.index.shell!==a.worktree.shell)return{kind:`declined`,reason:`index-worktree-divergence`};let o=EIe(a.base,a.worktree,a.incoming);if(o===null)return{kind:`declined`,reason:`unowned-shell-conflict`};let s=Object.values(a).map(e=>({entry:e.entry,descriptor:e.descriptor}));if(e.runningEntry){let t=He(e.runningEntry);t.kind===`recognized`&&s.push({entry:e.runningEntry,descriptor:t.descriptor})}if(new Set(s.map(e=>e.descriptor.family)).size!==1)return{kind:`declined`,reason:`mixed-launcher-family`};let c=s.reduce((e,t)=>t.descriptor.revision>e.descriptor.revision?t:e),l=[a.worktree,a.index,a.head,a.incoming,a.base].find(e=>e.shell===o);if(!l)return{kind:`declined`,reason:`unowned-shell-conflict`};let u=H7(l.raw,t,c.entry,e.tomlEditor);return u===null?{kind:`declined`,reason:e.tomlEditor?`unparseable`:`no-native-writer`}:{kind:`resolved`,raw:u,winner:c.descriptor,winnerEntry:c.entry}}const DIe=L(`github-account`),OIe=(e,t)=>{let n=tu(`git`,[`config`,`--get-urlmatch`,`credential`,e],uw({cwd:t,encoding:`utf-8`,timeout:5e3}));return n.error||n.status===null||n.status!==0&&n.status!==1?(DIe.warn({status:n.status,signal:n.signal,err:n.error,stderr:typeof n.stderr==`string`?CP(n.stderr).slice(0,200):void 0},`[github-account] git config --get-urlmatch failed — treating the URL as declaring no account`),null):n.status!==0||!n.stdout?null:n.stdout};function kIe(e){return e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/]*@/i,`$1`)}function AIe(e){let t;for(let n of e.split(`
2040
2040
  `)){let e=n.startsWith(`credential.username `)?n.slice(20).trim():void 0;e&&(t=e)}return t}function G7(e,t={}){let n=lP(e);if(!n)return{source:`active`};let r=n.host;if(n.login)return{host:r,login:n.login,source:`remote-url`};if(n.transport!==`https`)return{host:r,source:`active`};let i=(t._readCredentialUrlMatch??OIe)(kIe(e),t.cwd??process.cwd()),a=i?oP(AIe(i)):void 0;return a?{host:r,login:a,source:`credential-config`}:{host:r,source:`active`}}function jIe(e={}){let t=e.ttlMs??6e4,n=e.now??Date.now,r;return{resolve(i){let a=Mme(i);if(!a)return{source:`active`};let o=n();if(r&&r.projectDir===i&&r.url===a&&r.expiresAt>o)return r.account;let s=G7(a,{cwd:i,_readCredentialUrlMatch:e._readCredentialUrlMatch});return r={projectDir:i,url:a,account:s,expiresAt:o+t},s},invalidate(){r=void 0}}}function K7(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 MIe(e,t){return t===`anonymous`?Math.max(180,e):e}const $=L(`sync-engine`),q7=new Set(yIe),J7=/^[0-9a-f]{40}$/i,NIe=ed($l);var Y7=class extends Error{constructor(e,t){super(`Shareable .ok subtree "${e}" could not be fully enumerated; sync staging aborted`,{cause:t}),this.name=`ShareableOkEnumerationError`}};function PIe(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 FIe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason,...e.resolvedLogin===void 0?{}:{resolvedLogin:e.resolvedLogin},...e.declaredLogin===void 0?{}:{declaredLogin:e.declaredLogin},...e.declaredSource===void 0?{}:{declaredSource:e.declaredSource}}:{checkStatus:`unknown`,unknownError:e.error}}function X7(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason&&e.resolvedLogin===t.resolvedLogin&&e.declaredLogin===t.declaredLogin&&e.declaredSource===t.declaredSource:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const Z7={syncScope:{pathBase:`content`}},Q7={syncScope:{pathBase:`project`}},$7=new Set([`diverged-local-commits`,`external-changes-pending`]);function e9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function t9(e){let t=id(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 IIe(e){return e.class===`network`&&e.subclass!==`429`&&e.subclass!==`5xx`}function n9(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const r9=12e4;var LIe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;mcpTomlEditor;detectGh;detectGhAccounts;ghTokenSource;ghAccountResolver;declaredAccountWarnKey;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;get lastRunUtc(){return this.lastPullOkUtc===null?this.lastPushOkUtc:this.lastPushOkUtc===null||this.lastPullOkUtc>this.lastPushOkUtc?this.lastPullOkUtc:this.lastPushOkUtc}lastPullOkUtc=null;lastPushOkUtc=null;pushCycleLanded=!1;fetchOnlyInFlight=!1;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutivePullFailures=0;consecutivePushFailures=0;pushStreakIsConnectivity=!1;consecutiveContentions=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;blockingPaths=[];currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=Uk(B(this.contentDir,z(this.projectDir,`.ok`))).startsWith(`..`),this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialConfig=e.credentialConfig??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.mcpTomlEditor=e.mcpTomlEditor,this.detectGh=e.detectGh,this.detectGhAccounts=e.detectGhAccounts,this.ghTokenSource=oIe(e.detectGh),this.ghAccountResolver=jIe({_readCredentialUrlMatch:e._readCredentialUrlMatch}),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??mIe,this.statePath=V(lO(this.projectDir),`sync-state.json`),this.conflictStore=new SZ(this.projectDir,this.currentBranch)}syncGhTarget(){let e=this.ghAccountResolver.resolve(this.projectDir);return{account:e,host:e.host??`github.com`}}resolveRelayGhToken(){let{account:e,host:t}=this.syncGhTarget(),n=this.ghTokenSource.get(t,e.login);return this.noteDeclaredAccountOutcome(e,t,n),n}noteDeclaredAccountOutcome(e,t,n){let r=e.login,i=n===null?void 0:n.login??this.activeGhLogin(t);if(!(r!==void 0&&(n===null||!aP(i,r)))){this.declaredAccountWarnKey=void 0;return}let a=`${t}\0${r}\0${e.source}\0${n===null?`none`:`fallback`}`;a!==this.declaredAccountWarnKey&&(n===null?$.warn({host:t,declaredLogin:r,declaredSource:e.source},`[sync] declared GitHub account produced no gh token — git runs with no relayed credential`):$.warn({host:t,declaredLogin:r,declaredSource:e.source,resolvedLogin:i},`[sync] declared GitHub account did not produce the gh token — using the active account`)),this.declaredAccountWarnKey=a}parkedOnAmbiguousNotFound(){return(this.state===`auth-error`||this.pausedReason===`auth-error`)&&(this.pushErrorCode===`auth-not-found-as-identity`||this.pullErrorCode===`auth-not-found-as-identity`)}activeGhLogin(e){if(this.detectGhAccounts)try{return this.detectGhAccounts(e)?.find(e=>e.active)?.login}catch(t){$.warn({err:t,host:e},`[sync] detectGhAccounts failed — fallback identity stays unnamed`);return}}gitHandle(e){return vc(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.resolveRelayGhToken()??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){$.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),$.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){$.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=fd(this.projectDir),n=t?z(t,`MERGE_HEAD`):null,r=n!==null&&U(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){$.warn({count:i().length},`[sync] persisted merge conflicts but no MERGE_HEAD — clearing stale state`);for(let e of i())this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count()}else if(i().length>0&&r)try{let e=this.gitHandle(),t=new Set(await Ab(e.git,[`diff`,`--name-only`,`--diff-filter=U`])),n=this.conflictCount;for(let e of i())t.has(e.file)||this.conflictStore.removeConflict(e.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<n&&$.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){$.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){$.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort for stale MERGE_HEAD failed`)}}if(i().length>0){await this.notifyContentConflictsDetected(this.conflictStore.list().map(e=>e.file)),this.transitionTo(`conflict`),$.warn({count:this.conflictCount},`[sync] restarted with active conflicts — sync paused`);return}let a=this.conflictStore.list().filter(e=>e.variant===`working-tree`);a.length>0&&await this.notifyContentConflictsDetected(a.map(e=>e.file)),this.mode===`follow`&&await this.refreshAuthTier();let o=K7(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=K7(this.lastPushOkUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),$.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}setIntervals(e,t){let n=this.pullIntervalSeconds!==e,r=this.pushIntervalSeconds!==t;!n&&!r||($.info({pullFrom:this.pullIntervalSeconds,pullTo:e,pushFrom:this.pushIntervalSeconds,pushTo:t},`[sync] cycle intervals changed`),this.pullIntervalSeconds=e,this.pushIntervalSeconds=t,n&&this.pullTimer!==null&&this.schedulePull(),r&&this.pushTimer!==null&&this.schedulePush())}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,$.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}async setEnabled(e){await this.setMode(e?`full`:`off`)}cancelScheduledCycles(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null)}async drainInFlightCycles(){let e=Date.now();for(;this.pullInFlight||this.pushInFlight;){if(Date.now()-e>3e4){$.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await $u(50)}}async probeUnpushedCommitCount(){return!this.hasRemote||t9(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||t9(this.projectDir))return;let e=this.gitHandle(),t;try{t=await this.unpushedCommitCount(e)}catch(e){$.warn({err:e},`[sync] pull-only: could not probe stranded commits — skipping conversion`);return}if(t!==0){try{await this.checkpointBeforeStrandedConversion?.({branch:this.currentBranch,ahead:t})}catch(e){$.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await _c(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,$.info({ahead:t,behind:this.behind},`[sync] pull-only: folded stranded local commits into a working-tree overlay`)}catch(e){this.pausedReason=`diverged-local-commits`,$.warn({err:e},`[sync] pull-only: stranded-commit conversion failed — leaving branch as-is`)}}}async notifyCredentialsChanged(){if(this.mode!==`off`&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),!(this.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(0),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(e===`fetch`){await this.fetchOnly();return}if(this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.consecutiveContentions=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.parkedOnAmbiguousNotFound()&&(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}if(e===`push`){await this.pushOnce();return}this.state===`dormant`||this.state===`conflict`||this.state===`auth-error`?$.warn({op:e,state:this.state,mode:this.mode,hasRemote:this.hasRemote,pausedReason:this.pausedReason,conflictCount:this.conflictCount},`[sync] trigger(${e}) ignored — state=${this.state}`):$.info({op:e,state:this.state},`[sync] trigger(${e}) running`),await this.pushOnce(),await this.pullOnce(`sync`)}async pushOnce(){if(this.mode===`full`){await this.runPushCycle();return}await this.runOneShotPush()}async runOneShotPush(){if(this.pushInFlight||this.pullInFlight){$.info({pushInFlight:this.pushInFlight,pullInFlight:this.pullInFlight},`[sync] one-shot push refused — a cycle is already in flight`);return}if(this.state===`conflict`||this.state===`auth-error`){$.info({state:this.state},`[sync] one-shot push refused — state=${this.state}`);return}if(this.conflictCount>0){$.info({conflictCount:this.conflictCount},`[sync] one-shot push refused — unresolved conflicts hold the tree`);return}if(!this.hasRemote||t9(this.projectDir)){$.info({hasRemote:this.hasRemote},`[sync] one-shot push refused — no remote, or no commits yet`);return}let e=this.state;this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun();let t=this.currentState();t!==`conflict`&&t!==`auth-error`&&this.transitionTo(e),this.cc1Broadcaster?.signal(`sync-status`)}}async fetchOnly(){if(!this.hasRemote||t9(this.projectDir)||this.pullInFlight||this.pushInFlight||this.fetchOnlyInFlight)return!1;this.fetchOnlyInFlight=!0;let e=this.gitHandle();try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.scheduleSaveState()}catch(e){return $.debug({err:e},`[sync] panel-open fetch failed — counts left as they were`),!1}finally{this.fetchOnlyInFlight=!1}return await this.refreshDivergenceCounts(e),this.cc1Broadcaster?.signal(`sync-status`),!0}async refreshDivergenceCounts(e){try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch(e){$.debug({err:e},`[sync] divergence-count refresh failed — keeping previous counts`)}}async pullOnce(e=`explicit`){let t=this.mode,n=await this.runOneShotPull(e);return $.info({mode:t,outcome:n},`[sync] one-shot pull complete`),n}async runOneShotPull(e){if(this.pullInFlight||this.pushInFlight)return $.info({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] one-shot pull refused — a cycle is already in flight`),this.recordPullOutcome(`refused`);if(this.state===`conflict`)return $.info({state:this.state},`[sync] one-shot pull refused — the conflict resolver holds the tree`),this.recordPullOutcome(`refused`);if(!this.hasRemote||t9(this.projectDir))return $.info({hasRemote:this.hasRemote},`[sync] one-shot pull refused — no remote, or no commits yet`),this.recordPullOutcome(`refused`);let t=this.mode,n=this.state,r=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle(e))}finally{this.pullInFlight=!1,t===`off`?($7.has(this.pausedReason)||$7.has(r)||(this.pausedReason=r),this.transitionTo(n)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,(e===`succeeded`||e===`up-to-date`||e===`conflict`)&&(this.lastPullOkUtc=new Date().toISOString()),this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastRunUtc:this.lastRunUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?Nme(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.blockingPathsForStatus().length>0?{blockingPaths:this.blockingPathsForStatus()}:{},...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}blockingPathsForStatus(){return this.pausedReason===`external-changes-pending`?this.blockingPaths.slice(0,50):[]}getBlockingPaths(){return this.pausedReason===`external-changes-pending`?[...this.blockingPaths]:[]}async commitBlockingPaths(){let e=this.getBlockingPaths();if(e.length===0)return null;let t=this.gitHandle();return _c(async()=>{await this.applyCommitIdentity(t);try{if(await t.git.raw([`add`,`--`,...e]),(await Ab(t.git,[`diff`,`--cached`,`--name-only`,`--`,...e])).length===0)return null;await t.git.raw([`commit`,`-m`,`Commit local changes before syncing`,`--`,...e])}catch(n){throw await t.git.raw([`reset`,`--`,...e]).catch(()=>{}),$.error({err:n,files:e.length},`[sync] commit of blocking paths failed`),n}let n=(await t.git.revparse(`HEAD`)).trim();return this.clearBlockingPause(),$.info({files:e.length},`[sync] committed overlapping paths at user request`),n})}clearBlockingPause(){this.blockingPaths=[],this.pausedReason=void 0,this.clearPullError(),this.consecutivePullFailures=0,this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await DL(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await DL(this.projectDir),n=t===null;this.identityUnresolved!==n&&(this.identityUnresolved=n,this.cc1Broadcaster?.signal(`sync-status`));let r=t?.name??`OpenKnowledge`,i=t?.email??`sync@open-knowledge.local`;xc(e,{GIT_AUTHOR_NAME:r,GIT_AUTHOR_EMAIL:i,GIT_COMMITTER_NAME:r,GIT_COMMITTER_EMAIL:i})}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=dP(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,X7(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,$.info({caller:e,host:t.host,hasDetectGh:this.detectGh!==void 0,hasTokenStore:this.tokenStore!==void 0&&this.tokenStore!==null},`[sync] push-permission probe dispatching`);let{account:n}=this.syncGhTarget(),r;try{r=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,account:n,detectGh:this.detectGh,detectGhAccounts:this.detectGhAccounts,tokenStore:this.tokenStore})}catch(t){$.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),r={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let i=FIe(r),a=this.pushPermission;this.pushPermission=i;let o=!1;return i.checkStatus===`denied`&&this.mode===`full`&&this.parkedOnAmbiguousNotFound()&&$.info({reason:i.deniedReason,caller:e},`[sync] probe denial not applied — repository-not-found park is the more specific diagnosis`),i.checkStatus===`denied`&&this.mode===`full`&&!this.parkedOnAmbiguousNotFound()?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),o=!0,$.info({reason:i.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):i.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),o=!0,$.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!o&&!X7(a,i)&&this.cc1Broadcaster?.signal(`sync-status`),i}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,$.info({mode:this.mode},`[sync] remote detected post-boot — re-evaluating state`),this.mode===`off`?this.transitionTo(`disabled`):(this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush()))}async probeRemote(){if(!U(z(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return $.warn({err:e},`[sync] remote detection failed`),!1}}getConflicts(){return this.conflictStore.list()}async reconcileConflictsFromGit(){let e=this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(e.length===0)return;let t=this.conflictCount,n=fd(this.projectDir),r=n?z(n,`MERGE_HEAD`):null;if(r!==null&&U(r))try{let n=this.gitHandle(),r=new Set(await Ab(n.git,[`diff`,`--name-only`,`--diff-filter=U`]));for(let t of e)r.has(t.file)||this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count(),this.conflictCount<t&&$.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){$.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{$.info({cleared:e.length},`[sync] external resolve detected (no MERGE_HEAD) — clearing merge-native conflicts`);for(let t of e)this.conflictStore.removeConflict(t.file);this.conflictCount=this.conflictStore.count()}this.conflictCount!==t&&(this.conflictCount===0?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(0)):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&$.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e]),this.conflictCount=this.conflictStore.count(),this.conflictCount===0?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush(0)):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(0)))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{$.error({err:e},`[sync] pull cycle uncaught error`)})},t)}schedulePush(e){if(this.mode!==`full`)return;this.pushTimer!==null&&clearTimeout(this.pushTimer);let t=e??this.effectivePushDelayMs();this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){if(this.resolveRelayGhToken()!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(this.syncGhTarget().host))?.token)return`authenticated`}catch(e){$.warn({err:e},`[sync] auth-tier token-store lookup threw — treating as anonymous`)}return`anonymous`}async refreshAuthTier(){this.authTier=await this.resolveAuthTier()}currentPullIntervalSeconds(){return this.mode===`follow`?MIe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=n9(this.consecutivePullFailures),t=e>0?e/1e3:0;return e9(Math.max(t,this.currentPullIntervalSeconds()))}effectivePushDelayMs(){let e=n9(this.consecutivePushFailures),t=e>0?e/1e3:0;return e9(Math.max(t,this.pushIntervalSeconds))}logContention(){let e={consecutiveContentions:this.consecutiveContentions,consecutivePushFailures:this.consecutivePushFailures,releasedConnectivityStreak:this.pushStreakIsConnectivity};this.consecutiveContentions>=3?$.warn(e,`[sync] push repeatedly losing to remote contention — not backing off by design`):$.info(e,`[sync] push still rejected after retry (contention) — scheduling next push at base cadence`)}bumpFailureCount(e,t=!1){e===`push`?(this.consecutiveContentions=0,this.consecutivePushFailures++,this.pushStreakIsConnectivity=(this.consecutivePushFailures===1||this.pushStreakIsConnectivity)&&t):this.consecutivePullFailures++}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(t9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle(this.mode===`full`?`sync`:`explicit`))}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(e){let t=this.gitHandle(),n;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!e||e===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`),`refused`;n=e,this.currentBranch=n}catch(e){return this.handleError(k7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await t.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutivePullFailures=0,this.clearPullError(),this.consecutivePushFailures>0&&this.pushStreakIsConnectivity&&($.info({cleared:this.consecutivePushFailures},`[sync] fetch succeeded — releasing connectivity-class push backoff`),this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.schedulePush())}catch(e){let t=k7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}if(await this.refreshDivergenceCounts(t),this.behind>0&&e===`explicit`){let e=await this.doPullCycleB1(t,n);return this.scheduleSaveState(),e}if(this.behind>0&&this.conflictCount===0){this.pausedReason===`diverged-local-commits`&&(this.pausedReason=void 0),this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(t);let e=await this.prepareForMerge(t,n);if(!e.proceed)return`refused`;let r=!0,i=!0;try{await this.applyCommitIdentity(t),await t.git.merge([`origin/${n}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.pausedReason===`external-changes-pending`&&this.clearBlockingPause(),this.transitionTo(`idle`)}finally{e.needsStashPop&&(r=await this.popPreMergeStash(t)),i=this.restoreReconciledMcpOverlays(e.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);return await this.persistReconciledMcpEntries(e.reconciled),this.scheduleSaveState(),`succeeded`}catch(e){let t=k7(e instanceof Error?e:Error(String(e)));return t.class===`semantic`&&t.subclass===`merge-conflict`?(await this.handleMergeConflict(),this.state===`conflict`?`conflict`:this.pullError?`error`:`succeeded`):(this.handleError(t,`pull`),`error`)}finally{this.setBatchInProgress?.(!1)}}return this.transitionTo(`idle`),this.scheduleSaveState(),this.behind===0?`up-to-date`:`conflict`}async doPullCycleB1(e,t){if(this.transitionTo(`pulling`),this.ahead>0)return this.clearPullError(),this.pausedReason=`diverged-local-commits`,this.transitionTo(`idle`),$.warn({ahead:this.ahead,behind:this.behind},`[sync] pull-only: local history diverged — not fast-forwardable, skipping cycle`),`refused`;let n,r;try{n=(await e.git.revparse([`HEAD`])).trim();let i=await Ab(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Ab(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(k7(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(k7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.setBatchInProgress?.(!0);try{if(r.length>0){try{await this.checkpointBeforeOverlayRestore?.({branch:t,paths:r.length})}catch(e){$.warn({err:e,paths:r.length},`[sync] pull-only: overlay checkpoint failed before restore — proceeding`)}try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...r])}catch(e){return $.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(k7(e instanceof Error?e:Error(String(e))),`pull`),`error`}}let n=await this.fastForwardOnly(e,t);if(!n.ok){try{this.applyOverlayPlan(a.mineRestore,a.deletions)}catch(e){return $.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(k7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?($.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(k7(Error(`git merge --ff-only timed out after ${r9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),$.warn({refusal:n.refusal,stderr:n.stderr.slice(0,200)},`[sync] pull-only: fast-forward refused — skipping cycle`),`refused`)}try{this.applyOverlayPlan(a.writes,a.deletions)}catch(e){return $.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(k7(e instanceof Error?e:Error(String(e))),`pull`),`error`}let i=!0;for(let e of a.upserts)i=this.conflictStore.addConflict(e)&&i;for(let e of a.dissolved)i=this.conflictStore.removeConflict(e)&&i;if(this.conflictCount=this.conflictStore.count(),!i)return $.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(k7(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.blockingPaths=[],this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return $.info({created:a.newConflicts.length,autoCombined:a.autoCombined.length,autoDissolved:a.dissolved.length,autoRestored:a.autoRestored.length,overlayStock:o},`[sync] pull-only: fast-forwarded to origin tip`),a.newConflicts.length>0?`conflict`:`succeeded`}finally{this.setBatchInProgress?.(!1)}}async fastForwardOnly(e,t){try{return await NIe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:r9}),{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:PIe({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(!U(z(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),$.warn({err:e,path:p},`[sync] pull-only: unexpected error probing origin for a deleted overlay — deferring reconcile`);continue}s.push(p),m&&l.push(p);continue}if(!this.isContentConflictPath(p)){s.push(p);continue}f.push(p),m&&l.push(p);continue}let h;try{h=W(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`&&$.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&&q7.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=W7({target:p,layers:{base:t,head:t,index:await this.readMcpGitBlob(e,``,p),worktree:g,incoming:_},tomlEditor:this.mcpTomlEditor});if(r.kind===`resolved`){r.raw!==_&&a.push({path:p,bytes:Buffer.from(r.raw,`utf8`)}),$.info({event:`mcp-config-reconcile`,target:p,outcome:`auto-resolved`},`[sync] pull-only: auto-resolved OpenKnowledge MCP entry overlap`);continue}r.kind===`declined`&&$.warn({event:`mcp-config-reconcile`,target:p,outcome:`declined`,reason:r.reason},`[sync] pull-only: declined OpenKnowledge MCP entry reconciliation`)}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=xr(v?await this.gitBlobContent(e,v):``,g,_);if(y.clean){a.push({path:p,bytes:Buffer.from(y.merged,`utf-8`)}),d.push(p),m&&l.push(p);continue}a.push({path:p,bytes:h});let b=await this.gitBlobSha(e,`origin/${t}:${p}`);if(b===void 0){$.warn({path:p},`[sync] pull-only: could not pin origin blob for a collision — keeping overlay, deferring`);continue}c.push({file:p,detectedAt:r?.detectedAt??new Date().toISOString(),variant:`working-tree`,theirsSha:b,baseSha:v}),m||u.push(p)}return{writes:a,mineRestore:o,deletions:s,upserts:c,dissolved:l,newConflicts:u,autoCombined:d,autoRestored:f}}applyOverlayPlan(e,t){let n={allowShareableOkArtifact:dM};for(let{path:t,bytes:r}of e){let e=z(this.projectDir,t);Pq(e,this.projectDir,n),cc(e,r)}for(let e of t){let t=z(this.projectDir,e);Pq(t,this.projectDir,n);try{Qs(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=z(this.projectDir,e),n=Uk(B(this.contentDir,t));return!n.startsWith(`..`)&&Ox(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 Ab(e.git,[`diff-index`,`--name-only`,`HEAD`])).filter(e=>this.isContentConflictPath(e)).length}catch{return null}}async runPushCycle(){if(!this.pushInFlight&&this.mode===`full`&&!(this.state===`dormant`||this.state===`disabled`)&&!(this.state===`conflict`||this.state===`auth-error`)){if(this.conflictCount>0){this.schedulePush();return}if(t9(this.projectDir)){this.schedulePush();return}if(this.pullInFlight){$.info({pullInFlight:!0},`[sync] push cycle deferred — a pull cycle holds the tree`),this.pushTimer===null&&this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.pushCycleLanded&&this.markRun(),this.schedulePush()}}}async doPushCycle(e=0){this.pushCycleLanded=!1;let t=z(Iu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;this.transitionTo(`pushing`);try{let e=this.gatherContentFilesSync();await _c(async()=>{let r=this.gitHandle(t);if(t9(this.projectDir)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await r.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){$.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(k7(e instanceof Error?e:Error(String(e))),`push`);return}await r.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(r,i),o=await this.stageContentFiles(r,e),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(r,c);let l=(await r.git.raw([`write-tree`])).trim(),u=``;try{u=(await r.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let t=null;try{t=(await r.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(t===i){$.info({contentFileCount:e.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.transitionTo(`idle`);return}$.info({headSha:i,upstreamSha:t},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=i;return}let d=[],f=[];try{let t=await Ab(r.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(t.length>0){let n=new Map(e.map(e=>[e.projectRelPath,e.contentRelPath]));for(let e of t){d.push(e);let t=n.get(e)??Uk(B(this.contentDir,z(this.projectDir,e)));t&&!t.startsWith(`..`)&&f.push(t)}}}catch{d=e.map(e=>e.projectRelPath).concat(c),f=e.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f);await this.applyCommitIdentity(r);let m=(await r.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!m||!J7.test(m)){$.warn({raw:m},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await r.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,m,i]),await this.resetRealIndexForPaths(d);let h=!1;try{await r.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),h=!0}catch{}h?await r.git.raw([`push`,`origin`,this.currentBranch]):await r.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),n=m}),n&&(this.lastPushedSha=n,this.lastSyncUtc=new Date().toISOString(),this.pushCycleLanded=!0,this.ahead=0,this.consecutivePushFailures=0,this.consecutiveContentions=0,this.pushStreakIsConnectivity=!1,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=t instanceof Error?t:Error(String(t));n instanceof Y7&&$.warn({err:n},`[sync] push cycle: staging error detail`);let r=k7(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);let t=`fetch`;try{await e.git.fetch(`origin`),t=`push`,await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,this.currentBranch);if(!n.proceed){this.setBatchInProgress?.(!1);return}let r=!0,i=!0;try{await this.applyCommitIdentity(e),t=`merge`,await e.git.merge([`origin/${this.currentBranch}`]),t=`push`}finally{n.needsStashPop&&(r=await this.popPreMergeStash(e)),i=this.restoreReconciledMcpOverlays(n.reconciled)}if(!r)throw Error(`failed to replay pre-merge working-tree state`);if(!i)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(n.reconciled)}catch(e){let n=k7(e instanceof Error?e:Error(String(e)));if(n.class===`semantic`&&n.subclass===`merge-conflict`)await this.handleMergeConflict();else{let r=t===`merge`||t===`fetch`?`pull`:`push`;$.warn({err:e,stage:t},`[sync] push retry error detail`),this.handleError(n,r)}this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}this.consecutiveContentions++,this.logContention(),this.pushStreakIsConnectivity&&(this.consecutivePushFailures=0,this.pushStreakIsConnectivity=!1,this.clearPushError()),this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{Au(t)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=z(Iu(),`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 Ab(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}await this.applyCommitIdentity(a);let u=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!u||!J7.test(u)?($.warn({raw:u},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,u,t]),await this.resetRealIndexForPaths(l,e),u)}finally{try{Au(i)}catch{}}}async readMcpGitBlob(e,t,n){try{return await e.git.raw([`cat-file`,`-e`,`${t}:${n}`]),await e.git.raw([`show`,`${t}:${n}`])}catch{return null}}async planTrackedMcpOverlap(e,t,n){let r;try{r=(await e.git.raw([`merge-base`,`HEAD`,`origin/${t}`])).trim()}catch(e){return $.warn({err:e,branch:t,path:n},`[sync] MCP reconciliation merge-base unavailable — declining`),{kind:`declined`,reason:`merge-base-unavailable`}}let[i,a,o,s]=await Promise.all([this.readMcpGitBlob(e,r,n),this.readMcpGitBlob(e,`HEAD`,n),this.readMcpGitBlob(e,``,n),this.readMcpGitBlob(e,`origin/${t}`,n)]),c=null;try{c=W(z(this.projectDir,n),`utf8`)}catch{}return W7({target:n,layers:{base:i,head:a,index:o,worktree:c,incoming:s},tomlEditor:this.mcpTomlEditor})}async prepareForMerge(e,t){let n=[],r;try{r=await Ab(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return $.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}if(r.length===0)return{proceed:!0,needsStashPop:!1,reconciled:n};let i;try{i=new Set(await Ab(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return $.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1,reconciled:n}}let a=r.filter(e=>i.has(e)),o=q7,s=a.filter(e=>o.has(e));if(s.length>0){let r=await Promise.all(s.map(async n=>({path:n,plan:await this.planTrackedMcpOverlap(e,t,n)}))),i=r.find(({plan:e})=>e.kind===`declined`),c=a.some(e=>!o.has(e));if(!i&&!c){for(let{path:e,plan:t}of r)t.kind===`resolved`&&(n.push({path:e,raw:t.raw,winnerEntry:t.winnerEntry}),$.info({event:`mcp-config-reconcile`,target:e,outcome:`auto-resolved`},`[sync] auto-resolved OpenKnowledge MCP entry overlap`));a=a.filter(e=>!o.has(e))}else i?$.warn({event:`mcp-config-reconcile`,target:i.path,outcome:`declined`,reason:i.plan.kind===`declined`?i.plan.reason:void 0},`[sync] declined OpenKnowledge MCP entry reconciliation`):c&&$.info({event:`mcp-config-reconcile`,targets:s,outcome:`suppressed`,reason:`other-blocking-path`},`[sync] suppressed MCP entry reconciliation because another path blocks the merge`)}if(a.length>0){let e=a.slice(0,3).join(`, `),t=a.length>3?`, +${a.length-3} more`:``;return this.blockingPaths=a,this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:a},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(n.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...n.map(e=>e.path)])}catch(e){return $.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.blockingPaths=[],this.transitionTo(`idle`),this.scheduleSaveState(),{proceed:!1,needsStashPop:!1,reconciled:[]}}let c=new Set(n.map(e=>e.path));if(r.every(e=>c.has(e)))return{proceed:!0,needsStashPop:!1,reconciled:n};let l=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,l])}catch(e){return $.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1,reconciled:n}}return{proceed:!0,needsStashPop:!0,reconciled:n}}restoreReconciledMcpOverlays(e){let t=!0;for(let n of e)try{let e=z(this.projectDir,n.path);Pq(e,this.projectDir);let t=null;try{t=W(e,`utf8`)}catch(e){$.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&cc(e,n.raw,`utf8`)}catch(e){t=!1,$.warn({err:e,path:n.path},`[sync] could not restore reconciled MCP overlay`)}return t}async popPreMergeStash(e){try{return await e.git.raw([`stash`,`pop`]),!0}catch(e){return $.warn({err:e},`[sync] stash pop failed — stash remains on stack`),!1}}hasGitOperationInProgress(){let e=fd(this.projectDir);return e?[`MERGE_HEAD`,`CHERRY_PICK_HEAD`,`REVERT_HEAD`,`rebase-merge`,`rebase-apply`].some(t=>U(z(e,t))):!0}async persistReconciledMcpEntries(e){if(e.length!==0){if(this.hasGitOperationInProgress())throw Error(`refusing MCP entry commit while a Git operation is in progress`);await _c(async()=>{let t=z(Iu(),`ok-mcp-sync-idx-${process.pid}-${Date.now()}.idx`),n=[];try{let r=this.gitHandle(),i=this.gitHandle(t),a=(await i.git.revparse(`HEAD`)).trim(),o=(await i.git.revparse([`--abbrev-ref`,`HEAD`])).trim();if(o===`HEAD`)throw Error(`refusing MCP entry commit on detached HEAD`);await i.git.raw([`read-tree`,a]);let s=[];for(let r=0;r<e.length;r++){let o=e[r];if(!o)continue;let c=await this.readMcpGitBlob(i,a,o.path);if(c===null)throw Error(`tracked MCP path disappeared: ${o.path}`);let l=TIe({target:o.path,raw:c,entry:o.winnerEntry,tomlEditor:this.mcpTomlEditor});if(l===null)throw Error(`cannot edit tracked MCP path: ${o.path}`);let u=(await i.git.raw([`ls-tree`,a,`--`,o.path])).match(/^(100644|100755)\s/)?.[1];if(!u)throw Error(`unsafe tracked MCP mode: ${o.path}`);let d=`${t}.commit-${r}`;n.push(d),ju(d,l,`utf8`);let f=(await i.git.raw([`hash-object`,`-w`,d])).trim();await i.git.raw([`update-index`,`--add`,`--cacheinfo`,`${u},${f},${o.path}`]);let p=U7({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=U7({target:o.path,raw:o.raw,tomlEditor:this.mcpTomlEditor}),h=p!==null&&p===m?l:o.raw,g=`${t}.replay-${r}`;n.push(g),ju(g,h,`utf8`);let _=(await i.git.raw([`hash-object`,`-w`,g])).trim();s.push({path:o.path,mode:u,blobSha:_,raw:h})}let c=(await i.git.raw([`write-tree`])).trim();if(c===(await i.git.raw([`rev-parse`,`${a}^{tree}`])).trim())return;await this.applyCommitIdentity(i);let l=(await i.git.raw([`commit-tree`,c,`-p`,a,`-m`,`Update OpenKnowledge MCP launcher`])).trim();if(!J7.test(l))throw Error(`commit-tree returned an invalid SHA`);try{await i.git.raw([`update-ref`,`refs/heads/${o}`,l,a])}catch(e){$.info({event:`mcp-config-reconcile`,outcome:`ref-race`,branch:o,err:e},`[sync] skipped MCP launcher commit because the branch moved`);return}try{for(let e of s){await r.git.raw([`update-index`,`--add`,`--cacheinfo`,`${e.mode},${e.blobSha},${e.path}`]);let t=z(this.projectDir,e.path);Pq(t,this.projectDir),W(t,`utf8`)!==e.raw&&cc(t,e.raw,`utf8`)}}catch(t){$.warn({event:`mcp-config-reconcile`,outcome:`overlay-replay-failed`,err:t},`[sync] MCP overlay replay failed; resetting the affected index entries`),await this.resetRealIndexForPaths(s.map(e=>e.path)),this.restoreReconciledMcpOverlays(e)}$.info({event:`mcp-config-reconcile`,outcome:`persisted-entry-commit`},`[sync] persisted OpenKnowledge MCP launcher entry commit`)}finally{for(let e of n)try{Au(e)}catch{}try{Au(t)}catch{}}})}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await Ab(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,$.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&$.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`,`--`],s],[[`add`,`-f`,`--`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...i])}return i}gatherContentFilesSync(){let e=[],t=(e,t)=>{throw new Y7(Uk(B(this.projectDir,t))||`.`,e)},n=(r,i,a,o)=>{let s;try{s=wu(r,{withFileTypes:!0})}catch(e){o?.(e,r);return}for(let c of s){let s=z(r,c.name);if(c.isDirectory()){let e=Uk(B(i,s));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e,a))continue;let r=e.split(`/`).some(e=>e.toLowerCase()===`.ok`);n(s,i,a,o??(r?t:void 0))}else if(c.isFile()||c.isSymbolicLink()){let t=Uk(B(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=Uk(B(this.contentDir,s)),n=Uk(B(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(U(this.contentDir)&&n(this.contentDir,this.contentDir,Z7),this.rootOkOutsideContentWalk){let e=z(this.projectDir,`.ok`);U(e)&&!this.contentFilter.isDirExcluded(`.ok`,Q7)&&n(e,this.projectDir,Q7,t)}return e}isSyncScopedPath(e){let t=z(this.projectDir,e),n=Uk(B(this.contentDir,t)),r=!n.startsWith(`..`)&&!this.contentFilter.isExcluded(n,Z7),i=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,Q7);return r||i}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Ab(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r)this.isSyncScopedPath(e)&&n.add(e)}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await Ab(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){$.error({err:t},`[sync] failed to list conflicted files — aborting merge to avoid committing unresolved state`);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t)this.isContentConflictPath(e)?n.push(e):r.push(e);let i=[],a=Uk(B(this.projectDir,Rs(`project`,this.projectDir)));for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),t.toLowerCase()===a.toLowerCase()?$.warn({file:t},`[sync] auto-resolved .ok/config.yml conflict with theirs: local project config edits were overwritten by the remote version`):$.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){$.warn({err:e,file:t},`[sync] non-content auto-resolve failed — will abort merge and pause sync`),i.push({file:t,err:e})}if(i.length>0){let t=i.map(e=>e.file);try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e,files:t},`[sync] git merge --abort failed during non-content cleanup`)}let n=t.slice(0,3).join(`, `),r=t.length>3?`, +${t.length-3} more`:``;this.pullErrorCode=void 0,this.pullError=`Sync paused — couldn't auto-resolve ${n}${r}. Resolve in your terminal (e.g. \`git rm <file>\` or \`git checkout --ours/--theirs <file> && git add <file>\`), then retry sync.`,this.pausedReason=`non-content-merge-failure`,this.consecutivePullFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=fd(this.projectDir);t=n===null||!U(z(n,`MERGE_HEAD`))}catch(e){$.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),$.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){$.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullError=`Sync paused — could not finalize the merge. Retry sync to try again.`,this.transitionTo(`idle`),$.warn({},`[sync] could not finalize merge after auto-resolving conflicts — merge aborted`)}}}async notifyContentConflictsDetected(e){if(e.length!==0)try{await this.onContentConflictsDetected?.(e)}catch(t){$.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){$.warn({err:t,files:e},`[sync] content conflict resolved callback failed`)}}clearPushError(){this.pushError=void 0,this.pushErrorCode=void 0}clearPullError(){this.pullError=void 0,this.pullErrorCode=void 0}handleError(e,t){e.userFacingCode===null?t===`push`?(this.pushErrorCode=void 0,this.pushError=e.message):(this.pullErrorCode=void 0,this.pullError=e.message):t===`push`?(this.pushErrorCode=e.userFacingCode,this.pushError=void 0):(this.pullErrorCode=e.userFacingCode,this.pullError=void 0),$.warn({class:e.class,subclass:e.subclass,retryable:e.retryable,rawStderr:e.rawStderr},`[sync-error] ${e.message}`),e.class===`auth`?(this.ghTokenSource.invalidate(),this.ghAccountResolver.invalidate(),this.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.bumpFailureCount(t),this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.bumpFailureCount(t,IIe(e)),this.transitionTo(`offline`)):(this.bumpFailureCount(t),this.transitionTo(`idle`))}currentState(){return this.state}markRun(){this.lastPushOkUtc=new Date().toISOString(),this.cc1Broadcaster?.signal(`sync-status`)}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastPullOkUtc:this.lastPullOkUtc,lastPushOkUtc:this.lastPushOkUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutivePullFailures,consecutivePushFailures:this.consecutivePushFailures,pushStreakIsConnectivity:this.pushStreakIsConnectivity,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};ju(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(U(this.statePath))try{let e=W(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastPullOkUtc=t.lastPullOkUtc??null,this.lastPushOkUtc=t.lastPushOkUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutivePullFailures=t.consecutiveFailures??0,this.consecutivePushFailures=t.consecutivePushFailures??0,this.pushStreakIsConnectivity=t.pushStreakIsConnectivity??!1,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`||t.pausedReason===`external-changes-pending`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};Ps();const RIe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function zIe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Hx(e)||Ux(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&RIe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Bs(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Fs.with(Ns.extract(Fs.active(),r),e)}else e()}catch(e){L(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let i9=!1;function a9(){if(i9)return;let e=Ene;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){i9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),i9=!0}catch(e){L(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const BIe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),VIe=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function HIe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=tu(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],uw({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(`
2041
2041
  `)){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(!Kk(a,t))continue;let s=uL(a,t);i.has(s)||U(a)&&i.set(s,o)}return i}function o9(e){a9();let t=e.ingressPolicy??RL({}),{contentDir:n,projectDir:r=n,quiet:i=!0,debounce:a=2e3,maxDebounce:o=1e4,gitEnabled:s=!0,commitDebounceMs:c=3e4,wipRef:l=`refs/wip/main`,configHomedirOverride:u,enableTestRoutes:d=!1,shadowRepo:f,contentRoot:p,destroyTimeoutMs:m=1e4,localOpCliArgs:h,authStreamHeartbeatMs:g,skipStateManifestCheck:_=!1,singleDocRelPath:v,ephemeral:y=!1}=e,b=L(`server`),x=new I5,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),D=e=>x.setBatchInProgress(e),ee=()=>x.isBatchInProgress();function te(e){let t=Hs({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=ms(t.error)&&t.error.code===`SCHEMA_INVALID`?t.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(n.length>0){let e=n.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}if(e?.requireValid)throw Error(`Project config is invalid`,{cause:t.error});b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return t.value.content.attachmentFolderPath??`./`}function O(){let e=Hs({absPath:Rs(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=$ee(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.mode unavailable (config invalid) — falling back to the committed project default`);let n=Hs({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return n.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:ate(n.value.autoSync?.default)??`off`,source:`committed-default`}}function ne(){return vte(Hs({absPath:Rs(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}).value.autoSync)}function re(){let e=Hs({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?tr(e):Yr;return iFe(r,t.plugins.okf),t}function ie(){return Hs({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ae(){return jk(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function oe(){let e=Hs({absPath:Rs(`project-local`,r,u),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)});return e.valid?e.value.linkPreviews?.enabled===!0:!1}function se(){return Ste({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function ce(){for(let e of se().diagnostics)e.code===`REMOVED_KEY`&&b.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 le(e){return`${uk(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let ue;function de(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=O();i=t.mode,sn?.setMode(t.mode,t.source).catch(n=>{b.warn({err:n,mode:t.mode,docName:e},`[sync] failed to apply autoSync mode from config`)});let n=ne();sn?.setIntervals(n.pullIntervalSeconds,n.pushIntervalSeconds)}let a=ae();if(Ie.applyConfig({enabled:a.enabled,providerFingerprint:le(a)}),e===`__config__/project`){try{let e=te({requireValid:!0});ye?.setAttachmentFolderPath(e),ue!==void 0&&e!==ue&&b.warn({previous:ue,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),ue=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}ke?.signal(`lint-config`),(t??re().plugins.okf?.generate?.index===!0)||y5({projectDir:r,contentDir:n,generatedDocNames:kt(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),wt()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}uc();let fe=qu(),pe=lO(r),me=new Hd({localDir:pe,log:L(`acp-registry`)}),he=new Md(pe,L(`acp-permissions`));if(Ite(pe,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{E7({lockDir:pe,shadowRepoDir:pd(r)})}catch(e){throw Ec(pe),e}let ge=$i(),_e=(e,t)=>ge.resolveEmbed(e,t),ve=(e,t)=>{let r=ge.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=V(n,r);if(!Wk(i,V(n)))return null;try{let e=ku(i);return e.isFile()?e.size:null}catch{return null}},ye,be,xe,Se,Ce,we,Te,k,Ee,De,Oe,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=null,Fe=ae(),Ie=new Hk({loadEmbedder:e.embedderLoader??(()=>{let t=ae();return gk({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:z(lO(r),`embeddings`),enabled:Fe.enabled,providerFingerprint:le(Fe)}),Le=null,Re=new Set,ze=!1,Be=[],Ve,He,Ue,We=new Promise((e,t)=>{He=e,Ue=t}),Ge,Ke=new Promise(e=>{Ge=e});async function qe(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ke,n])!==t)return S()}finally{e&&clearTimeout(e)}try{return z5(r).branch??null}catch(e){return b.warn({err:e},`[auth] branch scope gate expired and HEAD is unreadable — skipping the branch claim check`),null}}function Je(e){ke?.signal(e)}let Ye,Xe,Ze,Qe=!1,$e=!1,et=new AbortController,tt=new Set,nt=!1,rt=!1,it=!1,at=0,ot,st=new Promise(e=>{ot=e});function ct(e){it||(it=!0,ot(e))}function lt(){return nt||tt.size>0}function ut(){$e||!Qe||(Ye!==void 0&&clearTimeout(Ye),Ye=setTimeout(()=>{Ye=void 0,yt()},500),Ye.unref?.())}function dt(){if($e){ct({status:`cancelled`,indexCount:0});return}nt=!0,rt=!0,Xe=setImmediate(()=>{Xe=void 0,yt()})}let ft,pt,mt=!1,ht=null;async function gt(){let e=xe.current;if(!e||mt)return;let t=performance.now();b.info({gitDir:e.gitDir},`[shadow-housekeeping] deferred boot housekeeping started`);try{await ax(e)}catch(e){b.warn({err:e},`failed to write gc config (non-fatal)`)}if(!mt){if(ht)try{let t=Number.parseInt(process.env.OK_BOOT_RENAME_GC_RETRY_INTERVAL_MS??``,10)||1e3,n=!1;for(let r=0;r<30;r++){if(!(await aH(e,ht,{rebuild:!0})).skipped){n=!0;break}if(r===29)break;if(await new Promise(e=>{setTimeout(e,t).unref?.()}),mt)return}n||b.warn({gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild retry budget exhausted (persistent GC contention); rebuild deferred to next boot`)}catch(t){b.warn({err:t,gitDir:e.gitDir},`[rename-log] deferred boot GC/rebuild failed; index loaded without GC`)}if(!mt){try{await Se?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}b.info({gitDir:e.gitDir,durationMs:Math.round(performance.now()-t)},`[shadow-housekeeping] deferred boot housekeeping complete`)}}}function _t(){mt||(ft=setImmediate(()=>{ft=void 0,pt=gt().catch(e=>{b.error({err:e},`[shadow-housekeeping] unexpected uncaught failure`)})}))}async function vt(){if(mt=!0,ft!==void 0&&(clearImmediate(ft),ft=void 0),!pt)return;let e,t=new Promise(t=>{e=setTimeout(()=>t(`timeout`),m)});try{if(await Promise.race([pt,t])===`timeout`)throw Error(`shadow housekeeping drain timed out after ${m}ms — abandoning in-flight housekeeping`)}finally{e!==void 0&&clearTimeout(e)}}function yt(){if($e||!Qe||!lt())return;if(Ze!==void 0){e.generatedIndexTestHooks?.onKickWhileInFlight?.();return}if(x.isBatchInProgress()){ut();return}let t=nt,n=new Set(tt),r=rt;nt=!1,tt.clear(),rt=!1;let i=t?{fullSweep:!0}:{fullSweep:!1,directories:n};Ze=(async()=>{let e=await Nt(i,et.signal);if(e.status===`deferred`){nt=!0,r&&(at+=e.indexCount,rt=!0);return}r&&(at+=e.indexCount,e.status===`completed`&&lt()?rt=!0:ct({...e,indexCount:at}))})().catch(e=>{b.warn({err:e},`[index] index regeneration coordinator failed`),r&&ct({status:`failed`,indexCount:0})}).finally(()=>{if(Ze=void 0,$e){r&&ct({status:`cancelled`,indexCount:0});return}lt()&&Ye===void 0?ut():!lt()&&Ye===void 0&&e.generatedIndexTestHooks?.onIdle?.()})}async function bt(){if(!$e){let e=Ze;$e=!0,et.abort(),Ye!==void 0&&(clearTimeout(Ye),Ye=void 0),Xe!==void 0&&(clearImmediate(Xe),Xe=void 0),tt.clear(),nt=!1,rt=!1,e===void 0&&ct({status:`cancelled`,indexCount:0})}await Ze}function xt(e){$e||KPe(e)||(tt.add(A5(e)),ut())}function St(e){if(!$e){for(let t of GPe(e))tt.add(t);ut()}}function Ct(e){let t=an?.getFileIndex();if(!t){xt(e);return}let n=A5(e);if(N5(t.keys()).has(n)){xt(e);return}St(A5(n))}function wt(){$e||(nt=!0,ut())}function Tt(e){let t=an?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let Et=!1,Dt={origin:VIe,writer:Oce,isConflict:e=>sn?.getConflicts().some(t=>a5(t,e,r,n))===!0,getDocument:e=>Te.documents.get(e),writeDisk:async(e,t)=>{tc(R(e),{recursive:!0}),await Vs(e,t,{fs:Js})},registerWrite:(e,t)=>eL(e,nL(t)),noteFileIndex:e=>an?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>Je(`files`),attribute:async(e,t)=>{AO(e,t.id,t.name,t.id),Et=!0}};function Ot(e){return e===``?O5:`${e}/${O5}`}function kt(){return[...an?N5(an.getFileIndex().keys()):new Set([``])].map(Ot)}function At(e){let t=re().plugins.okf?.generate?.index===!0,n=e.state===`ready`||e.state===`not-applicable`;return{enabled:t,active:t&&n,git:e.state===`ready`?{state:e.state,ownership:e.ownership}:{state:e.state}}}function jt(){return At(_5({projectDir:r,contentDir:n,generatedDocNames:kt()}))}async function Mt(e){let t=await y5({projectDir:r,contentDir:n,generatedDocNames:kt(),enabled:e});if(!t.ok)return{...jt(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ec({cwd:r,scope:`project`,patch:{contentRules:{okf:{generate:{index:e}}}}});if(!i.ok){try{await t.rollback()}catch(e){b.error({err:e},`[index] could not roll back generated-index Git attributes`)}return{...jt(),applied:!1,reason:`config-write`}}try{let e=W(i.path,`utf-8`);i5(Te.documents.get(`__config__/project`)??null,Er,e,Ce.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return de(Er,e),{...jt(),applied:!0}}async function Nt(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>re().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=an?.getFileIndex();if(!c)return{status:`failed`,indexCount:0};try{if(await e.generatedIndexTestHooks?.beforePlan?.({fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};let o=qPe({docs:c,docExtension:Ix,currentMarkdownFor:()=>null}),l=_5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>Ot(e))});if(l.state!==`ready`&&l.state!==`not-applicable`)return b.warn({state:l.state},`[index] generated index regeneration paused by Git attributes`),{status:`blocked`,indexCount:a};for(let{directory:r,markdown:c}of o){if(!t.fullSweep&&!t.directories.has(r))continue;if(i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};if(x.isBatchInProgress())return{status:`deferred`,indexCount:a};if(await e.generatedIndexTestHooks?.beforeDecision?.({directory:r,fullSweep:t.fullSweep,signal:i}),i.aborted)return{status:`cancelled`,indexCount:a};if(s())return{status:`disabled`,indexCount:a};let o=Ot(r),l=V(n,`${o}.md`),u;try{u=W(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:rc(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await DPe({docName:o,absPath:l,markdown:c,currentMarkdown:u},Dt);d===`blocked-conflict`?b.warn({event:`generated-index-regeneration`,outcome:`blocked`,directory:r,reason:`conflict`},`[index] generated index regeneration blocked by active conflict`):b.info({event:`generated-index-regeneration`,outcome:d===`unchanged`?`unchanged`:`written`,directory:r},`[index] generated index regeneration completed`),await e.generatedIndexTestHooks?.afterWrite?.({docName:o,fullSweep:t.fullSweep,signal:i}),!t.fullSweep&&r!==``&&u===null&&St(A5(r))}}finally{Et&&=(await Ce.waitForPendingCommits(),await Ce.flushContributors(),!1),o!==void 0&&(dR(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),fR(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Pt=null,Ft=!1,It=()=>{try{_7(r,Lt.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Lt=new IFe(void 0,{onEviction:()=>cce(),onSizeChange:e=>lce(e),onMutate:()=>{!Ft||Pt!==null||(Pt=setTimeout(()=>{Pt=null,It()},2e3))}});for(let[e,t]of VFe(r))Jx(e)||aZ(e)&&([`.md`,`.mdx`].some(t=>{let r=V(n,`${e}${t}`);return Wk(r,V(n))&&U(r)})||Lt.restore(e,t));Ft=!0;let Rt={current:null},zt=(e,t)=>{Jx(e)||Lt.setRenamed(e,t)},Bt=e=>{if(!Jx(e)){if(Lt.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Lt.setDeleted(e),Rt.current?.deleted(e)}},Vt=e=>{Jx(e)||Lt.delete(e)};try{let m=`./`;try{m=te()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}ue=m,ye=TM({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:FF(n),rescanInPlaceSkillDirs:()=>FF(n),skillRootPaths:whe(n),onAfterRebuild:()=>{be.refreshContentScope().catch(e=>{L(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Cge(an).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`)})}}),be=new $he({projectDir:r,contentDir:n,contentFilter:ye,getGlobalSkillRoots:()=>gH(Ce.managedArtifactCtx),signalChannel:Je,getLocalTargetInventory:()=>_ye(an,n),onRecoveredFileTarget:(e,t)=>{an&&RFe({watcher:an,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Ne})}}),xe={current:f},Se=s?CFe({getShadow:()=>xe.current??null,getCurrentBranch:()=>on?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:fd(r)??void 0,isWriterLive:e=>{if(!Me&&!k)return L(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Me?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of k?.sessionsForConnection(t)??[])return!0;return!1}}):void 0;let _=null;Ce=u7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:xe,ephemeral:y,contentRoot:p,derivedDocumentIndex:be,configHomedirOverride:u,getCurrentBranch:()=>on?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,getPrincipal:()=>Le,onAgentCommit:()=>ke?.signal(`session-activity`),onFlushCommit:()=>Se?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ke?.emitDiskAck(e,t),!Jx(e)&&(JPe(r,n,e)&&xt(e),Qge(r,n)&&(Ne?.(),Je(`files`)))},onConfigRejected:(e,t)=>ke?.emitConfigValidationRejected(e,t),onConfigPersisted:de,onManagedSkillPersisted:e=>{let t=Qi(e);t?.kind!==`skill`||t.scope!==`global`||(_!==null&&clearTimeout(_),_=setTimeout(()=>{_=null;let e=u??Nu();PJ(e,e,NF(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] post-edit copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] post-edit copy re-sync failed`))},2e3),_.unref?.())},isRecentlyRemoved:e=>Lt.has(e),mdManager:e.mdManager,getLossRing:()=>we,durabilityState:x}),Te=new dPe({quiet:i,debounce:a,maxDebounce:o,extensions:[Ce.extension]});let S=Te.openDirectConnection.bind(Te);Te.openDirectConnection=((e,t)=>S(Rx(e),t));let w=Te;Be.push(Nle(()=>w.documents.size),Ple(()=>Ce.getQueueDepths()),Ile(()=>{let e=0;for(let t of w.documents.values())e+=t.directConnectionsCount;return{websocket:w.getConnectionsCount()-e,direct:e}})),Rle(),y||(Pe=PFe({getLoadedDocuments:()=>w.documents,forceStore:(e,t)=>Ce.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let t=Gk(e,n),r,i;try{r=G(t),i=ku(r).size}catch(t){let n=Oc(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new f7(`symlink cycle at content path: ${e}`):t}if(!Kk(r,n))throw new f7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new f7(`document exceeds the open byte limit: ${e}`);try{return W(r,`utf-8`)}catch(e){if(Oc(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let T=Te.shouldUnloadDocument.bind(Te);Te.shouldUnloadDocument=e=>{if(Re.has(e)||ze&&T(e))return!0;let t=e.name;return Jx(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:T(e)},Ve=async e=>{Re.add(e);try{await Te.unloadDocument(e)}finally{Re.delete(e)}},ke=new Qx(Te),je=new jE(Te),Me=new ME(Te),k=new cw(Te,e.agentSessionOptions);let E=k;Be.push(Lle(()=>({active:E.liveSessionCount,limit:E.sessionLimit})));let D=H5({derivedDocumentIndex:be,onDocumentSettled:e=>Rt.current?.changed(e)});Te.configuration.extensions.push(D);function ee(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Te.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=hZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==fe)throw ee(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:fe}),new mZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${fe}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await qe();if(t!==null&&i!==t)throw ee(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new mZ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(Le&&n.principalId===Le.id?a.principalId=Le.id:Le?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Le.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Te.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!Ux(e.documentName)&&!Wx(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!zL(r,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`peer`}),Error(`config-doc admission requires loopback peer (peer=${r}, doc=${e.documentName})`);let i=e.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0;if(!BL(a,t))throw ee(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let O=V(n);function ne(e){if(!aZ(e))return null;let t=V(O,zx(e));return Wk(t,O)?t:null}Te.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await zFe(e.documentName,{recentlyRemovedDocs:Lt,resolveFilePath:ne,fileExists:U})}}),Te.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=hZ(e.token);YPe(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Te.documents.get(e)})}}),Te.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new w8(e.update);if(t.readVarString(),t.readVarUint()===F8.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Mo} rejected — server-only channel`)}});let ce=oZ({hocuspocus:Te,durabilityState:x,ingressPolicy:t,sessionManager:k,commentDocHooksRef:Rt,contentDir:n,getGeneratedIndexSettingsStatus:jt,setGeneratedIndexEnabled:Mt,contentFilter:ye,serverInstanceId:fe,getFileIndex:()=>an?an.getFileIndex():new Map,getAttachmentFolderPath:te,getAllFilesIndex:()=>an?an.getAllFilesIndex():new Map,getFileIndexGeneration:()=>an?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?Tt(e.docName):void 0;switch(an?.mutateFileIndex(e),e.kind){case`update`:F5(t,e.content,e.docName)&&xt(e.docName);break;case`create`:case`conflict`:xt(e.docName);break;case`delete`:Ct(e.docName);break;case`rename`:Ct(e.oldDocName),xt(e.newDocName);break;case`folder-create`:case`folder-delete`:St(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:XI(e)}},getFolderIndex:()=>an?an.getFolderIndex():new Map,getAliasMap:()=>an?an.getAliasMap():new Map,getFolderAliasIndex:()=>an?an.getFolderAliasIndex():new Map,rescanFiles:()=>an?.rescanFromDisk(),enableTestRoutes:d,shadowRef:xe,flushGitCommit:()=>Ce.flushPendingGitCommit(),flushContributors:()=>Ce.flushContributors(),getCurrentBranch:()=>on?.getLastKnownBranch()??null,getDiskAckSVs:()=>ke?.getLatestDiskAckSVsAsBase64()??{},getCollabClientCount:e.getCollabClientCount,contentRoot:p,derivedDocumentIndex:be,signalChannel:Je,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>sn,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:_e,getBridgeLossReporter:()=>Oe,getPrincipal:()=>Le,acpRegistry:me,loadAcpCustomAgents:()=>Ud(pe,L(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Ve,ready:We,recentlyRemovedDocs:Lt,serializeDoc:qt,evictManagedArtifactLkg:e=>{Ce.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ie,getSemanticSimilarityFloor:()=>ae().similarityFloor,getLinterBaseConfig:()=>re(),getLinksValidationSetting:()=>ie(),getLinkPreviewsEnabled:oe,getConfigDiagnostics:se,embeddingsSecretsFile:Ck(u),readSemanticProviderConfig:ae,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Ne=e}});Te.configuration.extensions.push(ce),Ee=ce.nativeApi,De=ce.localApi;let le=Hs({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),he=le.value.bridge.deferGuard.enabled,ge=le.value.bridge.fixedPoint.enabled,Ae=le.value.bridge.preDrain.enabled;we=le.value.lossCapture.enabled?new Xoe({projectDir:r,maxBytes:le.value.lossCapture.maxBytes}):void 0,le.value.bridge.lossDetector.enabled&&(Oe=Hce({shadow:()=>xe.current,ring:we,getBranch:()=>on?.getLastKnownBranch()??`main`,contentRoot:p??``}),k.attachBridgeLossReporter(Oe)),Te.configuration.extensions.push(y7({mdManager:Ls,schema:Is,shadowRef:xe,contentRoot:p,getCurrentBranch:()=>on?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,deferGuardEnabled:he,lossDetectorEnabled:le.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ge,preDrainEnabled:Ae,lossRing:we})),Te.configuration.extensions.push(zIe()),Te.configuration.extensions.push(EPe({getSyncEngine:()=>sn,projectDir:r,contentDir:n}))}catch(e){for(let e of Be.splice(0))e();throw Pe?.dispose(),Pe=null,Ec(pe),e}let Ht=null,Ut=new Map,Wt=[];function Kt(e,t){let n=V(e,`rescue`),r=V(n,zx(t));return Wk(r,n)?r:null}function qt(e){let t=Te.documents.get(e);return t?WI(t):null}let Jt=(e,t)=>HI(x,Te,e,t,_e,ve,Oe);function Yt(e){if(!cS(e)||sn?.getConflicts().some(t=>a5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Xt=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Te.documents){if(Jx(n))continue;let r=Te.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{FI(r,i,_e,n)},PI)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Zt=null,Qt=e=>{e&&(Zt===null&&(Zt=new Set,setImmediate(()=>{let e=Zt;if(Zt=null,e)try{for(let t of e)Xt(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Zt.add(e))};function $t(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return XI(e)}}async function en(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await be.recordDiskUpsert(e.docName,e.content),Je(`files`),xt(e.docName),Vt(e.docName);break;case`update`:{let{docName:t,content:n}=e;F5(e.previousIndexedFields,n,t)&&xt(t);let r=Te.documents.get(t);if(!r){await be.recordDiskUpsert(t,n);return}let i=C(t)??``,a=qt(t)??i,o=BI({docName:t,base:i,ours:a,theirs:n}),s=nL(i).slice(0,6),c=nL(a).slice(0,6),l=nL(n).slice(0,6);switch(b.info({docName:t,base:s,ours:c,theirs:l,result:o.kind},`[reconcile] ${t} base=${s} ours=${c} theirs=${l} result=${o.kind}`),o.kind){case`noop`:Yt(r),await be.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{Jt(t,o.newContent),w(t,o.newContent),Mb(),Yt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),Yt(r)}e&&await be.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{Jt(t,o.newContent),w(t,n),Mb(),Yt(r),e=!0}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),Yt(r)}e&&await be.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{Jt(t,o.newContent),w(t,o.newContent),Mb(),Nb(),e=!0}catch(e){b.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 be.recordDiskUpsert(t,n);break}case`refused`:{Nb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Te.documents.get(t);if(!n){await be.recordDiskDelete(t),Je(`files`),Bt(t),Ct(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=qt(t)??``,a=i!==r;if(a&&xe.current){let e=xe.current,n=on?.getLastKnownBranch()??`main`;queueMicrotask(()=>{xx(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Fb(),b.info({docName:t},`[reconcile] rescue checkpoint saved (delete): ${t}`)}).catch(e=>{b.error({docName:t,err:e},`[reconcile] rescue checkpoint write failed: ${t}`)})})}n.getMap(`lifecycle`).set(`status`,`deleted-upstream`),T(t),await be.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Te.closeConnections(t),await Ve(n),Je(`files`),Bt(t),Ct(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=Te.documents.get(t);if(T(t),w(n,r),await be.recordDiskRename(t,n,r),i){let e=i.getMap(`lifecycle`);e.set(`status`,`renamed`),e.set(`newPath`,n)}b.info({oldDocName:t,newDocName:n},`[reconcile] rename: ${t} → ${n}`),Je(`files`),zt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),Ct(t),xt(n);break}case`conflict`:{let{docName:t}=e,n=Te.documents.get(t);if(!n)return;let r=qt(t);r===null?b.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`),b.info({docName:t},`[reconcile] conflict markers detected: ${t}`);break}case`asset-create`:ge.add(e.relativePath),Je(`files`),Qt(ru(e.relativePath));break;case`asset-delete`:ge.remove(e.relativePath),Je(`files`),Qt(ru(e.relativePath));break;case`folder-create`:case`folder-delete`:Je(`files`),St(e.relativePath);break;case`file-create`:case`file-update`:await be.recordFileTargetUpsert(e.relativePath),Ne?.(),Je(`files`);break;case`file-delete`:await be.recordFileTargetDelete(e.relativePath),Ne?.(),Je(`files`);break;default:XI(e)}}catch(t){let n=$t(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let tn=[];async function nn(e){if(ee()){tn.push(e);return}await en(e)}async function rn(){let e=tn.splice(0,tn.length);for(let t of e)await en(t)}let an=null,on=null,sn=null,cn=null;async function ln(e){if(Te.documents.size===0)return;let t=!1,n=new Promise(e=>{Te.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Te.documents.keys());Te.closeConnections(),Te.flushPendingStores();for(let e of Te.documents.values())e.getConnectionsCount()===0&&Te.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(Te.documents.keys()),i=[],o=[];if(xe.current){for(let e of n)if(!Jx(e))try{let t=qt(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Kt(xe.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:xe.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}yu(R(n),{recursive:!0}),ju(n,t,`utf-8`),Fb(),i.push(e),b.info({docName:e},`[rescue] rescue buffer saved on flush timeout: ${e}`)}catch(t){o.push(e),b.error({err:t,docName:e},`[rescue] failed to write rescue buffer for ${e}`)}}else b.warn({stillLoadedCount:n.length},`[rescue] shadow repo unavailable at flush timeout — ${n.length} doc(s) will be lost: [${n.join(`, `)}]`),o.push(...n);let s=i.length>0||o.length>0?` — rescued [${i.join(`, `)}]${o.length>0?`, lost [${o.join(`, `)}]`:``}`:``;a(Error(`flushAllStoresAndWait timeout after ${e}ms — ${n.length}/${r.length} docs did not unload: [${n.join(`, `)}]${s}`))},e)});try{await Promise.race([n,a])}finally{i!==void 0&&clearTimeout(i)}}async function un(){return cn||(cn=(async()=>{let e=Date.now(),t=[];ze=!0;try{await bt()}catch(e){b.warn({err:e},`[index] generated index shutdown drain failed`),t.push({phase:`generated-index-drain`,error:String(e)})}for(let e of Be.splice(0))e();try{await Pe?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Pe=null;try{Fte(pe)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}Se?.destroy();try{await vt()}catch(e){b.warn({err:e},`[shadow-housekeeping] shutdown drain failed`),t.push({phase:`shadow-housekeeping-drain`,error:String(e)})}if(Pt!==null&&(clearTimeout(Pt),Pt=null),Ft)try{_7(r,Lt.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal during shutdown`),t.push({phase:`removed-docs-journal-flush`,error:String(e)})}let n,i=await Promise.race([We.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{n=setTimeout(()=>e(`timeout`),5e3)})]);n!==void 0&&clearTimeout(n),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=Te.documents.size;try{try{try{Ae&&=(clearTimeout(Ae),null),on&&=(await on.unsubscribe(),null),an&&=(await an.unsubscribe(),null);for(let{docName:e,cleanup:t}of Wt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Wt.length=0}catch(e){t.push({phase:`watcher-unsubscribe`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1 watcher unsubscribe failed`)}try{ke?.destroy(),Me?.destroy(),Ht&&=(await Ht.disconnect(),null);for(let[e,t]of Ut)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}Ut.clear()}catch(e){t.push({phase:`cc1-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-1b CC1 teardown failed`)}try{await k.closeAll()}catch(e){t.push({phase:`agent-session-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2 agent session drain failed`)}try{await ile()}catch(e){t.push({phase:`parse-pool-teardown`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-2b parse pool teardown failed`)}try{await ln(m)}catch(e){t.push({phase:`flush-all-stores`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-3 flush failed`)}be.close();let e;try{await Promise.race([(async()=>{await Ce.flushPendingGitCommit(),await Ce.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{sn&&=(await sn.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(xe.current){let e;try{await Promise.race([$b(xe.current).drain(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`shadow mutator drain timeout`)),m)})])}catch(e){t.push({phase:`shadow-mutator-drain`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 shadow mutator drain failed`)}finally{e!==void 0&&clearTimeout(e)}try{let e=(await bc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&ju(V(xe.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Sce(xe.current)}catch(e){t.push({phase:`shadow-repo-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-5 destroyShadowRepo failed`)}}let n=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:n},`[server] shutdown flushed ${a} documents in ${n}ms`):b.warn({documentCount:a,durationMs:n,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${n}ms with ${t.length} phase error(s)`)}}finally{try{Ec(pe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await lc()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),cn)}let dn=[];async function fn(){try{Le=await p7(r),b.info({principalId:Le.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!xe.current)try{xe.current=await sx(r,{deferGcConfig:!0}),b.info({gitDir:xe.current.gitDir},`[server] history repo initialized at ${xe.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),dn.push(`shadow-repo`)}if(xe.current)try{let e=FV(xe.current.gitDir);iH(xe.current.gitDir,e),BV(xe.current.gitDir,e),ht=e,b.info({entries:e.byTo.size},`[server] rename log loaded (${e.byTo.size} entries)`)}catch(e){b.warn({err:e},`[rename-log] boot-time load/sweep failed; rename history unavailable`)}if(xe.current)try{await ix(xe.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`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{xe.current=await sx(r,{deferGcConfig:!0})}catch(e){b.error({err:e},`[server] history repo reinit failed`),xe.current=void 0,dn.includes(`shadow-repo`)||dn.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(xe.current){let e=xe.current,t=Uk(B(r,n))||`.`;setTimeout(()=>{dx(e,t).catch(e=>{b.debug({err:e},`[shadow] fan-out index warm-up failed (non-fatal)`)})},3e3).unref()}if(xe.current)try{let e=V(xe.current.gitDir,`last-known-head`),t=null;try{t=W(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await bc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await bc({baseDir:r,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:n,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=import`);try{await vx(xe.current,p??``,t,n,e),Pb()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:n},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${n}, action=noop`);try{ju(e,n,`utf-8`)}catch(e){b.warn({err:e},`[head-drift] failed to write last-known-head`)}}}catch(e){b.warn({err:e},`[head-drift] check failed — continuing`)}try{let e=kye(n,r);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;b.warn({journalVersion:e.journal.version,fromPath:t,toPath:n,restoredDocNames:e.restoredDocNames},`[managed-rename] recovered pending rename ${t} -> ${n}`)}}catch(e){b.error({err:e},`[server] managed rename recovery failed`),dn.push(`managed-rename-recovery`)}try{let e=tz(r);(e.deleted>0||e.errors>0)&&b.info({scanned:e.scanned,deleted:e.deleted,errors:e.errors},`[upload-tempfile-sweep] swept ${e.deleted} orphan tempfile(s)`)}catch(e){b.error({err:e},`[server] upload-tempfile sweep failed`),dn.push(`upload-tempfile-sweep`)}try{Ht=await Te.openDirectConnection(Mo),ke?.emitServerInfo(fe,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),dn.push(`cc1-push`)}let t=y?[]:Ai;for(let e of t)try{let t=await Te.openDirectConnection(e);Ut.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),dn.push(`config-doc:${e}`)}let i=new Map([[Er,Rs(`project`,r)],[To,Rs(`project-local`,r)],[Lee,Rs(`user`,r,u)]]);for(let e of t){let t=i.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await J8(t,t=>{let n=Te.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=i5(n??null,e,t,Ce.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),de(e)});Wt.push({docName:e,cleanup:n}),b.info({docName:e,path:t},`[config-file-watcher] started`)}catch(n){b.warn({err:n,docName:e,path:t},`[config-file-watcher] failed to start for ${e}`),dn.push(`config-file-watcher:${e}`)}}if(!y){let e=null,t=t=>{e!==null&&clearTimeout(e),e=setTimeout(()=>{e=null,be.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle re-ingest failed`)})},300)},n=(e,n)=>{let r=xH(e,Ce.managedArtifactCtx);if(!r)return;let i=EH(Te.documents.get(r)??null,r,n,Ce.managedArtifactCtx);b.info({docName:r,outcome:i},`[managed-artifact-watcher] external change`),Je(`files`),Gt(r)&&t(r)},r=e=>{let n=xH(e,Ce.managedArtifactCtx);Je(`files`),n&&Gt(n)&&t(n)};try{let e=gH(Ce.managedArtifactCtx),t=await wFe(e,n,r);Wt.push({docName:`__skill-files__`,cleanup:t}),b.info({roots:e},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),dn.push(`managed-artifact-watcher:skills`)}try{let e=V(pH(Ce.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await J8(e,()=>{Je(`files`)});Wt.push({docName:`__skill-state__`,cleanup:t}),b.info({path:e},`[skill-state-watcher] started`)}catch(e){b.warn({err:e},`[skill-state-watcher] failed to start`),dn.push(`skill-state-watcher`)}}try{let e=V(n,`.okignore`),t=V(r,`.gitignore`),i=null;try{let e=tu(`git`,[`rev-parse`,`--git-common-dir`],uw({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=z(V(r,e.stdout.trim()),`info`,`exclude`);U(R(t))&&(i=t)}}catch{}let a=i?[e,t,i]:[e,t],o=b;o.info({okignorePath:e,gitignorePath:t,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await _Pe(a,(t,n)=>{(async()=>{if(t===e)try{let e=i5(Te.documents.get(`__config__/okignore`)??null,Si,n,Ce.configPersistenceCtx);o.info({docName:Si,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:B(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ye.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:B(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ke?.signal(`files`);else{let e=B(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ke?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:B(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Wt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:t},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:r,contentDir:n},`[ignore-watcher] failed to start multi-path watcher`),dn.push(`ignore-files-watcher`)}let a=z5(r).branch??`main`;E(a),Ge();let o=be.beginStartup(a),s=!1,c=performance.now();try{await Ks(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&dn.push(`backlink-index`);let i=0;for(let t of e)Jx(t)||Lt.peek(t)?.kind!==`renamed`&&(Lt.setDeleted(t),i++);i>0&&b.info({count:i},`[removal-guard] tombstoned docs deleted while the server was down`);let a=performance.now(),c=/^\.(?!ok\/)[A-Za-z0-9_-]+\/skills\//,l=ye?FF(n):new Set,d=e=>{e.some(e=>c.test(B(n,e).split(H).join(`/`)))&&(Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{Ae=null;try{PJ(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),ke?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=FF(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ye.rebuildIgnorePatterns().then(t=>{t.ok?(b.info({skillDirs:e.size},`[in-place-skills] canonical set changed — filter rebuilt`),ke?.signal(`files`)):b.warn({error:t.error.message},`[in-place-skills] filter rebuild failed after skill re-scan`)}).catch(e=>b.warn({err:e},`[in-place-skills] rebuild threw`))}catch(e){b.warn({err:e},`[in-place-skills] re-scan trigger failed`)}},500))};an=await Ks(`ok.boot.seed-walk`,void 0,async()=>EL(n,nn,ye,{onRawBatch:d})),PJ(r,n).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] boot copy re-sync failed`));{let e=u??Nu();PJ(e,e,NF(e)).then(e=>{e>0&&b.info({refreshed:e},`[in-place-skills] global boot copy re-sync`)}).catch(e=>b.warn({err:e},`[in-place-skills] global copy re-sync failed`))}dR(`seedWalkMs`,Math.round(performance.now()-a));{let e=V(n),t=0;for(let[n]of Lt.entries()){if(!aZ(n))continue;let r=V(e,`${n}${Ix(n)}`);Wk(r,e)&&U(r)&&(Lt.delete(n),t++)}t>0&&b.info({count:t},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}let f=await be.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&dn.push(`tag-index`);let p=0;try{v===void 0?await lZ({contentDir:n,contentFilter:ye,basenameIndex:ge,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):Bxe({contentDir:n,basenameIndex:ge,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),p>0&&(b.warn({count:p},`[basename-index] startup seed completed with ${p} skipped entries — embeds under inaccessible subtrees will not resolve`),dn.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),dn.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),dn.push(`file-watcher`),!s){let e=await be.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&dn.push(`tag-index`)}}finally{dR(`indexesMs`,Math.round(performance.now()-c)),an&&fR(`fileCount`,an.getFileIndex().size)}try{on=await eFe(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),ase(),Te.flushPendingStores(),await Ce.flushPendingGitCommit(),D(!0),xe.current){let e=S(),t=z5(r).branch??e,n=[];for(let[e,t]of Te.documents){if(Jx(e))continue;let r=null;if(t.transact(()=>{r=qt(e)},BIe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await Nce(xe.current,e,gx.id,n,t);r&&(cse(),b.info({count:n.length,branch:e,sha:r.slice(0,8)},`[history] parked ${n.length} docs on ${e} → ${r.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let t=tn.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:t,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${t}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(D(!1),await rn(),e.headMoved&&e.newHead){let t=HIe(r,V(n),e.oldHead,e.newHead);if(t.size>0){jO(t.keys());for(let[e,n]of t)AO(e,jne(n.email),n.name,n.email,wd(e));await Ce.flushContributors()}}if(await Ce.flushDeferredStores(`within-branch`),sn!==null)try{await sn.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{sse(),tn.splice(0,tn.length);let t=!1,r;try{E(i),r=await be.beginBranchSwitch(i),ye.rebuildDirCount();try{let e=0;ge.clear(),await lZ({contentDir:n,contentFilter:ye,basenameIndex:ge,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),dn.includes(`basename-index-partial`)||dn.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Te.documents)if(!Jx(e))try{let r=Gk(e,n);if(!U(r)){let n=C(e)??``,r=qt(e)??``;if(r!==n&&xe.current){let t=xe.current;queueMicrotask(()=>{xx(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Fb(),b.info({docName:e},`[reconcile] rescue checkpoint saved on branch switch: ${e}`)}).catch(t=>{b.error({docName:e,err:t},`[reconcile] rescue checkpoint write failed: ${e}`)})})}t.getMap(`lifecycle`).set(`status`,`deleted-upstream`),b.info({docName:e,branch:i},`[branch-switch] tombstone: ${e} (not on ${i})`);continue}let a=W(r,`utf-8`);Jt(e,a),w(e,a),b.info({docName:e},`[branch-switch] reset: ${e}`)}catch(t){b.error({err:t,docName:e},`[branch-switch] failed to reset ${e}`)}b.info({branch:i,docCount:Te.documents.size},`[branch-switch] loaded branch ${i} (${Te.documents.size} docs)`);try{await be.settleBranchFromDisk(r)}catch(e){be.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(xe.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Te.documents)if(!Jx(t))try{let n=await Fce(xe.current,i,gx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=BI({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Jt(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:Jt(t,a.newContent),w(t,a.newContent),Nb(),e++;{let e=Te.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){b.error({err:e,docName:t},`[branch-switch] restore WIP failed for ${t}`)}e>0&&b.info({count:e,branch:i},`[branch-switch] restored ${e} parked docs on ${i}`)}if(e.oldBranch?.startsWith(`detached-`)&&xe.current)try{let t=ix(xe.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await $b(xe.current).withMutator(async()=>{for(let e of n.split(`
2042
- `))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}D(!1),await Ce.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{be.abortBranchSwitch(r),t||(D(!1),await Ce.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&xe.current&&t>0){let t=p??`.`;try{let n=await vx(xe.current,t,e.oldHead,e.newHead,i);Pb(),b.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){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),dn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=Uk(B(n,z(r,t)));if(e.startsWith(`..`))continue;let i=Ax(e),a=Te.documents.get(i);if(!a)continue;let o=qt(i);o===null?b.warn({docName:i,file:t},`[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`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=Uk(B(n,z(r,t)));if(e.startsWith(`..`))continue;let i=Te.documents.get(Ax(e));i&&Yt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=pP(r);b.debug({resetAmbientCredentials:f,originKind:dP(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=yc(h,{resetAmbient:f}),g=O(),_=ne();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{sn=new LIe({projectDir:r,contentDir:n,contentFilter:ye,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{D(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=xe.current;n&&await bx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=xe.current;n&&await bx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ec({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:As(t.error),configPath:Rs(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await sn.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),sn=null}Je(`files`),be.announceReadyViews();let x=uR();x!==void 0&&dR(`readyMs`,x),ce()}return fn().then(()=>{Qe=!0,He(),dt(),_t()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),be.close(),Ge(),Ue(e)}),{hocuspocus:Te,durabilityState:x,sessionManager:k,nativeApi:Ee,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:Se,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:un,ready:We,generatedIndexSweepReady:st,degraded:dn,lockDir:pe,get syncEngine(){return sn},getLinkPreviewsEnabled:oe,resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function s9(e){return e/1048576}function UIe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:s9(e.rss),heapTotalMb:s9(e.heapTotal),heapUsedMb:s9(e.heapUsed),externalMb:s9(e.external),arrayBuffersMb:s9(e.arrayBuffers)}}}let c9=null,l9=null,u9=null;const d9=1e6;let f9=null,p9=null;Gs(()=>{c9=null,l9=null,u9=null,f9?.disable(),f9=null,p9=null});function WIe(){if(c9)return;let e=dc().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}=UIe();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`})}),c9=e}function GIe(){if(!l9){let e=dc().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(!f9){f9=fne({resolution:20}),f9.enable();return}e.observe(f9.percentile(50)/d9,{stat:`p50`}),e.observe(f9.percentile(99)/d9,{stat:`p99`}),f9.reset()}),l9=e}if(!u9){let e=dc().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=p9;if(p9={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`}))}),u9=e}}const m9=L(`skill-migrate`);function h9(e){return[{host:`agents`,root:g},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=oD.indexOf(e.host),r=oD.indexOf(t.host);return(n===-1?oD.length:n)-(r===-1?oD.length:r)||e.host.localeCompare(t.host)})}const KIe=h9(oi),qIe=h9(so);function JIe(e,t){return U(V(e,_o(t)))}function YIe(e,t){tc(R(t),{recursive:!0});try{Xs(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;ic(e,t,{recursive:!0}),ac(e,{recursive:!0,force:!0})}}function XIe(e,t,n){let r=$P(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 g9(e,t){let n;try{n=G(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!G(V(e,t.dir)).startsWith(n+H)}catch{return!0}}).map(e=>e.name))}async function _9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??KIe,a={migrated:[],skipped:[]};if(!U(n))return a;let o;try{o=wu(n)}catch{return a}let s=B(t,n).split(H).join(`/`),c=new Set;for(let[e,n]of Object.entries(jJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Br.test(e)||RD.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(!U(z(o,`SKILL.md`)))continue;let s=eD(o)?.contentHash;if(s===void 0)continue;let l=G(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:sF(t,i),state:XIe(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=>JIe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ac(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ac(d.path,{recursive:!0,force:!0}),YIe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ac(e.path,{recursive:!0,force:!0}),ic(d.path,e.path,{recursive:!0}));await kA(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),m9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),m9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const v9=L(`skill-reconcile`),ZIe=RD;function y9(){let e=[];for(let t of zi){let n=oi[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:g,editor:null}),e}function QIe(e,t){let n=B(e,V(t));return ou(n)?V(t):n}function b9(e){let{frontmatter:t,body:n}=Ko(e),r={};if(t!==``)try{let e=(0,pO.parse)(S(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function $Ie(e,t){let n=b9(e),r=b9(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 x9(e,t){let n=S9(e),r=S9(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+=ku(s).size+ku(c).size,i>1048576)return!1;let l=W(s),u=W(c);if(!l.equals(u)&&(o!==`SKILL.md`||!$Ie(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function S9(e,t=``){let n=[];for(let r of wu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...S9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function C9(e,t,n){ac(t,{recursive:!0,force:!0}),tc(e,{recursive:!0}),$s(QIe(e,n),t,`dir`)}function w9(e,t){try{let n=Tu(e);return V(ou(n)?n:V(R(e),n))===V(t)}catch{return!1}}function eLe(e,t){try{let n=Tu(e),r=ou(n)?V(n):V(R(e),n);if(!U(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||ou(i))}catch(t){return v9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const tLe=[...zi,`agents`];function nLe(e){for(let t of tLe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function rLe(e){let{projectDir:t,skillsRoot:n}=e;if(!U(n))return;let r;try{r=wu(n)}catch{return}let i=y9();for(let e of r){let r=nLe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(U(o))try{let n=vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!U(z(a,`SKILL.md`))||!U(z(o,`SKILL.md`))||!x9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(sF(t,r))continue;let i=z(r,e);w9(i,a)&&C9(r,i,o)}ac(a,{recursive:!0,force:!0}),v9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){v9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function iLe(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 y9()){let o=V(t,e);if(!U(o)||sF(t,o))continue;let s;try{s=wu(o)}catch(e){v9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(ZIe.has(e))continue;let t=z(o,e),s=V(n,e),c=U(s);try{let l=vu(t);if(l.isSymbolicLink()){if(w9(t,s)&&c)continue;if(eLe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(C9(o,t,s),r.healed.push({name:e,editor:i})):(ac(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Br.test(e)){v9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&x9(t,s)){C9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){v9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=EA(t);for(let[r,a]of i){let i=V(n,r);if(!U(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await OA(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??nF(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){v9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{rLe({projectDir:t,skillsRoot:n})}catch(e){v9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let T9=null,E9=!1;function D9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function O9(e){if(!D9())return;let t=lO(e);T9=new mc({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ve(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};T9?.append(`${JSON.stringify(t)}\n`).catch(e=>{E9||(E9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function k9(){ve(null),await T9?.drain(),T9=null,E9=!1}Ps();const aLe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],oLe=[`cache`,`tmp`];function sLe(e){let t=V(e,ys);if(!(()=>{if(!U(t))return!0;try{return wu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of aLe)U(V(e,t))&&n.push(t);for(let t of oLe){let r=V(e,t);try{U(r)&&ku(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function cLe(e){let t=dd(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 A9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function lLe(e){Kge();let t=e.projectDir??e.contentDir,n=tSe({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}`)}fc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}uc({localSink:n?.telemetry}),O9(t),WIe(),GIe();let{kind:r,gitdir:i}=cLe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=rc(i));let o=$xe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ks(`ok.boot`,{attributes:a},async()=>uLe(e)),l=()=>{if(s)try{let e=Ns.extract(Fs.active(),{traceparent:s});return Fs.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 e=>{try{await d(e)}finally{o.uninstall()}},u}async function uLe(e){let t=e.skipAutoInit??!1,n=e.log??L(`boot`),r=e.serverRuntime??{...Uee(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((mn(r)||!yt(i))&&!r.allowExternal)throw new IL(`refusing to start: the server would bind a non-loopback address (${(yt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=RL({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-C1GmzCcn.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=V(p,`.ok`);if(!U(V(m,`config.yml`)))throw new q6(U(m)?`config`:`okdir`,p);let h=V(m,`.gitignore`);U(h)||L(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??gw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof pw||e instanceof mw){let t=e instanceof mw?e.detected:``,r=e instanceof mw?`too_old`:`not_available`;VJ(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await lc(),await Promise.race([k9(),new Promise(e=>setTimeout(e,A9))]),e}let _=sLe(m);_.length>0&&L(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ys}/.`);let v=null,y=o9({getCollabClientCount:()=>v?.getCount()??0,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee}=y,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,ne=()=>`http://${te}:${O}`,re=e.ephemeral?void 0:B6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ne(),localApi:y.localApi,log:n}),ie=c();ie.headersTimeout=3e4,ie.requestTimeout=6e4;let ae=e.serveContentAssets===!1?void 0:sZ({contentFilter:y.contentFilter,contentSirv:bZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Os,assetExtensions:bs,blocklistExtensions:gte,ingressPolicy:a}),oe=e.reactShellDistDir?bZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,se=e.ephemeral?null:new bE({contentDir:e.contentDir,localDir:w,globalDir:V(Nu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,agentPresenceBroadcaster:D,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ne(),getMcpStdioCommand:()=>yE(e.localOpCliArgs,O,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});se!==null&&await se.init();let ce=`pending`;S.then(()=>{ce=`ready`},()=>{ce=`failed`});let le=G6({httpServer:ie,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:re,ingressPolicy:a,health:{readiness:()=>ce,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ae,reactShellMiddleware:oe,ephemeral:e.ephemeral,acpThreadManager:se}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=TZ(ie);let de=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});de=EZ({httpServer:ie,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await ue(`idle-shutdown`)})})}await j9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let fe=[...new Set(i)],pe=fe[0],me=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},he=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await he(ie,e.port??0,pe??`127.0.0.1`)}catch(e){throw await me(),e}let ge=ie.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0,ve=[];for(let e of fe.slice(1)){let t=c();t.headersTimeout=ie.headersTimeout,t.requestTimeout=ie.requestTimeout;for(let e of ie.listeners(`request`))t.on(`request`,e);for(let e of ie.listeners(`upgrade`))t.on(`upgrade`,e);try{await he(t,_e,e)}catch(t){n.error({err:t,failedAddress:e,port:_e,alreadyBound:ve.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ve,ie])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await me(),t}ve.push(t)}let ye=uR();ye!==void 0&&dR(`httpListenMs`,ye);let be=ie.address(),xe=typeof be==`object`&&be?be.port:e.port??0;O=xe;let Se=ne();d(w,xe,Se),n.info({event:`server-listening`,pid:process.pid,port:xe,addresses:fe,url:Se,lockDir:w},`[boot] listening on ${Se}`);let Ce=!1,we=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${A9}ms`))},A9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async(e=`unspecified`)=>{if(Ce)return;Ce=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),ce=`draining`;let t=[],r=async(e,r)=>{try{await we(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{de?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(se!==null&&await r(`acpThreads.destroy`,()=>se.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of ve)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>le.shutdown()),re!==void 0&&await r(`mcpHttpHandler.close`,()=>re.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{ie.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{ie.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>lc()),await r(`teardownToleranceTelemetry`,()=>k9()),await r(`flushLogFileSinks`,()=>fc.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await _9({projectDir:p,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:g9(e.contentDir,MF(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Nu(),t=await _9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:qIe,inPlaceNames:g9(e,NF(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await iLe({projectDir:p,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ie,destroy:ue,lockDir:w,contentDir:e.contentDir,port:xe,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:mNe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:se}}async function j9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new SZ(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=fd(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!U(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=jte({baseDir:n,timeout:{block:5e3}});s=new Set(await Ab(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=Ax(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 dLe=Jo;function fLe(e={}){let t=e.home??Nu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?U(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?U(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var M9=t(Ote(),1);const N9=z(Nu(),`.ok`,`logs`),pLe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function mLe(){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 hLe(e){yu(e,{recursive:!0})}function P9(){return new Date().toISOString().slice(0,10)}function gLe(e){try{if(ku(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{Eu(n,r)}catch{}}try{Au(`${e}.3`)}catch{}}function _Le(e){try{let t=Date.now(),n=10080*60*1e3,r=wu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ku(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{Au(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{Au(z(e,t.name)),a-=t.size}catch{}}}catch{}}function vLe(e){hLe(N9);let t=P9(),n=e.filePath??z(N9,`${e.name}.${t}.log`);gLe(n),(e._setTimeout??setTimeout)(()=>_Le(N9),5e3).unref();let r=M9.default.destination({dest:n,append:!0,sync:!0});return(0,M9.default)({level:mLe(),name:e.name,redact:{paths:pLe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:M9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function yLe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[M9.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 bLe(e){return z(N9,`${e}.${P9()}.log`)}function F9(){return N9}function xLe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=U(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 I9=ed($l),L9=L(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function SLe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],uw({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function CLe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],uw({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function wLe(e){let t=V(e,`packed-refs`);if(U(t))try{if(W(t,`utf-8`).split(`
2042
+ `))e&&await t.raw(`update-ref`,`-d`,e)}),b.info({context:e.oldBranch},`[branch-switch] cleaned up detached context ${e.oldBranch}`))}catch(e){b.error({err:e},`[branch-switch] detached cleanup failed`)}D(!1),await Ce.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{be.abortBranchSwitch(r),t||(D(!1),await Ce.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&xe.current&&t>0){let t=p??`.`;try{let n=await vx(xe.current,t,e.oldHead,e.newHead,i);Pb(),b.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){b.error({err:e},`[shadow] upstream-import failed`)}}})}catch(e){b.error({err:e},`[server] HEAD watcher failed to start`),dn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=Uk(B(n,z(r,t)));if(e.startsWith(`..`))continue;let i=Ax(e),a=Te.documents.get(i);if(!a)continue;let o=qt(i);o===null?b.warn({docName:i,file:t},`[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`),b.info({docName:i,file:t},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:t},`[sync] failed to mark loaded content conflict`)}}function d(e){for(let t of e)try{let e=Uk(B(n,z(r,t)));if(e.startsWith(`..`))continue;let i=Te.documents.get(Ax(e));i&&Yt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=pP(r);b.debug({resetAmbientCredentials:f,originKind:dP(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=yc(h,{resetAmbient:f}),g=O(),_=ne();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{sn=new LIe({projectDir:r,contentDir:n,contentFilter:ye,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds??_.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds??_.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{D(e),e||Ce.flushDeferredStores(`within-branch`).catch(e=>{b.error({err:e},`[persistence] deferred store drain failed after sync batch`)})},onStateChange:e=>{b.info({state:e},`[sync] state → ${e}`)},onContentConflictsDetected:l,onContentConflictsResolved:d,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=xe.current;n&&await bx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=xe.current;n&&await bx(n,p??``,{action:`pull-only-overlay-restore`,context:{paths:t}},e)},onAutoDisable:async e=>{b.warn({reason:e},`[sync] auto-disabled — persisting to project-local config`);let t=await ec({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:As(t.error),configPath:Rs(`project-local`,r)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await sn.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),sn=null}Je(`files`),be.announceReadyViews();let x=uR();x!==void 0&&dR(`readyMs`,x),ce()}return fn().then(()=>{Qe=!0,He(),dt(),_t()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),be.close(),Ge(),Ue(e)}),{hocuspocus:Te,durabilityState:x,sessionManager:k,nativeApi:Ee,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:Se,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:un,ready:We,generatedIndexSweepReady:st,degraded:dn,lockDir:pe,get syncEngine(){return sn},getLinkPreviewsEnabled:oe,resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function s9(e){return e/1048576}function UIe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:s9(e.rss),heapTotalMb:s9(e.heapTotal),heapUsedMb:s9(e.heapUsed),externalMb:s9(e.external),arrayBuffersMb:s9(e.arrayBuffers)}}}let c9=null,l9=null,u9=null;const d9=1e6;let f9=null,p9=null;Gs(()=>{c9=null,l9=null,u9=null,f9?.disable(),f9=null,p9=null});function WIe(){if(c9)return;let e=dc().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}=UIe();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`})}),c9=e}function GIe(){if(!l9){let e=dc().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(!f9){f9=fne({resolution:20}),f9.enable();return}e.observe(f9.percentile(50)/d9,{stat:`p50`}),e.observe(f9.percentile(99)/d9,{stat:`p99`}),f9.reset()}),l9=e}if(!u9){let e=dc().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=p9;if(p9={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`}))}),u9=e}}const m9=L(`skill-migrate`);function h9(e){return[{host:`agents`,root:g},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=oD.indexOf(e.host),r=oD.indexOf(t.host);return(n===-1?oD.length:n)-(r===-1?oD.length:r)||e.host.localeCompare(t.host)})}const KIe=h9(oi),qIe=h9(so);function JIe(e,t){return U(V(e,_o(t)))}function YIe(e,t){tc(R(t),{recursive:!0});try{Xs(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;ic(e,t,{recursive:!0}),ac(e,{recursive:!0,force:!0})}}function XIe(e,t,n){let r=$P(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 g9(e,t){let n;try{n=G(V(e,`.ok`,`skills`))}catch{n=V(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!G(V(e,t.dir)).startsWith(n+H)}catch{return!0}}).map(e=>e.name))}async function _9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??KIe,a={migrated:[],skipped:[]};if(!U(n))return a;let o;try{o=wu(n)}catch{return a}let s=B(t,n).split(H).join(`/`),c=new Set;for(let[e,n]of Object.entries(jJ(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Br.test(e)||RD.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(!U(z(o,`SKILL.md`)))continue;let s=eD(o)?.contentHash;if(s===void 0)continue;let l=G(o),u=i.map(({host:n,root:r})=>{let i=V(t,r);return{host:n,root:r,path:z(i,e),escapes:sF(t,i),state:XIe(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=>JIe(t,e.root));if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ac(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ac(d.path,{recursive:!0,force:!0}),YIe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ac(e.path,{recursive:!0,force:!0}),ic(d.path,e.path,{recursive:!0}));await kA(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),m9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),m9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const v9=L(`skill-reconcile`),ZIe=RD;function y9(){let e=[];for(let t of zi){let n=oi[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:g,editor:null}),e}function QIe(e,t){let n=B(e,V(t));return ou(n)?V(t):n}function b9(e){let{frontmatter:t,body:n}=Ko(e),r={};if(t!==``)try{let e=(0,pO.parse)(S(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function $Ie(e,t){let n=b9(e),r=b9(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 x9(e,t){let n=S9(e),r=S9(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+=ku(s).size+ku(c).size,i>1048576)return!1;let l=W(s),u=W(c);if(!l.equals(u)&&(o!==`SKILL.md`||!$Ie(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function S9(e,t=``){let n=[];for(let r of wu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...S9(z(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function C9(e,t,n){ac(t,{recursive:!0,force:!0}),tc(e,{recursive:!0}),$s(QIe(e,n),t,`dir`)}function w9(e,t){try{let n=Tu(e);return V(ou(n)?n:V(R(e),n))===V(t)}catch{return!1}}function eLe(e,t){try{let n=Tu(e),r=ou(n)?V(n):V(R(e),n);if(!U(r))return!1;let i=B(V(t),r);return i!==``&&(i.startsWith(`..`)||ou(i))}catch(t){return v9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const tLe=[...zi,`agents`];function nLe(e){for(let t of tLe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function rLe(e){let{projectDir:t,skillsRoot:n}=e;if(!U(n))return;let r;try{r=wu(n)}catch{return}let i=y9();for(let e of r){let r=nLe(e);if(r===null)continue;let a=V(n,e),o=V(n,r);if(U(o))try{let n=vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!U(z(a,`SKILL.md`))||!U(z(o,`SKILL.md`))||!x9(o,a))continue;for(let{rel:n}of i){let r=V(t,n);if(sF(t,r))continue;let i=z(r,e);w9(i,a)&&C9(r,i,o)}ac(a,{recursive:!0,force:!0}),v9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){v9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function iLe(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 y9()){let o=V(t,e);if(!U(o)||sF(t,o))continue;let s;try{s=wu(o)}catch(e){v9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(ZIe.has(e))continue;let t=z(o,e),s=V(n,e),c=U(s);try{let l=vu(t);if(l.isSymbolicLink()){if(w9(t,s)&&c)continue;if(eLe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(C9(o,t,s),r.healed.push({name:e,editor:i})):(ac(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Br.test(e)){v9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&x9(t,s)){C9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){v9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=EA(t);for(let[r,a]of i){let i=V(n,r);if(!U(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await OA(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??nF(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){v9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{rLe({projectDir:t,skillsRoot:n})}catch(e){v9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let T9=null,E9=!1;function D9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function O9(e){if(!D9())return;let t=lO(e);T9=new mc({currentPath:V(t,`tolerance-telemetry.jsonl`),previousPath:V(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ve(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};T9?.append(`${JSON.stringify(t)}\n`).catch(e=>{E9||(E9=!0,L(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function k9(){ve(null),await T9?.drain(),T9=null,E9=!1}Ps();const aLe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],oLe=[`cache`,`tmp`];function sLe(e){let t=V(e,ys);if(!(()=>{if(!U(t))return!0;try{return wu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of aLe)U(V(e,t))&&n.push(t);for(let t of oLe){let r=V(e,t);try{U(r)&&ku(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function cLe(e){let t=dd(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 A9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function lLe(e){Kge();let t=e.projectDir??e.contentDir,n=tSe({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}`)}fc.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}uc({localSink:n?.telemetry}),O9(t),WIe(),GIe();let{kind:r,gitdir:i}=cLe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=rc(i));let o=$xe(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ks(`ok.boot`,{attributes:a},async()=>uLe(e)),l=()=>{if(s)try{let e=Ns.extract(Fs.active(),{traceparent:s});return Fs.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 e=>{try{await d(e)}finally{o.uninstall()}},u}async function uLe(e){let t=e.skipAutoInit??!1,n=e.log??L(`boot`),r=e.serverRuntime??{...Uee(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((mn(r)||!yt(i))&&!r.allowExternal)throw new IL(`refusing to start: the server would bind a non-loopback address (${(yt(i)?r.bind:i).join(`, `)}), which exposes this server beyond this machine. Consent with OK_ALLOW_EXTERNAL=1, or server.allowExternal: true in .ok/local/config.yml.`);let a=RL({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrl===void 0&&(a.bindLiterals.length===0?n.warn({bind:r.bind},`[ingress] server.allowExternal is set on a wildcard bind (0.0.0.0/::) with no server.externalUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.externalUrl to the public origin clients dial (e.g. behind a reverse proxy or platform edge), or bind a specific address instead of a wildcard.`):n.info({bind:r.bind},`[ingress] server.allowExternal is set with no server.externalUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.externalUrl to admit a hostname.`));let o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-CHQfzAi7.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=V(p,`.ok`);if(!U(V(m,`config.yml`)))throw new q6(U(m)?`config`:`okdir`,p);let h=V(m,`.gitignore`);U(h)||L(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??gw;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof pw||e instanceof mw){let t=e instanceof mw?e.detected:``,r=e instanceof mw?`too_old`:`not_available`;VJ(e),n.warn({event:`git_preflight_fail`,platform:e.platform,reason:r,detectedVersion:t},r===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await lc(),await Promise.race([k9(),new Promise(e=>setTimeout(e,A9))]),e}let _=sLe(m);_.length>0&&L(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ys}/.`);let v=null,y=o9({getCollabClientCount:()=>v?.getCount()??0,contentDir:e.contentDir,projectDir:e.projectDir,ingressPolicy:a,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,mcpTomlEditor:e.mcpTomlEditor,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,capabilities:e.reactShellDistDir?[`http`,`ws`,`ui`]:[`http`,`ws`],skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,detectGhAccounts:e.detectGhAccounts,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral,configHomedirOverride:e.configHomedirOverride}),{hocuspocus:b,destroy:x,ready:S,degraded:C,lockDir:w,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee}=y,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,ne=()=>`http://${te}:${O}`,re=e.ephemeral?void 0:B6({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ne(),localApi:y.localApi,log:n}),ie=c();ie.headersTimeout=3e4,ie.requestTimeout=6e4;let ae=e.serveContentAssets===!1?void 0:sZ({contentFilter:y.contentFilter,contentSirv:bZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:Os,assetExtensions:bs,blocklistExtensions:gte,ingressPolicy:a}),oe=e.reactShellDistDir?bZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,se=e.ephemeral?null:new bE({contentDir:e.contentDir,localDir:w,globalDir:V(Nu(),`.ok`),registry:y.acpRegistry,permissions:y.acpPermissions,sessionManager:T,agentPresenceBroadcaster:D,resolveEmbed:y.resolveEmbed,isExcludedPath:e=>y.contentFilter.isExcluded(e),isIgnoredPath:e=>y.contentFilter.isPathIgnored(e),getLoadedDocText:e=>b.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ne(),getMcpStdioCommand:()=>yE(e.localOpCliArgs,O,{log:n}),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,probePiAcpBridge:e.probePiAcpBridge,ensurePiAcpBridge:e.ensurePiAcpBridge,log:n});se!==null&&await se.init();let ce=`pending`;S.then(()=>{ce=`ready`},()=>{ce=`failed`});let le=G6({httpServer:ie,hocuspocus:b,nativeApi:y.nativeApi,mcpHttpHandler:re,ingressPolicy:a,health:{readiness:()=>ce,degraded:()=>C},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:D,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:ae,reactShellMiddleware:oe,ephemeral:e.ephemeral,acpThreadManager:se}),ue=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)};v=TZ(ie);let de=null;if(e.idleShutdownMs!==null){let t=e.idleShutdownMs??18e5,r=e.idleShutdownHandler??(e=>async()=>{await e()});de=EZ({httpServer:ie,counter:v,thresholdMs:t,log:n,onShutdown:r(async()=>{await ue(`idle-shutdown`)})})}await j9({hocuspocus:b,projectDir:e.projectDir??e.contentDir,log:n});let fe=[...new Set(i)],pe=fe[0],me=async()=>{await x().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(w)},he=(e,t,n)=>new Promise((r,i)=>{let a=e=>i(e);e.once(`error`,a),e.listen(t,n,()=>{e.removeListener(`error`,a),r()})});try{await he(ie,e.port??0,pe??`127.0.0.1`)}catch(e){throw await me(),e}let ge=ie.address(),_e=typeof ge==`object`&&ge?ge.port:e.port??0,ve=[];for(let e of fe.slice(1)){let t=c();t.headersTimeout=ie.headersTimeout,t.requestTimeout=ie.requestTimeout;for(let e of ie.listeners(`request`))t.on(`request`,e);for(let e of ie.listeners(`upgrade`))t.on(`upgrade`,e);try{await he(t,_e,e)}catch(t){n.error({err:t,failedAddress:e,port:_e,alreadyBound:ve.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ve,ie])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await me(),t}ve.push(t)}let ye=uR();ye!==void 0&&dR(`httpListenMs`,ye);let be=ie.address(),xe=typeof be==`object`&&be?be.port:e.port??0;O=xe;let Se=ne();d(w,xe,Se),n.info({event:`server-listening`,pid:process.pid,port:xe,addresses:fe,url:Se,lockDir:w},`[boot] listening on ${Se}`);let Ce=!1,we=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${A9}ms`))},A9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};ue=async(e=`unspecified`)=>{if(Ce)return;Ce=!0,n.info({reason:e,pid:process.pid,lockDir:w},`[server] shutdown initiated (${e})`),ce=`draining`;let t=[],r=async(e,r)=>{try{await we(e,r)}catch(r){t.push(r),n.warn({err:r,step:e},`bootServer destroy step failed`)}};try{l(w)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{v?.detach()}catch(e){n.warn({err:e,step:`collabClientCounter.detach`},`bootServer destroy step failed`)}try{de?.detach()}catch(e){t.push(e),n.warn({err:e,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(se!==null&&await r(`acpThreads.destroy`,()=>se.destroy()),await r(`secondaryListeners.close`,async()=>{for(let e of ve)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await r(`mount.shutdown`,()=>le.shutdown()),re!==void 0&&await r(`mcpHttpHandler.close`,()=>re.close()),await r(`mount.wss.close`,()=>new Promise((e,t)=>{le.wss.close(n=>n?t(n):e())})),await r(`httpServer.closeAllConnections`,async()=>{ie.closeAllConnections?.()}),await r(`httpServer.close`,()=>new Promise((e,t)=>{ie.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await r(`destroyHocuspocus`,()=>x()),await r(`shutdownTelemetry`,()=>lc()),await r(`teardownToleranceTelemetry`,()=>k9()),await r(`flushLogFileSinks`,()=>fc.flushAllFileSinks()),t.length>0)throw AggregateError(t,`bootServer destroy completed with errors`)};try{let t=await _9({projectDir:p,skillsRoot:V(e.contentDir,`.ok`,`skills`),inPlaceNames:g9(e.contentDir,MF(e.contentDir))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`store-skill-migration-failed`},`Store-skill in-place migration failed (non-fatal).`)}try{let e=Nu(),t=await _9({projectDir:e,skillsRoot:V(e,`.ok`,`skills`),hostRoots:qIe,inPlaceNames:g9(e,NF(e))});t.migrated.length+t.skipped.length>0&&n.info?.({event:`global-store-skills-migrated-in-place`,migrated:t.migrated,skipped:t.skipped},`Migrated ${t.migrated.length} global store skill(s) in place (${t.skipped.length} skipped).`)}catch(e){n.warn?.({err:e,event:`global-store-skill-migration-failed`},`Global store-skill in-place migration failed (non-fatal).`)}try{let t=await iLe({projectDir:p,skillsRoot:V(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ie,destroy:ue,lockDir:w,contentDir:e.contentDir,port:xe,ready:S,generatedIndexSweepReady:y.generatedIndexSweepReady,degraded:C,didAutoInit:f,serverInstance:y,runtime:mNe(y,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:se}}async function j9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new SZ(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=fd(n),t=e?z(e,`MERGE_HEAD`):null;if(!t||!U(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=jte({baseDir:n,timeout:{block:5e3}});s=new Set(await Ab(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=Ax(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 dLe=Jo;function fLe(e={}){let t=e.home??Nu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?U(z(t,`Library`,`Application Support`,`Claude`)):n===`win32`?U(z(r.APPDATA??z(t,`AppData`,`Roaming`),`Claude`)):!1}var M9=t(Ote(),1);const N9=z(Nu(),`.ok`,`logs`),pLe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function mLe(){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 hLe(e){yu(e,{recursive:!0})}function P9(){return new Date().toISOString().slice(0,10)}function gLe(e){try{if(ku(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{Eu(n,r)}catch{}}try{Au(`${e}.3`)}catch{}}function _Le(e){try{let t=Date.now(),n=10080*60*1e3,r=wu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ku(z(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{Au(z(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{Au(z(e,t.name)),a-=t.size}catch{}}}catch{}}function vLe(e){hLe(N9);let t=P9(),n=e.filePath??z(N9,`${e.name}.${t}.log`);gLe(n),(e._setTimeout??setTimeout)(()=>_Le(N9),5e3).unref();let r=M9.default.destination({dest:n,append:!0,sync:!0});return(0,M9.default)({level:mLe(),name:e.name,redact:{paths:pLe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:M9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function yLe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[M9.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 bLe(e){return z(N9,`${e}.${P9()}.log`)}function F9(){return N9}function xLe(e){let t=V(e),n=0;for(;n<30;){let e=!1;try{e=U(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 I9=ed($l),L9=L(`project-git`);var R9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function SLe(e,t){try{return await I9(e,[`var`,`GIT_COMMITTER_IDENT`],uw({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function CLe(e,t){try{let{stdout:n}=await I9(e,[`for-each-ref`,`--count=1`,`refs/`],uw({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return L9.warn({path:t,stderr:z9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function wLe(e){let t=V(e,`packed-refs`);if(U(t))try{if(W(t,`utf-8`).split(`
2043
2043
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return wu(V(e,`refs/heads`)).length>0}catch{return!1}}function z9(e){let t=typeof e==`object`&&e?e:null,n=t?.stderr;return n==null?String(t?.message??e):Buffer.isBuffer(n)?n.toString(`utf-8`):String(n)}async function B9(e,t){if(await CLe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await SLe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await I9(e,i,uw({cwd:t,encoding:`utf-8`})),r||L9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){L9.warn({path:t,stderr:z9(e)},`could not create initial commit`)}}async function TLe(e,t){try{let{stdout:n}=await I9(e,[`rev-parse`,`--is-inside-work-tree`],uw({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function ELe(e){let t=V(e);_K(t);let n=V(t,`.git`),r=V(n,`HEAD`),i=!1,a=!1;if(U(n)){if(!ku(n).isDirectory())return{didInit:!1};if(U(r)){if(wLe(n))return{didInit:!1};a=!0}else L9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=gw()}catch(e){throw e instanceof pw||e instanceof mw?(VJ(e),L9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof mw?`too_old`:`not_available`,detectedVersion:e instanceof mw?e.detected:``},e instanceof mw?`git binary too old`:`git binary not found`)):L9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await B9(s,t),{didInit:!1};if(!i&&await TLe(s,t))return{didInit:!1};let c=``;try{c=(await I9(s,[`init`,`--initial-branch=main`,t],uw({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new R9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!U(r))throw new R9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await B9(s,t),i?(L9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(L9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const V9=L(`project-skill-git`),H9=/^[0-9a-f]{40}$/,DLe=jr.map(e=>e.replace(/\/$/,``));async function OLe(e){let t=fd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(MLe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=vc(e,{credentialConfig:[]});if((await U9(n)).length===0)return{kind:`nothing-tracked`};try{return await _c(async()=>{let t=await kLe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await ALe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await U9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=vc(e,{gitIndexFile:z(Iu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`),credentialConfig:[]});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await jLe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await DL(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;xc(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 \`${Ta}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!H9.test(f))return V9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return V9.info({branch:t,err:W9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){V9.info({err:W9(e)},`real-index reset after untrack failed (cosmetic)`)}return V9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:W9(e)}}}async function U9(e){let t=[];for(let n of DLe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function kLe(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 ALe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return H9.test(t)?t:null}catch{return null}}async function jLe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return H9.test(n)?n:null}catch{return null}}function MLe(e){return U(z(e,`MERGE_HEAD`))||U(z(e,`rebase-merge`))||U(z(e,`rebase-apply`))||U(z(e,`CHERRY_PICK_HEAD`))||U(z(e,`REVERT_HEAD`))}function W9(e){return e instanceof Error?e.message:String(e)}async function NLe(e,t){let n;try{n=Ql(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(U(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 PLe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function G9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of PLe)t=t.replace(e,n);return t}function K9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:G9(e.message)??``,stack:G9(e.stack),code:e.code,cause:e.cause===void 0?void 0:K9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:G9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:G9(String(r.message??``))??``,stack:G9(r.stack),code:r.code,cause:r.cause===void 0?void 0:K9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var q9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},J9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},Y9=class extends Error{constructor(e,t){super(`Cannot open with --project ${e}: ${t}`),this.projectRoot=e,this.name=`SingleFileProjectOverrideError`}},X9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function FLe(e,t={}){if(!Ox(e))throw new X9(e);let n;try{n=G(V(e))}catch(t){throw t.code===`ENOENT`?new q9(e):t}if(!ku(n).isFile())throw new J9(e);let r=R(n);if(t.projectRoot!==void 0){let e=V(t.projectRoot);if(!qj(e))throw new Y9(e,`no .ok/config.yml there, so it is not an OpenKnowledge project root`);let r=B(Z9(e),n);if(r.startsWith(`..`)||ou(r))throw new Y9(e,`${n} is not inside that project's content directory`);return{mode:`project`,projectRoot:e,docName:Ax(r.split(H).join(`/`)),canonicalFilePath:n}}let i=Jj(r);if(i){let e=i.rootPath;return{mode:`project`,projectRoot:e,docName:Ax(B(Z9(e),n).split(H).join(`/`)),canonicalFilePath:n}}let a=ru(n);return{mode:`ephemeral`,canonicalFilePath:n,contentDir:r,singleDocRelPath:a,docName:Ax(a)}}function Z9(e){return V(e,Hs({absPath:Rs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}const Q9=`ok-ephemeral-`;function $9(e,t){let n=V(e,`.ok`);return yu(n,{recursive:!0}),ju(V(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(t)}\n`,`utf-8`),ju(V(n,`.gitignore`),`local/
2044
2044
  `,`utf-8`),e}function ILe(e){return $9(bu(V(Iu(),Q9)),e)}export{D6 as $,Qx as $i,BI as $n,kk as $r,_q as $t,C7 as A,Nd as Aa,Ew as Ai,PL as An,Fpe as Ar,lZ as At,X5 as B,uw as Bi,tL as Bn,gpe as Br,sye as Bt,O9 as C,zb as Ca,AD as Ci,mK as Cn,fP as Cr,dZ as Ct,a9 as D,sh as Da,bE as Di,IL as Dn,dN as Dr,fZ as Dt,o9 as E,ah as Ea,AE as Ei,gK as En,uN as Er,pZ as Et,y7 as F,Ad as Fa,gw as Fi,jL as Fn,eN as Fr,Oxe as Ft,I5 as G,aw as Gi,_L as Gn,nA as Gr,LJ as Gt,sFe as H,ow as Hi,hL as Hn,qj as Hr,VJ as Ht,p7 as I,pd as Ia,Tw as Ii,AL as In,tN as Ir,oZ as It,G6 as J,kC as Ji,QI as Jn,jk as Jr,Hq as Jt,K6 as K,XC as Ki,EL as Kn,lA as Kr,zq as Kt,u7 as L,ad as La,hw as Li,XI as Ln,ZM as Lr,iZ as Lt,x7 as M,Md as Ma,pw as Mi,VL as Mn,aN as Mr,AX as Mt,w7 as N,gd as Na,mw as Ni,zL as Nn,iN as Nr,kX as Nt,G7 as O,oh as Oa,uE as Oi,RL as On,fN as Or,Vxe as Ot,T7 as P,hd as Pa,dw as Pi,ML as Pn,nN as Pr,Dxe as Pt,L6 as Q,aS as Qi,RI as Qn,Dk as Qr,h_e as Qt,J5 as R,xw as Ri,vL as Rn,QM as Rr,PX as Rt,j9 as S,Kb as Sa,Ofe as Si,kK as Sn,sP as Sr,gZ as St,k9 as T,cae as Ta,jE as Ti,hK as Tn,TN as Tr,uZ as Tt,H5 as U,cw as Ui,uL as Un,Fj as Ur,aye as Ut,Y5 as V,GC as Vi,yL as Vn,Jj as Vr,BJ as Vt,z5 as W,iw as Wi,eL as Wn,Pj as Wr,iye as Wt,H6 as X,oS as Xi,cge as Xn,Sk as Xr,Vq as Xt,W6 as Y,UC as Yi,HI as Yn,Ek as Yr,Bq as Yt,B6 as Z,J as Zi,LI as Zn,Ak as Zr,Iq as Zt,bLe as _,xx as _a,BD as _i,DK as _n,VP as _r,GSe as _t,Y9 as a,Cx as aa,RO as ai,oq as an,QP as ar,P0 as at,dLe as b,Xb as ba,Dfe as bi,OK as bn,TP as br,TZ as bt,$9 as c,gx as ca,AO as ci,pq as cn,rhe as cr,ETe as ct,OLe as d,lx as da,lO as di,dq as dn,HP as dr,S0 as dt,Ux as ea,Ok as ei,hq as en,zI as er,B0 as et,R9 as f,px as fa,cO as fi,cq as fn,UP as fr,y0 as ft,yLe as g,bx as ga,qD as gi,EK as gn,Yme as gr,YQ as gt,vLe as h,Sx as ha,GD as hi,vK as hn,zP as hr,_$ as ht,X9 as i,Hx as ia,LO as ii,fq as in,mI as ir,zTe as it,E7 as j,Ud as ja,Ow as ji,BL as jn,rN as jr,sZ as jt,b7 as k,Hd as ka,yE as ki,Lge as kn,lN as kr,hZ as kt,K9 as l,dx as la,NO as li,uq as ln,qP as lr,DTe as lt,xLe as m,sx as ma,JD as mi,ZK as mn,BP as mr,V1 as mt,J9 as n,Wx as na,rk as ni,c_e as nn,OI as nr,H0 as nt,ILe as o,mx as oa,FO as oi,sq as on,XP as or,N0 as ot,ELe as p,wx as pa,uO as pi,XK as pn,WP as pr,x0 as pt,q6 as q,OC as qi,gL as qn,Gk as qr,Rq as qt,q9 as r,Jx as ra,hk as ri,o_e as rn,vI as rr,q0 as rt,FLe as s,hx as sa,PO as si,s_e as sn,che as sr,O0 as st,Q9 as t,Yx as ta,nk as ti,nq as tn,PI as tr,V0 as tt,NLe as u,vx as ua,MO as ui,lq as un,GP as ur,OTe as ut,F9 as v,Tx as va,VD as vi,SK as vn,EP as vr,u$ as vt,D9 as w,gce as wa,ME as wi,_K as wn,aP as wr,mZ as wt,lLe as x,Jb as xa,HD as xi,bK as xn,CP as xr,EZ as xt,fLe as y,ix as ya,LD as yi,jK as yn,wP as yr,p$ as yt,yFe as z,vw as zi,nL as zn,TM as zr,UJ as zt};
2045
- //# sourceMappingURL=src-C_6FcYaw.mjs.map
2045
+ //# sourceMappingURL=src-DoNjy6J-.mjs.map