@inkeep/open-knowledge 0.59.0-beta.35 → 0.59.0-beta.37

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 (130) hide show
  1. package/dist/{acp-harness-probe-vsGUe6qp.mjs → acp-harness-probe-CBrm8Uc5.mjs} +2 -2
  2. package/dist/assets/skills/discovery/SKILL.md +8 -2
  3. package/dist/assets/skills/project/SKILL.md +8 -0
  4. package/dist/cli.mjs +6 -6
  5. package/dist/constants-CfAYwClm.mjs +2 -0
  6. package/dist/{git-handle-CB29jOi9.mjs → git-handle-BkSalb6i.mjs} +2 -2
  7. package/dist/git-handle-DaYxKcxM.mjs +1 -0
  8. package/dist/index.d.mts +2 -0
  9. package/dist/index.mjs +180 -180
  10. package/dist/init-JuSYS7tV.mjs +1 -0
  11. package/dist/{init-r0YtTtfz.mjs → init-k56XGq0P.mjs} +3 -3
  12. package/dist/{launch-json-removal-Om4i-L6S.mjs → launch-json-removal-DKrnmBtd.mjs} +2 -2
  13. package/dist/loader-BFene3YR.mjs +1 -0
  14. package/dist/{loader-CR3h5Mju.mjs → loader-D2mUeyWr.mjs} +2 -2
  15. package/dist/md-manager-_lKMHY2F.mjs +2 -0
  16. package/dist/{open-browser-Buuo3P-E.mjs → open-browser-CldvWM5B.mjs} +2 -2
  17. package/dist/parse-worker.mjs +1 -1
  18. package/dist/preview-3H89Af5-.mjs +1 -0
  19. package/dist/{preview-BT3Oifm5.mjs → preview-P1fUYVKl.mjs} +2 -2
  20. package/dist/public/assets/{ActivityModeContent-ZMkynbjt.js → ActivityModeContent-CPVWFbUj.js} +1 -1
  21. package/dist/public/assets/{AgentDiffPane-B8nC1KUO.js → AgentDiffPane-vKHDjrFP.js} +1 -1
  22. package/dist/public/assets/{AgentThreadClientBinder-B0Tnmc_C.js → AgentThreadClientBinder-DuflAOYp.js} +1 -1
  23. package/dist/public/assets/{CodeMirrorPropInput-D7nB1aDJ.js → CodeMirrorPropInput-zWNXj-An.js} +1 -1
  24. package/dist/public/assets/{DocumentContext-DK6WjZtm.js → DocumentContext-DZbxXv6H.js} +1 -1
  25. package/dist/public/assets/{EditorModeToggle-Bw3g_RS7.js → EditorModeToggle-DabSiY81.js} +1 -1
  26. package/dist/public/assets/{EnableSyncConfirmDialog-D6G6yrqT.js → EnableSyncConfirmDialog-BqkxgRaX.js} +1 -1
  27. package/dist/public/assets/{ExcalidrawDocEditor-BUL0FNWm.js → ExcalidrawDocEditor-CIIPYb0V.js} +1 -1
  28. package/dist/public/assets/FeedbackForm-DTsymupO.js +1 -0
  29. package/dist/public/assets/{GraphPanel-Cxz5VYMl.js → GraphPanel-CDq6Cn96.js} +1 -1
  30. package/dist/public/assets/{ImportSkillDialog-Eb3L_zjp.js → ImportSkillDialog-6I-tdfnK.js} +1 -1
  31. package/dist/public/assets/{LintConfigEditor-DfvsohvN.js → LintConfigEditor-iIARYye7.js} +1 -1
  32. package/dist/public/assets/ManagedArtifactProperties-3se1RZmj.js +1 -0
  33. package/dist/public/assets/{ManagedArtifactProperties-BmksuBSn.js → ManagedArtifactProperties-BPyzZkdV.js} +1 -1
  34. package/dist/public/assets/{MermaidDocEditor-QByjyMzX.js → MermaidDocEditor-DxoJLmGh.js} +1 -1
  35. package/dist/public/assets/{PropertyDisplayRow-CE9D0uq8.js → PropertyDisplayRow-fMZKhF3_.js} +1 -1
  36. package/dist/public/assets/{ReportBugDialogBody-BY7Mi1BQ.js → ReportBugDialogBody-Bkfnn8Pd.js} +1 -1
  37. package/dist/public/assets/{SchemaConfigEditor-vZ4Iznw7.js → SchemaConfigEditor-fFuUGFGN.js} +1 -1
  38. package/dist/public/assets/{SessionsHost-p4B3j2uq.js → SessionsHost-pFFD0VSW.js} +2 -2
  39. package/dist/public/assets/{SettingsDialogBody-CzOL2SRu.js → SettingsDialogBody-CqJssURh.js} +1 -1
  40. package/dist/public/assets/{ShareBranchSwitchDialog-Dyzc83GK.js → ShareBranchSwitchDialog-t6-lKq1l.js} +1 -1
  41. package/dist/public/assets/{ShareReceiveDialog-CtF5U57_.js → ShareReceiveDialog-LuA8x7YC.js} +1 -1
  42. package/dist/public/assets/{ShareReceiveMissDialog-D4TxU2FH.js → ShareReceiveMissDialog-D8ADRN91.js} +1 -1
  43. package/dist/public/assets/{SkillCostValue-B9rxsZZe.js → SkillCostValue-CGcui9JR.js} +1 -1
  44. package/dist/public/assets/{SkillEditBanner-Btv3scxq.js → SkillEditBanner-CNTikXwl.js} +1 -1
  45. package/dist/public/assets/{SkillInstallMenu-Djr9cLyQ.js → SkillInstallMenu-Cpjl7OIH.js} +1 -1
  46. package/dist/public/assets/{SkillOriginInline-CVtmqSId.js → SkillOriginInline-CXj10KzG.js} +1 -1
  47. package/dist/public/assets/{SkillToolbarControls-NDRzmFvN.js → SkillToolbarControls-Cfi6OPhq.js} +1 -1
  48. package/dist/public/assets/{SlidesToolbarControls-BUZLwCo9.js → SlidesToolbarControls-DIQu0p-H.js} +1 -1
  49. package/dist/public/assets/{SourceEditor-D280BxeC.js → SourceEditor-CqiFwBMC.js} +1 -1
  50. package/dist/public/assets/{TerminalPanel-B2eMtg9W.js → TerminalPanel-BqbCRTNn.js} +1 -1
  51. package/dist/public/assets/{TerminalWindowApp-DiFRQ0Wj.js → TerminalWindowApp-Pv-VOJ0w.js} +1 -1
  52. package/dist/public/assets/{TextDocEditor-B19eo9Zu.js → TextDocEditor-Bw-f5mNN.js} +1 -1
  53. package/dist/public/assets/{ThreadView-DuWlmKjj.js → ThreadView-CLESX5dJ.js} +1 -1
  54. package/dist/public/assets/{TimelineDiffPane-iZl0xaNU.js → TimelineDiffPane-NUKr4hbw.js} +1 -1
  55. package/dist/public/assets/{agent-diff-store-d13OQwxA.js → agent-diff-store-sEwMOwXy.js} +1 -1
  56. package/dist/public/assets/{auth-state-cache-CE_bMumR.js → auth-state-cache-Cb7mdO-H.js} +1 -1
  57. package/dist/public/assets/{client-version-BnANtuGb.js → client-version-BSiKYSme.js} +1 -1
  58. package/dist/public/assets/{comment-chips-DxWHm9Cs.js → comment-chips-C8RgEJKK.js} +1 -1
  59. package/dist/public/assets/{config-provider-KCmXGgSj.js → config-provider-Cm5WhzR7.js} +1 -1
  60. package/dist/public/assets/{dist-C7FVgQnF2.js → dist-D-pIxpOA2.js} +1 -1
  61. package/dist/public/assets/{doc-paths-RsoaUvtD.js → doc-paths-je9IlWgC.js} +1 -1
  62. package/dist/public/assets/{documents-events-CsY1UHz_.js → documents-events-Dv0-c6Gq.js} +1 -1
  63. package/dist/public/assets/{file-tree-adapter-VJviIUhC.js → file-tree-adapter-BcQxnXAE.js} +1 -1
  64. package/dist/public/assets/{file-tree-utils-CFgZ2Cn3.js → file-tree-utils-DaZREteD.js} +1 -1
  65. package/dist/public/assets/{folder-config-api-C9BPoMvu.js → folder-config-api-CWvrN8lP.js} +1 -1
  66. package/dist/public/assets/i18n-BaCTU6Zh.js +1 -0
  67. package/dist/public/assets/{index-BT38n3zl.js → index-Cn_Zo_-J.js} +7 -7
  68. package/dist/public/assets/{lint-config-client-B7E69j5g.js → lint-config-client-DKa5fmfG.js} +1 -1
  69. package/dist/public/assets/{markdownlint-rule-browser--Z9pkvK3.js → markdownlint-rule-browser-r1KXGJzZ.js} +1 -1
  70. package/dist/public/assets/{navigation-targets-xthiKVG-.js → navigation-targets-D-ukZJM0.js} +1 -1
  71. package/dist/public/assets/{open-managed-artifact-tab-BSvOi_H-.js → open-managed-artifact-tab-Dz-XpKZV.js} +1 -1
  72. package/dist/public/assets/{pending-receive-nav-store-eivLgf-S.js → pending-receive-nav-store-BIWb4fW2.js} +1 -1
  73. package/dist/public/assets/{progress-BzUYuL-V.js → progress-DN5ZVmeh.js} +1 -1
  74. package/dist/public/assets/{prop-types-Cy2A7TPC.js → prop-types-CYiFLB9V.js} +1 -1
  75. package/dist/public/assets/{receive-store-CtzFhr6S.js → receive-store-C4Bb5kEd.js} +1 -1
  76. package/dist/public/assets/{selection-context-gHo_9Fbo.js → selection-context-GAipzi1C.js} +1 -1
  77. package/dist/public/assets/{skill-actions-DtcJ1SJd.js → skill-actions-CwEwwoQa.js} +1 -1
  78. package/dist/public/assets/{skill-scope-Bua0nDSa.js → skill-scope-MvvK5VaZ.js} +1 -1
  79. package/dist/public/assets/{skills-api-D08ihk2a.js → skills-api-DSiZ01ML.js} +1 -1
  80. package/dist/public/assets/{src-NjVFjnQM.js → src-Cxbc-uJu.js} +1 -1
  81. package/dist/public/assets/{tag-pill-input-BilmKPUq.js → tag-pill-input-DLu1afux.js} +1 -1
  82. package/dist/public/assets/{target-navigation-intent-7U-MrZdc.js → target-navigation-intent-6yA5JFaJ.js} +1 -1
  83. package/dist/public/assets/{terminal-cli-display-C2erLHKw.js → terminal-cli-display-BYsImxHL.js} +1 -1
  84. package/dist/public/assets/{terminal-launch-events-CKR4fyca.js → terminal-launch-events-weVUvN2D.js} +1 -1
  85. package/dist/public/assets/{terminal-telemetry-DVJphneI.js → terminal-telemetry-BdGxgj0Q.js} +1 -1
  86. package/dist/public/assets/{typing-burst-detector-CgfR26-J.js → typing-burst-detector-CnrmNGX4.js} +1 -1
  87. package/dist/public/assets/{uninstall-ZTgWvcqD.js → uninstall-DB1pYf9F.js} +1 -1
  88. package/dist/public/assets/{use-activity-panel-D-Xmd1zX.js → use-activity-panel-BOZG8akM.js} +1 -1
  89. package/dist/public/assets/{use-apply-config-color-theme-BBRWSHcW.js → use-apply-config-color-theme-Kky-EB37.js} +1 -1
  90. package/dist/public/assets/{use-collab-url-DElOWqQi.js → use-collab-url-B8CCNpkf.js} +1 -1
  91. package/dist/public/assets/{use-live-xterm-theme-JuPkRnhw.js → use-live-xterm-theme-aATfBST5.js} +1 -1
  92. package/dist/public/assets/{use-open-skill-Cwhk0mI6.js → use-open-skill-CRdMHw50.js} +1 -1
  93. package/dist/public/assets/{use-popular-skills-C4zNnQqG.js → use-popular-skills-BSlbkBjx.js} +1 -1
  94. package/dist/public/assets/{use-settings-route-BBLR_URX.js → use-settings-route-B0SXlDtB.js} +1 -1
  95. package/dist/public/assets/{use-skill-origin-BYWnSATz.js → use-skill-origin-QuR6e3Vu.js} +1 -1
  96. package/dist/public/assets/{use-terminal-enabled-QPWQYOg5.js → use-terminal-enabled-Cwmb5Ljb.js} +1 -1
  97. package/dist/public/assets/{use-timeline-entry-diff-BcxlAt36.js → use-timeline-entry-diff-DnoIkq-D.js} +1 -1
  98. package/dist/public/assets/{use-workspace-uY_J8IXy.js → use-workspace-CTA6IT0U.js} +1 -1
  99. package/dist/public/index.html +45 -45
  100. package/dist/public/uninstall.html +3 -3
  101. package/dist/{repair-launch-json-DNtAoYuK.mjs → repair-launch-json-a7Z3fyff.mjs} +2 -2
  102. package/dist/{repair-mcp-configs-CE3qqMQw.mjs → repair-mcp-configs-BDw1EAI6.mjs} +2 -2
  103. package/dist/repair-skills-CS2_jKX3.mjs +1 -0
  104. package/dist/{repair-skills-BsBXroSe.mjs → repair-skills-DdLknuYw.mjs} +2 -2
  105. package/dist/{resolve-project-root-BCtyt-M3.mjs → resolve-project-root-CHFE5Tp7.mjs} +2 -2
  106. package/dist/server-lock-BZi8m82Z.mjs +1 -0
  107. package/dist/{server-lock-B3DaXpD-.mjs → server-lock-RKPNHNqb.mjs} +2 -2
  108. package/dist/{skill-teardown-CEOCC6te.mjs → skill-teardown-DcAF7q_b.mjs} +2 -2
  109. package/dist/src-132xmrlg.mjs +20 -0
  110. package/dist/{src-DM9JDHjF.mjs → src-BD1wHyiU.mjs} +132 -132
  111. package/dist/{src-3c-GN0Vv.mjs → src-CKvbaaFV.mjs} +4 -4
  112. package/dist/{src-BReyc6U1.mjs → src-nk8WfDCB.mjs} +1 -1
  113. package/dist/src-ptD290kA.mjs +1 -0
  114. package/dist/start-CsSD9ES3.mjs +1 -0
  115. package/dist/{start-DJZtRPBb.mjs → start-DsahtpGy.mjs} +3 -3
  116. package/package.json +4 -4
  117. package/dist/constants-ZaRc-oTU.mjs +0 -2
  118. package/dist/git-handle-Ci-ka9U-.mjs +0 -1
  119. package/dist/init-IRj6tWLS.mjs +0 -1
  120. package/dist/loader-BUmJVdvY.mjs +0 -1
  121. package/dist/md-manager-V3jbnXEF.mjs +0 -2
  122. package/dist/preview-9ouAo77k.mjs +0 -1
  123. package/dist/public/assets/FeedbackForm-DW0x7yxI.js +0 -1
  124. package/dist/public/assets/ManagedArtifactProperties-lJ8wwEp2.js +0 -1
  125. package/dist/public/assets/i18n-CxTgngSa.js +0 -1
  126. package/dist/repair-skills-K7CwEUhi.mjs +0 -1
  127. package/dist/server-lock-DEUsqKAE.mjs +0 -1
  128. package/dist/src-B-ikueq5.mjs +0 -1
  129. package/dist/src-DdFbH19m.mjs +0 -20
  130. package/dist/start-BU-5d7w8.mjs +0 -1
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,A as i,At as a,B as o,Bt as s,C as c,Ct as l,Dt as u,Et as d,F as f,Ft as p,Gt as m,H as h,Ht as g,I as _,It as v,Jt as y,Kt as b,L as x,Lt as S,M as C,Mt as w,N as T,Nt as E,P as ee,Pt as te,Q as ne,Qt as re,R as ie,Rt as D,S as O,St as k,T as ae,Tt as oe,Vt as se,Xt as ce,Yt as le,Zt as ue,a as de,at as fe,bt as A,d as pe,dt as me,en as he,ft as ge,gt as _e,ht as ve,i as ye,it as be,jt as j,kt as M,lt as xe,m as Se,nn as Ce,o as we,ot as Te,p as Ee,pt as De,qt as Oe,s as ke,st as Ae,t as je,tn as Me,tt as Ne,ut as Pe,vt as Fe,w as Ie,wt as Le,x as Re,yt as ze,zt as Be}from"./sleep-DhRrtbfG.mjs";import{$ as Ve,$a as He,$i as Ue,$n as We,$r as Ge,$s as Ke,$t as qe,A as Je,Aa as Ye,Ai as Xe,An as Ze,Ao as Qe,Ar as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Cc as dt,Ci as ft,Cn as pt,Co as mt,Cr as ht,Ct as gt,D as _t,Da as vt,Di as yt,Dn as bt,Do as xt,Dr as St,Ds as Ct,Dt as wt,E as Tt,Ea as Et,Ei as Dt,En as Ot,Eo as kt,Er as At,Et as jt,F as Mt,Fa as Nt,Fi as Pt,Fn as Ft,Fo as It,Fr as Lt,Fs as Rt,Ft as zt,G as Bt,Ga as Vt,Gi as Ht,Gn as Ut,Gr as Wt,Gs as Gt,Gt as Kt,H as qt,Ha as Jt,Hi as Yt,Hn as Xt,Ho as Zt,Hr as Qt,Hs as $t,Ht as en,I as tn,Ia as nn,Ii as rn,In as an,Io as on,Ir as eee,Is as sn,It as cn,J as tee,Ja as ln,Ji as un,Jn as nee,Jo as dn,Jr as ree,Js as fn,Jt as pn,K as mn,Ka as iee,Ki as hn,Kn as gn,Ko as aee,Kr as _n,Ks as vn,Kt as yn,L as bn,La as oee,Li as xn,Ln as Sn,Lo as Cn,Lr as wn,Ls as Tn,Lt as En,M as Dn,Ma as see,Mi as On,Mn as cee,Mo as lee,Mr as uee,Ms as kn,Mt as An,N as jn,Na as Mn,Ni as Nn,Nn as dee,No as Pn,Nr as fee,Ns as Fn,Nt as In,O as Ln,Oa as pee,Oc as Rn,Oi as zn,On as Bn,Oo as mee,Or as hee,Os as Vn,Ot as Hn,P as Un,Pa as Wn,Pi as Gn,Pn as Kn,Po as gee,Pr as _ee,Pt as qn,Q as Jn,Qa as Yn,Qi as Xn,Qn as Zn,Qr as vee,Qt as Qn,R as yee,Ra as bee,Ri as $n,Rn as xee,Ro as See,Rr as Cee,Rt as er,S as tr,Sa as nr,Sc as rr,Si as wee,Sn as ir,So as Tee,Sr as Eee,Ss as ar,St as or,T as sr,Ta as Dee,Tc as cr,Ti as lr,Tn as ur,To as dr,Tr as fr,Ts as pr,Tt as mr,U as hr,Ua as gr,Ui as _r,Un as vr,Uo as yr,Ur as br,Us as xr,V as Sr,Va as Cr,Vi as wr,Vn as Tr,Vo as Er,Vr as Dr,Vs as Or,Vt as kr,W as Ar,Wa as Oee,Wi as jr,Wn as Mr,Wo as Nr,Wr as Pr,X as kee,Xa as Fr,Xi as Ir,Xn as Aee,Xr as jee,Xs as Lr,Xt as Rr,Y as Mee,Ya as zr,Yi as Br,Yn as Nee,Yo as Vr,Yr as Pee,Ys as Hr,Yt as Ur,Za as Wr,Zi as Gr,Zn as Fee,Zo as Kr,Zr as Iee,Zs as qr,Zt as Jr,_ as Yr,_a as Xr,_i as Lee,_n as Ree,_o as Zr,_r as zee,_s as Qr,_t as $r,a as ei,aa as ti,ac as ni,ai as ri,an as ii,ao as ai,ar as Bee,as as oi,at as si,b as ci,ba as li,bi as ui,bn as di,br as fi,bs as pi,bt as mi,c as hi,ca as gi,cc as _i,ci as vi,cn as yi,co as bi,cr as xi,cs as Si,ct as Ci,d as wi,da as Ti,dc as Ei,di as Di,dn as Oi,dr as ki,ds as Ai,dt as ji,ea as Mi,ec as Ni,ei as Pi,en as Fi,eo as Ii,er as Li,es as Ri,et as zi,f as Bi,fa as Vi,fi as Hi,fn as Vee,fo as Ui,fr as Wi,fs as Gi,ft as Ki,g as qi,ga as Ji,gi as Yi,gn as Hee,go as Xi,gr as Uee,gt as Zi,h as Qi,ha as $i,hc as ea,hi as ta,hn as Wee,ho as na,hr as Gee,hs as ra,ht as ia,i as aa,ia as oa,ic as sa,ii as ca,in as la,io as ua,ir as da,it as fa,j as pa,ja as ma,ji as ha,jn as ga,jo as _a,jr as va,js as ya,jt as ba,k as xa,ka as Sa,ki as Ca,kn as wa,ko as Ta,kr as Ea,ks as Da,kt as Oa,l as ka,la as Aa,lc as ja,li as Ma,ln as Na,lo as Pa,lr as Fa,ls as Ia,m as La,ma as Ra,mc as za,mi as Ba,mn as Va,mo as Ha,mr as Ua,ms as Wa,mt as Ga,n as Ka,na as qa,nc as Ja,ni as Ya,nn as Kee,no as Xa,nr as qee,ns as Za,nt as Qa,o as $a,oa as eo,oc as to,oi as Jee,on as no,oo as ro,or as Yee,os as io,ot as ao,p as oo,pa as so,pc as co,pi as Xee,pn as Zee,po as lo,pr as Qee,ps as uo,pt as fo,qa as $ee,qi as po,qn as ete,qo as mo,qr as tte,qs as ho,qt as go,r as _o,ra as nte,rc as vo,ri as yo,rn as rte,ro as bo,rr as ite,rs as xo,rt as So,s as Co,sa as wo,sc as ate,si as ote,sn as ste,so as To,sr as cte,st as Eo,t as Do,ta as Oo,tc as lte,ti as ko,tn as Ao,to as jo,tr as ute,ts as Mo,tt as No,u as Po,ua as Fo,uc as dte,ui as Io,un as fte,uo as Lo,ur as Ro,v as zo,va as Bo,vi as Vo,vn as pte,vo as Ho,vr as mte,vs as Uo,vt as Wo,w as Go,wa as hte,wc as Ko,wi as qo,wn as gte,wo as Jo,wr as _te,ws as Yo,wt as Xo,x as Zo,xa as Qo,xi as vte,xn as $o,xo as yte,xr as es,xs as ts,xt as ns,y as rs,ya as is,yi as as,yn as bte,yo as os,yr as xte,ys as ss,yt as cs,z as ls,za as Ste,zi as Cte,zn as wte,zo as Tte,zr as Ete,zs as us,zt as ds}from"./src-DM9JDHjF.mjs";import{c as fs,i as ps,l as ms,n as hs,s as gs}from"./esm-DxvI2ZVA.mjs";import{n as _s,t as vs}from"./md-manager-V3jbnXEF.mjs";import{A as ys,C as bs,E as xs,I as Ss,M as Cs,O as ws,P as Ts,S as Es,T as Ds,_ as Os,a as ks,b as As,c as js,d as Ms,f as Ns,g as Ps,h as Fs,i as Is,j as Ls,k as Rs,l as zs,m as Bs,n as Vs,o as Hs,p as Us,r as Ws,s as Gs,t as Ks,u as qs,v as Js,w as Ys,x as Xs,y as Zs}from"./fs-traced-2B_-YK-g.mjs";import{E as Qs,T as $s,a as ec,b as tc,l as nc,p as rc,r as N,s as ic,v as ac,w as oc,x as sc,y as cc}from"./logger-Dq-cRhcP.mjs";import{a as lc,c as uc,i as dc,l as fc,o as pc,r as mc,s as hc,t as gc}from"./git-handle-CB29jOi9.mjs";import{C as _c,S as vc,a as yc,b as bc,d as xc,i as Sc,n as Cc,o as wc,r as Tc,v as Ec,y as Dc}from"./server-lock-B3DaXpD-.mjs";import{t as Oc}from"./libesm-DzwC_yFw.mjs";import{t as kc}from"./yazl-DZr4PyKA.mjs";import{t as Ac}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as jc,c as Mc,d as Nc,f as Pc,h as Fc,i as Ic,l as Lc,m as Rc,n as zc,o as Bc,p as Vc,r as Hc,s as Uc,t as Wc,u as Gc}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as Kc,B as qc,C as Jc,D as Yc,E as Xc,F as Zc,H as Qc,I as $c,L as el,M as tl,N as nl,O as rl,P as il,S as al,T as ol,V as sl,_ as cl,a as ll,b as ul,c as dl,d as fl,f as pl,g as ml,h as hl,i as gl,j as _l,k as vl,l as yl,m as bl,n as xl,o as Sl,p as Cl,r as wl,s as Tl,t as Dte,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 Ote,o as kte,r as Ate,s as Ll,t as jte,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 Mte,t as Nte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as Kl,r as ql,t as Jl}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Pte,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 Fte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as Ql}from"node:module";import{execFile as $l,execFileSync as Ite,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 P,extname as au,isAbsolute as ou,join as F,normalize as su,parse as cu,posix as lu,relative as I,resolve as L,sep as R,win32 as Lte}from"node:path";import{URLSearchParams as Rte,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 z,fstatSync as Bte,lstatSync as vu,mkdirSync as yu,mkdtempSync as bu,openSync as xu,opendirSync as Su,readFile as Vte,readFileSync as B,readSync as Cu,readdirSync as wu,readlinkSync as Tu,realpathSync as V,renameSync as Eu,rmSync as Du,rmdirSync as Ou,statSync as ku,unlinkSync as Au,writeFileSync as ju,writeSync as Hte}from"node:fs";import{arch as Mu,availableParallelism as Ute,homedir as Nu,hostname as Pu,platform as Fu,tmpdir as Iu}from"node:os";import{access as Lu,chmod as Wte,constants as Ru,lstat as zu,readFile as Bu,readdir as Vu,realpath as Hu,stat as Uu,writeFile as Gte}from"node:fs/promises";import{Readable as Wu,Transform as Kte,Writable as qte}from"node:stream";import Gu,{createHash as Ku,randomUUID as qu,webcrypto as Ju}from"node:crypto";import Jte from"crypto";import{Readable as Yu}from"stream";import{EventEmitter as Yte}from"node:events";import{readdirSync as Xte,statSync as Zte}from"fs";import{join as Xu,resolve as Qte}from"path";import{Worker as $te}from"node:worker_threads";import{monitorEventLoopDelay as ene,performance as Zu}from"node:perf_hooks";import{createInterface as tne}from"node:readline";import{pipeline as Qu}from"node:stream/promises";import{setImmediate as nne,setTimeout as $u}from"node:timers/promises";import{promisify as ed}from"node:util";import{request as rne}from"node:http";import{Http2ServerRequest as td,constants as ine}from"node:http2";import{lookup as ane}from"node:dns/promises";import{request as one}from"node:https";import{createBrotliDecompress as sne,createGunzip as cne,createInflate as lne}from"node:zlib";import*as une from"node:querystring";import{Http2ServerRequest as nd,constants as dne}from"http2";import{AsyncLocalStorage as fne}from"node:async_hooks";import{lookup as pne}from"node:dns";import mne 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=B(F(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=ou(t)?t:L(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=B(F(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=B(F(t.path,`config`),`utf-8`)}catch(e){return sd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=hne(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=L(t.path,e),r=I(t.path,n);if(r.startsWith(`..`)||ou(r))return{kind:`invalid`};try{let e=B(n,`utf-8`).trim(),t=vne(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=B(F(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(L(e),``)}function ad(e){let t=L(e),n=L(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=P(i);if(e===i||e===n)return{kind:`absent`};let r=od(e,I(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function od(e,t){let n=F(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=B(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:L(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 hne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=gne(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=_ne(i[1]);if(a.length>0)return a}return null}function gne(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function _ne(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 vne(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 yne(e){return`git-author-${er(e.trim().toLowerCase())}`}const bne=/^(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 L(t.path,md(t.projectSubPath));case`linked`:if(!z(t.path))throw new hd(t.gitPath,t.path);return L(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 L(e,`.git/ok`)}}function md(e){return e===``?`ok`:`ok-${xne(e)}`}function xne(e){let t=e.split(R).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Sne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Sne(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 Cne(e){let t;try{t=pd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return z(L(t,`HEAD`))?t:null}function _d(e){return`refs/wip/${e}/`}function wne(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,A as i,At as a,B as o,Bt as s,C as c,Ct as l,Dt as u,Et as d,F as f,Ft as p,Gt as m,H as h,Ht as g,I as _,It as v,Jt as y,Kt as b,L as x,Lt as S,M as C,Mt as w,N as T,Nt as E,P as ee,Pt as te,Q as ne,Qt as re,R as ie,Rt as D,S as O,St as k,T as ae,Tt as oe,Vt as se,Xt as ce,Yt as le,Zt as ue,a as de,at as fe,bt as A,d as pe,dt as me,en as he,ft as ge,gt as _e,ht as ve,i as ye,it as be,jt as j,kt as M,lt as xe,m as Se,nn as Ce,o as we,ot as Te,p as Ee,pt as De,qt as Oe,s as ke,st as Ae,t as je,tn as Me,tt as Ne,ut as Pe,vt as Fe,w as Ie,wt as Le,x as Re,yt as ze,zt as Be}from"./sleep-DhRrtbfG.mjs";import{$ as Ve,$a as He,$i as Ue,$n as We,$r as Ge,$s as Ke,$t as qe,A as Je,Aa as Ye,Ai as Xe,An as Ze,Ao as Qe,Ar as $e,At as et,B as tt,Ba as nt,Bi as rt,Bn as it,Bo as at,Br as ot,Bs as st,Bt as ct,C as lt,Ca as ut,Cc as dt,Ci as ft,Cn as pt,Co as mt,Cr as ht,Ct as gt,D as _t,Da as vt,Di as yt,Dn as bt,Do as xt,Dr as St,Ds as Ct,Dt as wt,E as Tt,Ea as Et,Ei as Dt,En as Ot,Eo as kt,Er as At,Et as jt,F as Mt,Fa as Nt,Fi as Pt,Fn as Ft,Fo as It,Fr as Lt,Fs as Rt,Ft as zt,G as Bt,Ga as Vt,Gi as Ht,Gn as Ut,Gr as Wt,Gs as Gt,Gt as Kt,H as qt,Ha as Jt,Hi as Yt,Hn as Xt,Ho as Zt,Hr as Qt,Hs as $t,Ht as en,I as tn,Ia as nn,Ii as rn,In as an,Io as on,Ir as eee,Is as sn,It as cn,J as tee,Ja as ln,Ji as un,Jn as nee,Jo as dn,Jr as ree,Js as fn,Jt as pn,K as mn,Ka as iee,Ki as hn,Kn as gn,Ko as aee,Kr as _n,Ks as vn,Kt as yn,L as bn,La as oee,Li as xn,Ln as Sn,Lo as Cn,Lr as wn,Ls as Tn,Lt as En,M as Dn,Ma as see,Mi as On,Mn as cee,Mo as lee,Mr as uee,Ms as kn,Mt as An,N as jn,Na as Mn,Ni as Nn,Nn as dee,No as Pn,Nr as fee,Ns as Fn,Nt as In,O as Ln,Oa as pee,Oc as Rn,Oi as zn,On as Bn,Oo as mee,Or as hee,Os as Vn,Ot as Hn,P as Un,Pa as Wn,Pi as Gn,Pn as Kn,Po as gee,Pr as _ee,Pt as qn,Q as Jn,Qa as Yn,Qi as Xn,Qn as Zn,Qr as vee,Qt as Qn,R as yee,Ra as bee,Ri as $n,Rn as xee,Ro as See,Rr as Cee,Rt as er,S as tr,Sa as nr,Sc as rr,Si as wee,Sn as ir,So as Tee,Sr as Eee,Ss as ar,St as or,T as sr,Ta as Dee,Tc as cr,Ti as lr,Tn as ur,To as dr,Tr as fr,Ts as pr,Tt as mr,U as hr,Ua as gr,Ui as _r,Un as vr,Uo as yr,Ur as br,Us as xr,V as Sr,Va as Cr,Vi as wr,Vn as Tr,Vo as Er,Vr as Dr,Vs as Or,Vt as kr,W as Ar,Wa as Oee,Wi as jr,Wn as Mr,Wo as Nr,Wr as Pr,X as kee,Xa as Fr,Xi as Ir,Xn as Aee,Xr as jee,Xs as Lr,Xt as Rr,Y as Mee,Ya as zr,Yi as Br,Yn as Nee,Yo as Vr,Yr as Pee,Ys as Hr,Yt as Ur,Za as Wr,Zi as Gr,Zn as Fee,Zo as Kr,Zr as Iee,Zs as qr,Zt as Jr,_ as Yr,_a as Xr,_i as Lee,_n as Ree,_o as Zr,_r as zee,_s as Qr,_t as $r,a as ei,aa as ti,ac as ni,ai as ri,an as ii,ao as ai,ar as Bee,as as oi,at as si,b as ci,ba as li,bi as ui,bn as di,br as fi,bs as pi,bt as mi,c as hi,ca as gi,cc as _i,ci as vi,cn as yi,co as bi,cr as xi,cs as Si,ct as Ci,d as wi,da as Ti,dc as Ei,di as Di,dn as Oi,dr as ki,ds as Ai,dt as ji,ea as Mi,ec as Ni,ei as Pi,en as Fi,eo as Ii,er as Li,es as Ri,et as zi,f as Bi,fa as Vi,fi as Hi,fn as Vee,fo as Ui,fr as Wi,fs as Gi,ft as Ki,g as qi,ga as Ji,gi as Yi,gn as Hee,go as Xi,gr as Uee,gt as Zi,h as Qi,ha as $i,hc as ea,hi as ta,hn as Wee,ho as na,hr as Gee,hs as ra,ht as ia,i as aa,ia as oa,ic as sa,ii as ca,in as la,io as ua,ir as da,it as fa,j as pa,ja as ma,ji as ha,jn as ga,jo as _a,jr as va,js as ya,jt as ba,k as xa,ka as Sa,ki as Ca,kn as wa,ko as Ta,kr as Ea,ks as Da,kt as Oa,l as ka,la as Aa,lc as ja,li as Ma,ln as Na,lo as Pa,lr as Fa,ls as Ia,m as La,ma as Ra,mc as za,mi as Ba,mn as Va,mo as Ha,mr as Ua,ms as Wa,mt as Ga,n as Ka,na as qa,nc as Ja,ni as Ya,nn as Kee,no as Xa,nr as qee,ns as Za,nt as Qa,o as $a,oa as eo,oc as to,oi as Jee,on as no,oo as ro,or as Yee,os as io,ot as ao,p as oo,pa as so,pc as co,pi as Xee,pn as Zee,po as lo,pr as Qee,ps as uo,pt as fo,qa as $ee,qi as po,qn as ete,qo as mo,qr as tte,qs as ho,qt as go,r as _o,ra as nte,rc as vo,ri as yo,rn as rte,ro as bo,rr as ite,rs as xo,rt as So,s as Co,sa as wo,sc as ate,si as ote,sn as ste,so as To,sr as cte,st as Eo,t as Do,ta as Oo,tc as lte,ti as ko,tn as Ao,to as jo,tr as ute,ts as Mo,tt as No,u as Po,ua as Fo,uc as dte,ui as Io,un as fte,uo as Lo,ur as Ro,v as zo,va as Bo,vi as Vo,vn as pte,vo as Ho,vr as mte,vs as Uo,vt as Wo,w as Go,wa as hte,wc as Ko,wi as qo,wn as gte,wo as Jo,wr as _te,ws as Yo,wt as Xo,x as Zo,xa as Qo,xi as vte,xn as $o,xo as yte,xr as es,xs as ts,xt as ns,y as rs,ya as is,yi as as,yn as bte,yo as os,yr as xte,ys as ss,yt as cs,z as ls,za as Ste,zi as Cte,zn as wte,zo as Tte,zr as Ete,zs as us,zt as ds}from"./src-BD1wHyiU.mjs";import{c as fs,i as ps,l as ms,n as hs,s as gs}from"./esm-DxvI2ZVA.mjs";import{n as _s,t as vs}from"./md-manager-_lKMHY2F.mjs";import{A as ys,C as bs,E as xs,I as Ss,M as Cs,O as ws,P as Ts,S as Es,T as Ds,_ as Os,a as ks,b as As,c as js,d as Ms,f as Ns,g as Ps,h as Fs,i as Is,j as Ls,k as Rs,l as zs,m as Bs,n as Vs,o as Hs,p as Us,r as Ws,s as Gs,t as Ks,u as qs,v as Js,w as Ys,x as Xs,y as Zs}from"./fs-traced-2B_-YK-g.mjs";import{E as Qs,T as $s,a as ec,b as tc,l as nc,p as rc,r as N,s as ic,v as ac,w as oc,x as sc,y as cc}from"./logger-Dq-cRhcP.mjs";import{a as lc,c as uc,i as dc,l as fc,o as pc,r as mc,s as hc,t as gc}from"./git-handle-BkSalb6i.mjs";import{C as _c,S as vc,a as yc,b as bc,d as xc,i as Sc,n as Cc,o as wc,r as Tc,v as Ec,y as Dc}from"./server-lock-RKPNHNqb.mjs";import{t as Oc}from"./libesm-DzwC_yFw.mjs";import{t as kc}from"./yazl-DZr4PyKA.mjs";import{t as Ac}from"./chunk-B74TABJS-CK4NFJp-.mjs";import{a as jc,c as Mc,d as Nc,f as Pc,h as Fc,i as Ic,l as Lc,m as Rc,n as zc,o as Bc,p as Vc,r as Hc,s as Uc,t as Wc,u as Gc}from"./chunk-GFQRA5P5-BWmec-I9.mjs";import{A as Kc,B as qc,C as Jc,D as Yc,E as Xc,F as Zc,H as Qc,I as $c,L as el,M as tl,N as nl,O as rl,P as il,S as al,T as ol,V as sl,_ as cl,a as ll,b as ul,c as dl,d as fl,f as pl,g as ml,h as hl,i as gl,j as _l,k as vl,l as yl,m as bl,n as xl,o as Sl,p as Cl,r as wl,s as Tl,t as Dte,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 Ote,o as kte,r as Ate,s as Ll,t as jte,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 Mte,t as Nte}from"./chunk-A5O5YHGN-OOtvVl24.mjs";import{n as Kl,r as ql,t as Jl}from"./chunk-OJDRYQWQ-DqalHi82.mjs";import{r as Pte,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 Fte}from"./wrapper-BR9ZCXZF.mjs";import{createRequire as Ql}from"node:module";import{execFile as $l,execFileSync as Ite,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 P,extname as au,isAbsolute as ou,join as F,normalize as su,parse as cu,posix as lu,relative as I,resolve as L,sep as R,win32 as Lte}from"node:path";import{URLSearchParams as Rte,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 z,fstatSync as Bte,lstatSync as vu,mkdirSync as yu,mkdtempSync as bu,openSync as xu,opendirSync as Su,readFile as Vte,readFileSync as B,readSync as Cu,readdirSync as wu,readlinkSync as Tu,realpathSync as V,renameSync as Eu,rmSync as Du,rmdirSync as Ou,statSync as ku,unlinkSync as Au,writeFileSync as ju,writeSync as Hte}from"node:fs";import{arch as Mu,availableParallelism as Ute,homedir as Nu,hostname as Pu,platform as Fu,tmpdir as Iu}from"node:os";import{access as Lu,chmod as Wte,constants as Ru,lstat as zu,readFile as Bu,readdir as Vu,realpath as Hu,stat as Uu,writeFile as Gte}from"node:fs/promises";import{Readable as Wu,Transform as Kte,Writable as qte}from"node:stream";import Gu,{createHash as Ku,randomUUID as qu,webcrypto as Ju}from"node:crypto";import Jte from"crypto";import{Readable as Yu}from"stream";import{EventEmitter as Yte}from"node:events";import{readdirSync as Xte,statSync as Zte}from"fs";import{join as Xu,resolve as Qte}from"path";import{Worker as $te}from"node:worker_threads";import{monitorEventLoopDelay as ene,performance as Zu}from"node:perf_hooks";import{createInterface as tne}from"node:readline";import{pipeline as Qu}from"node:stream/promises";import{setImmediate as nne,setTimeout as $u}from"node:timers/promises";import{promisify as ed}from"node:util";import{request as rne}from"node:http";import{Http2ServerRequest as td,constants as ine}from"node:http2";import{lookup as ane}from"node:dns/promises";import{request as one}from"node:https";import{createBrotliDecompress as sne,createGunzip as cne,createInflate as lne}from"node:zlib";import*as une from"node:querystring";import{Http2ServerRequest as nd,constants as dne}from"http2";import{AsyncLocalStorage as fne}from"node:async_hooks";import{lookup as pne}from"node:dns";import mne 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=B(F(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=ou(t)?t:L(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=B(F(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=B(F(t.path,`config`),`utf-8`)}catch(e){return sd(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=hne(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=L(t.path,e),r=I(t.path,n);if(r.startsWith(`..`)||ou(r))return{kind:`invalid`};try{let e=B(n,`utf-8`).trim(),t=vne(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=B(F(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(L(e),``)}function ad(e){let t=L(e),n=L(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=P(i);if(e===i||e===n)return{kind:`absent`};let r=od(e,I(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function od(e,t){let n=F(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=B(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:L(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 hne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=gne(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=_ne(i[1]);if(a.length>0)return a}return null}function gne(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function _ne(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 vne(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 yne(e){return`git-author-${er(e.trim().toLowerCase())}`}const bne=/^(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 L(t.path,md(t.projectSubPath));case`linked`:if(!z(t.path))throw new hd(t.gitPath,t.path);return L(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 L(e,`.git/ok`)}}function md(e){return e===``?`ok`:`ok-${xne(e)}`}function xne(e){let t=e.split(R).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Sne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Sne(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 Cne(e){let t;try{t=pd(e)}catch(e){if(e instanceof hd||e instanceof gd)return null;throw e}return z(L(t,`HEAD`))?t:null}function _d(e){return`refs/wip/${e}/`}function wne(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=xd(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 xd(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 Tne(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 Sd(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 Ene(e){let t={v:1,id:e.writer_id,name:e.display_name,colorSeed:e.color_seed,docs:e.docs};return e.summaries&&e.summaries.length>0&&(t.summaries=e.summaries),t}function Cd(e){let t=Sd(e);return t.length>0?t.map(Ene):wne(e)}function wd(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Td(e){return`reconcile: ${e}`}function Ed(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Dd(e,t){return`park: ${e} -> ${t}`}function Od(e,t){return`rename: ${e} -> ${t}`}function kd(e){return`checkpoint: ${e}`}function Dne(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const One=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Ad(e){return e.replace(One,` `)}function kne(e,t){let n=Ad(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=Ad(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 jd(e){return bne.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 Md(e){let t=dd(e);if(t.kind!==`linked`)return L(e);try{let n=B(F(t.path,`commondir`),`utf-8`).trim();return n===``?L(e):L(P(L(t.path,n)),t.projectSubPath)}catch{return L(e)}}function Nd(e){return e.kind??`other`}function Pd(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var Fd=class{filePath;log;grants=null;constructor(e,t){this.filePath=F(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Nd(t),i=Pd(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=Nd(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-DjggEXdh.mjs`);await e(F(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(B(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 Id=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Ane={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},Ld=`acp-agents.json`,Rd=`acp-registry-cache.json`;function zd(){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 jne=new Set([`goose`,`fast-agent`,`crow-cli`]);function Mne(e,t){let n=t.trim();return n.length===0?e:jne.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Nne(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 Bd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Nne).map(e=>({...e,name:Mne(e.id,e.name)})):null}var Vd=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=Bd(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-DjggEXdh.mjs`);await e(this.localDir,{recursive:!0}),await n(F(this.localDir,Rd),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=Bd(await Bu(F(this.localDir,Rd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Hd(e,t){let n;try{n=await Bu(F(e,Ld),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${Ld} 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 ${Ld} entry`)}return i}const H={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`},Ud={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`},Pne={cancel_request:`$/cancel_request`},Wd=Symbol(`skippedItem`);function U(e,t){return e.catch(t)}function Gd(e,t){let n=e.catch(t);return D().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Ce):n.parse(e))}function Kd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function qd(e,t,n){return e.superRefine((e,r)=>{let i=Kd(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 Jd(e,t,n){return D().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Ce}let o=a.data,s=Kd(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 Yd(e){return k(e.catch(Wd)).transform(e=>e.filter(e=>e!==Wd))}const Xd=S([j(),v()]).nullable(),Zd=v(),Qd=w({sessionId:Zd,path:v(),content:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),$d=w({sessionId:Zd,path:v(),line:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),ef=v(),tf=S([M(`read`),M(`edit`),M(`delete`),M(`move`),M(`search`),M(`execute`),M(`think`),M(`fetch`),M(`switch_mode`),M(`other`)]),nf=S([M(`pending`),M(`in_progress`),M(`completed`),M(`failed`)]),rf=w({audience:U(Yd(S([M(`assistant`),M(`user`)])).nullish(),()=>void 0),lastModified:U(v().nullish(),()=>void 0),priority:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),af=w({annotations:U(rf.nullish(),()=>void 0),text:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),of=w({annotations:U(rf.nullish(),()=>void 0),data:v(),mimeType:v(),uri:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),sf=w({annotations:U(rf.nullish(),()=>void 0),data:v(),mimeType:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),cf=w({annotations:U(rf.nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),mimeType:U(v().nullish(),()=>void 0),name:v(),size:U(j().nullish(),()=>void 0),title:U(v().nullish(),()=>void 0),uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),lf=S([w({mimeType:U(v().nullish(),()=>void 0),text:v(),uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),w({blob:v(),mimeType:U(v().nullish(),()=>void 0),uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)})]),uf=w({annotations:U(rf.nullish(),()=>void 0),resource:lf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),df=S([af.and(w({type:M(`text`)})),of.and(w({type:M(`image`)})),sf.and(w({type:M(`audio`)})),cf.and(w({type:M(`resource_link`)})),uf.and(w({type:M(`resource`)}))]),Fne=w({content:df,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ine=w({path:v(),oldText:U(v().nullish(),()=>void 0),newText:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),ff=v(),Lne=w({terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),pf=S([Fne.and(w({type:M(`content`)})),Ine.and(w({type:M(`diff`)})),Lne.and(w({type:M(`terminal`)}))]),mf=w({path:v(),line:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),hf=w({toolCallId:ef,kind:U(tf.nullish(),()=>void 0),status:U(nf.nullish(),()=>void 0),title:U(v().nullish(),()=>void 0),content:U(Yd(pf).nullish(),()=>void 0),locations:U(Yd(mf).nullish(),()=>void 0),rawInput:U(D().optional(),()=>void 0),rawOutput:U(D().optional(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),gf=v(),Rne=S([M(`allow_once`),M(`allow_always`),M(`reject_once`),M(`reject_always`)]),_f=w({sessionId:Zd,toolCall:hf,options:k(w({optionId:gf,name:v(),kind:Rne,_meta:U(p(v(),D()).nullish(),()=>void 0)})),_meta:U(p(v(),D()).nullish(),()=>void 0)}),vf=w({name:v(),value:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),yf=w({sessionId:Zd,command:v(),args:U(Yd(v()).optional(),()=>[]),env:U(Yd(vf).optional(),()=>[]),cwd:U(v().nullish(),()=>void 0),outputByteLimit:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),bf=w({sessionId:Zd,terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),xf=w({sessionId:Zd,terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Sf=w({sessionId:Zd,terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Cf=w({sessionId:Zd,terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),wf=w({sessionId:Zd,toolCallId:U(ef.nullish(),()=>void 0)}),Tf=w({requestId:Xd}),zne=M(`object`),Bne=S([M(`email`),M(`uri`),M(`date`),M(`date-time`)]),Ef=w({const:v(),title:v(),description:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Df=w({title:U(v().nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),minLength:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:v().nullish(),format:Bne.nullish(),default:U(v().nullish(),()=>void 0),enum:k(v()).nullish(),oneOf:k(Ef).nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Of=w({title:U(v().nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),minimum:j().nullish(),maximum:j().nullish(),default:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),kf=w({title:U(v().nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),minimum:j().nullish(),maximum:j().nullish(),default:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Af=w({title:U(v().nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),default:U(l().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),jf=w({enum:k(v()),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Vne=w({anyOf:k(Ef),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Hne=Jd(S([jf.and(w({type:M(`string`)})),qd(w({type:v()}),`type`,[`string`]),Vne]),`type`,[`string`]),Mf=w({title:U(v().nullish(),()=>void 0),description:U(v().nullish(),()=>void 0),minItems:j().nullish(),maxItems:j().nullish(),items:Hne,default:U(Yd(v()).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Une=Jd(S([Df.and(w({type:M(`string`)})),Of.and(w({type:M(`number`)})),kf.and(w({type:M(`integer`)})),Af.and(w({type:M(`boolean`)})),Mf.and(w({type:M(`array`)})),qd(w({type:v()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Wne=w({type:U(zne.optional().default(`object`),()=>`object`),title:U(v().nullish(),()=>void 0),properties:p(v(),Une).optional().default({}),required:k(v()).nullish(),description:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Nf=u(S([wf,Tf]),w({requestedSchema:Wne})),Pf=v(),Ff=u(S([wf,Tf]),w({elicitationId:Pf,url:Be()})),If=Jd(u(S([Nf.and(w({mode:M(`form`)})),Ff.and(w({mode:M(`url`)})),qd(u(S([wf,Tf]),w({mode:v()})),`mode`,[`form`,`url`])]),w({message:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),Lf=v(),Gne=w({serverId:Lf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Rf=v(),zf=w({connectionId:Rf,method:v(),params:p(v(),D()).nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Kne=w({connectionId:Rf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Bf=D();w({id:Xd,method:v(),params:S([Qd,$d,_f,yf,bf,xf,Sf,Cf,If,Gne,zf,Kne,Bf]).nullish()});const Vf=d().gte(0).lte(65535),qne=w({image:U(l().optional().default(!1),()=>!1),audio:U(l().optional().default(!1),()=>!1),embeddedContext:U(l().optional().default(!1),()=>!1),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Jne=w({http:U(l().optional().default(!1),()=>!1),sse:U(l().optional().default(!1),()=>!1),acp:U(l().optional().default(!1),()=>!1),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Yne=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Xne=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Zne=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Qne=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),$ne=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),ere=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),tre=w({list:U(Yne.nullish(),()=>void 0),delete:U(Xne.nullish(),()=>void 0),additionalDirectories:U(Zne.nullish(),()=>void 0),fork:U(Qne.nullish(),()=>void 0),resume:U($ne.nullish(),()=>void 0),close:U(ere.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),nre=w({logout:U(w({_meta:U(p(v(),D()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),rre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),ire=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),are=w({syncKind:S([M(`full`),M(`incremental`)]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),ore=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),sre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),cre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),lre=w({document:U(w({didOpen:U(ire.nullish(),()=>void 0),didChange:U(are.nullish(),()=>void 0),didClose:U(ore.nullish(),()=>void 0),didSave:U(sre.nullish(),()=>void 0),didFocus:U(cre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),ure=w({maxCount:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),dre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),fre=w({maxCount:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),pre=w({maxCount:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),mre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),hre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),gre=w({recentFiles:U(ure.nullish(),()=>void 0),relatedSnippets:U(dre.nullish(),()=>void 0),editHistory:U(fre.nullish(),()=>void 0),userActions:U(pre.nullish(),()=>void 0),openFiles:U(mre.nullish(),()=>void 0),diagnostics:U(hre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),_re=w({events:U(lre.nullish(),()=>void 0),context:U(gre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Hf=S([M(`utf-16`),M(`utf-32`),M(`utf-8`)]),vre=w({loadSession:U(l().optional().default(!1),()=>!1),promptCapabilities:U(qne.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:U(Jne.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:U(tre.optional().default({}),()=>({})),auth:U(nre.optional().default({}),()=>({})),providers:U(rre.nullish(),()=>void 0),nes:U(_re.nullish(),()=>void 0),positionEncoding:U(Hf.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Uf=v(),yre=w({name:v(),label:U(v().nullish(),()=>void 0),secret:U(l().optional().default(!0),()=>!0),optional:U(l().optional().default(!1),()=>!1),_meta:U(p(v(),D()).nullish(),()=>void 0)}),bre=w({id:Uf,name:v(),description:U(v().nullish(),()=>void 0),vars:Gd(Yd(yre),()=>[]),link:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),xre=w({id:Uf,name:v(),description:U(v().nullish(),()=>void 0),args:U(Yd(v()).optional(),()=>[]),env:U(p(v(),v()).optional(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Sre=w({id:Uf,name:v(),description:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Cre=S([bre.and(w({type:M(`env_var`)})),xre.and(w({type:M(`terminal`)})),Sre]),Wf=w({name:v(),title:U(v().nullish(),()=>void 0),version:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Gf=w({protocolVersion:Vf,agentCapabilities:U(vre.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:U(Yd(Cre).optional().default([]),()=>[]),agentInfo:U(Wf.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Kf=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),qf=v(),Jf=S([M(`anthropic`),M(`openai`),M(`azure`),M(`vertex`),M(`bedrock`),v()]),Yf=w({apiType:Jf,baseUrl:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Xf=w({providers:k(w({providerId:qf,supported:Gd(Yd(Jf),()=>[]),required:l(),current:Yf.nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)})),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Zf=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Qf=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),$f=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),ep=v(),tp=w({currentModeId:ep,availableModes:Gd(Yd(w({id:ep,name:v(),description:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)})),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),np=v(),rp=S([M(`mode`),M(`model`),M(`model_config`),M(`thought_level`),v()]),ip=v(),ap=w({value:ip,name:v(),description:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),op=w({group:v(),name:v(),options:Gd(Yd(ap),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),sp=w({currentValue:ip,options:S([k(ap),k(op)])}),cp=w({currentValue:l()}),lp=u(S([sp.and(w({type:M(`select`)})),cp.and(w({type:M(`boolean`)}))]),w({id:np,name:v(),description:U(v().nullish(),()=>void 0),category:U(rp.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)})),up=w({sessionId:Zd,modes:U(tp.nullish(),()=>void 0),configOptions:U(Yd(lp).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),dp=w({modes:U(tp.nullish(),()=>void 0),configOptions:U(Yd(lp).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),fp=w({sessions:Gd(Yd(w({sessionId:Zd,cwd:v(),additionalDirectories:U(Yd(v()).optional(),()=>[]),title:U(v().nullish(),()=>void 0),updatedAt:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)})),()=>[]),nextCursor:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),pp=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),mp=w({sessionId:Zd,modes:U(tp.nullish(),()=>void 0),configOptions:U(Yd(lp).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),hp=w({modes:U(tp.nullish(),()=>void 0),configOptions:U(Yd(lp).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),gp=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),_p=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),vp=w({configOptions:Gd(Yd(lp),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),yp=w({stopReason:S([M(`end_turn`),M(`max_tokens`),M(`max_turn_requests`),M(`refusal`),M(`cancelled`)]),usage:U(w({totalTokens:j(),inputTokens:j(),outputTokens:j(),thoughtTokens:U(j().nullish(),()=>void 0),cachedReadTokens:U(j().nullish(),()=>void 0),cachedWriteTokens:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),bp=w({sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),xp=v(),Sp=w({line:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Cp=w({start:Sp,end:Sp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),wp=w({range:Cp,newText:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Tp=w({id:xp,uri:v(),edits:k(wp),cursorPosition:U(Sp.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ep=w({id:xp,uri:v(),position:Sp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Dp=w({id:xp,uri:v(),position:Sp,newName:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Op=w({id:xp,uri:v(),search:v(),replace:v(),isRegex:l().nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),kp=w({suggestions:k(S([Tp.and(w({kind:M(`edit`)})),Ep.and(w({kind:M(`jump`)})),Dp.and(w({kind:M(`rename`)})),Op.and(w({kind:M(`searchAndReplace`)}))])),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ap=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),jp=D(),Mp=D(),Np=w({code:S([M(-32700),M(-32600),M(-32601),M(-32602),M(-32603),M(-32800),M(-32e3),M(-32002),d().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:v(),data:U(D().optional(),()=>void 0)});S([w({id:Xd,result:S([Gf,Kf,Xf,Zf,Qf,$f,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,kp,Ap,jp,Mp])}),w({id:Xd,error:Np})]);const Pp=w({content:df,messageId:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Fp=w({toolCallId:ef,title:v(),kind:U(tf.optional(),()=>void 0),status:U(nf.optional(),()=>void 0),content:U(Yd(pf).optional(),()=>[]),locations:U(Yd(mf).optional(),()=>[]),rawInput:U(D().optional(),()=>void 0),rawOutput:U(D().optional(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ip=S([M(`high`),M(`medium`),M(`low`)]),Lp=S([M(`pending`),M(`in_progress`),M(`completed`)]),Rp=w({content:v(),priority:Ip,status:Lp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),zp=w({entries:Gd(Yd(Rp),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Bp=v(),Vp=w({planId:Bp,entries:Gd(Yd(Rp),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Hp=w({planId:Bp,uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Up=w({planId:Bp,content:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Wp=w({plan:S([Vp.and(w({type:M(`items`)})),Hp.and(w({type:M(`file`)})),Up.and(w({type:M(`markdown`)}))]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Gp=w({planId:Bp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Kp=w({hint:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),qp=w({availableCommands:Gd(Yd(w({name:v(),description:v(),input:U(Kp.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)})),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),wre=w({currentModeId:ep,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Tre=w({configOptions:Gd(Yd(lp),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ere=w({title:U(v().nullish(),()=>void 0),updatedAt:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Dre=w({amount:j(),currency:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ore=w({used:j(),size:j(),cost:U(Dre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Jp=w({sessionId:Zd,update:S([Pp.and(w({sessionUpdate:M(`user_message_chunk`)})),Pp.and(w({sessionUpdate:M(`agent_message_chunk`)})),Pp.and(w({sessionUpdate:M(`agent_thought_chunk`)})),Fp.and(w({sessionUpdate:M(`tool_call`)})),hf.and(w({sessionUpdate:M(`tool_call_update`)})),zp.and(w({sessionUpdate:M(`plan`)})),Wp.and(w({sessionUpdate:M(`plan_update`)})),Gp.and(w({sessionUpdate:M(`plan_removed`)})),qp.and(w({sessionUpdate:M(`available_commands_update`)})),wre.and(w({sessionUpdate:M(`current_mode_update`)})),Tre.and(w({sessionUpdate:M(`config_option_update`)})),Ere.and(w({sessionUpdate:M(`session_info_update`)})),Ore.and(w({sessionUpdate:M(`usage_update`)}))]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Yp=w({elicitationId:Pf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Xp=w({connectionId:Rf,method:v(),params:U(p(v(),D()).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Zp=D();w({method:v(),params:S([Jp,Yp,Xp,Zp]).nullish()});const kre=w({readTextFile:U(l().optional().default(!1),()=>!1),writeTextFile:U(l().optional().default(!1),()=>!1),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Are=w({configOptions:U(w({boolean:U(w({_meta:U(p(v(),D()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),jre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Mre=w({terminal:U(l().optional().default(!1),()=>!1),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Nre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Pre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Fre=w({form:U(Nre.nullish(),()=>void 0),url:U(Pre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ire=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Lre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Rre=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),zre=w({jump:U(Ire.nullish(),()=>void 0),rename:U(Lre.nullish(),()=>void 0),searchAndReplace:U(Rre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Qp=w({protocolVersion:Vf,clientCapabilities:U(w({fs:U(kre.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:U(l().optional().default(!1),()=>!1),session:U(Are.nullish(),()=>void 0),plan:U(jre.nullish(),()=>void 0),auth:U(Mre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:U(Fre.nullish(),()=>void 0),nes:U(zre.nullish(),()=>void 0),positionEncodings:U(Yd(Hf).optional(),()=>[]),_meta:U(p(v(),D()).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:U(Wf.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),$p=w({methodId:Uf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),em=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),tm=w({providerId:qf,apiType:Jf,baseUrl:v(),headers:p(v(),v()).optional(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),nm=w({providerId:qf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),rm=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),im=w({name:v(),value:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Bre=w({name:v(),url:v(),headers:k(im),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Vre=w({name:v(),url:v(),headers:k(im),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Hre=w({name:v(),serverId:Lf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Ure=w({name:v(),command:v(),args:k(v()),env:k(vf),_meta:U(p(v(),D()).nullish(),()=>void 0)}),am=S([Bre.and(w({type:M(`http`)})),Vre.and(w({type:M(`sse`)})),Hre.and(w({type:M(`acp`)})),Ure]),om=w({cwd:v(),additionalDirectories:U(Yd(v()).optional(),()=>[]),mcpServers:Gd(Yd(am),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),sm=w({mcpServers:Gd(Yd(am),()=>[]),cwd:v(),additionalDirectories:U(Yd(v()).optional(),()=>[]),sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),cm=w({cwd:v().nullish(),cursor:v().nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),lm=w({sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),um=w({sessionId:Zd,cwd:v(),additionalDirectories:U(Yd(v()).optional(),()=>[]),mcpServers:U(Yd(am).optional(),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),dm=w({sessionId:Zd,cwd:v(),additionalDirectories:U(Yd(v()).optional(),()=>[]),mcpServers:U(Yd(am).optional(),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),fm=w({sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),pm=w({sessionId:Zd,modeId:ep,_meta:U(p(v(),D()).nullish(),()=>void 0)}),mm=u(S([w({value:l(),type:M(`boolean`)}),w({value:ip})]),w({sessionId:Zd,configId:np,_meta:U(p(v(),D()).nullish(),()=>void 0)})),hm=w({sessionId:Zd,prompt:k(df),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Wre=w({uri:v(),name:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Gre=w({name:v(),owner:v(),remoteUrl:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),gm=w({workspaceUri:U(v().nullish(),()=>void 0),workspaceFolders:k(Wre).nullish(),repository:U(Gre.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Kre=S([M(`automatic`),M(`diagnostic`),M(`manual`)]),qre=w({uri:v(),languageId:v(),text:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Jre=w({startLine:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Yre=w({uri:v(),excerpts:k(Jre),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Xre=w({uri:v(),diff:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Zre=w({action:v(),uri:v(),position:Sp,timestampMs:j(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Qre=w({uri:v(),languageId:v(),visibleRange:U(Cp.nullish(),()=>void 0),lastFocusedMs:U(j().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),$re=S([M(`error`),M(`warning`),M(`information`),M(`hint`)]),eie=w({uri:v(),range:Cp,severity:$re,message:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),tie=w({recentFiles:k(qre).nullish(),relatedSnippets:k(Yre).nullish(),editHistory:k(Xre).nullish(),userActions:k(Zre).nullish(),openFiles:k(Qre).nullish(),diagnostics:k(eie).nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),_m=w({sessionId:Zd,uri:v(),version:j(),position:Sp,selection:Cp.nullish(),triggerKind:Kre,context:tie.nullish(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),vm=w({sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)});w({id:Xd,method:v(),params:S([Qp,$p,em,tm,nm,rm,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,zf,Bf]).nullish()});const nie=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),rie=w({content:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),iie=w({optionId:gf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),aie=w({outcome:S([w({outcome:M(`cancelled`)}),iie.and(w({outcome:M(`selected`)}))]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),oie=w({terminalId:ff,_meta:U(p(v(),D()).nullish(),()=>void 0)}),sie=w({exitCode:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),cie=w({output:v(),truncated:l(),exitStatus:U(sie.nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),lie=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),uie=w({exitCode:U(d().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(v().nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)}),die=w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),fie=S([v(),j(),j(),l(),k(v())]),ym=w({content:p(v(),fie).nullish()});S([w({id:Xd,result:S([nie,rie,aie,oie,cie,lie,uie,die,Jd(u(S([ym.and(w({action:M(`accept`)})),w({action:M(`decline`)}),w({action:M(`cancel`)}),qd(w({action:v()}),`action`,[`accept`,`cancel`,`decline`])]),w({_meta:U(p(v(),D()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),w({connectionId:Rf,_meta:U(p(v(),D()).nullish(),()=>void 0)}),w({_meta:U(p(v(),D()).nullish(),()=>void 0)}),Mp,jp])}),w({id:Xd,error:Np})]);const bm=w({sessionId:Zd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),xm=w({sessionId:Zd,uri:v(),languageId:v(),version:j(),text:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),pie=w({range:Cp.nullish(),text:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Sm=w({sessionId:Zd,uri:v(),version:j(),contentChanges:Gd(Yd(pie),()=>[]),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Cm=w({sessionId:Zd,uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),wm=w({sessionId:Zd,uri:v(),_meta:U(p(v(),D()).nullish(),()=>void 0)}),Tm=w({sessionId:Zd,uri:v(),version:j(),position:Sp,visibleRange:Cp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Em=w({sessionId:Zd,id:xp,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Dm=w({sessionId:Zd,id:xp,reason:U(S([M(`rejected`),M(`ignored`),M(`replaced`),M(`cancelled`)]).nullish(),()=>void 0),_meta:U(p(v(),D()).nullish(),()=>void 0)});w({method:v(),params:S([bm,xm,Sm,Cm,wm,Tm,Em,Dm,Xp,Zp]).nullish()}),w({requestId:Xd,_meta:U(p(v(),D()).nullish(),()=>void 0)}),Nf.and(w({mode:M(`form`)})).and(w({message:v()})),Ff.and(w({mode:M(`url`)})).and(w({message:v()})),S([wf,Tf]).and(w({message:v()})),Df.and(w({type:M(`string`)})),Of.and(w({type:M(`number`)})),kf.and(w({type:M(`integer`)})),Af.and(w({type:M(`boolean`)})),Mf.and(w({type:M(`array`)})),jf.and(w({type:M(`string`)})),ym.and(w({action:M(`accept`)})),w({action:M(`decline`)}),w({action:M(`cancel`)});const Om=`$/cancel_request`;function km(e){return typeof e==`object`&&!!e}function mie(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function hie(e){if(!(!km(e)||!mie(e.requestId)))return e.requestId}const Am={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function jm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function gie(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function _ie(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 Mm(e){if(e instanceof Fm)return e.toResult();if(_ie(e))return Fm.invalidParams(e.format()).toResult();let t=gie(e);try{return Fm.internalError(t?JSON.parse(t):{}).toResult()}catch{return Fm.internalError({details:t}).toResult()}}function vie(e){return e instanceof Fm&&e.code===-32800?e:Fm.requestCancelled(e)}function yie(e,t){let n=bie(e,t);return n?n.toResult():Mm(e)}function bie(e,t){if(!(!t.aborted||!xie(e)))return vie(t.reason)}function xie(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Sie=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 Fm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?jm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Nm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Cie=class{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Pm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Cie(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 wie}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 Nm(()=>{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 jm(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(Om,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?jm(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 Am.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(!km(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(Fm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(yie(n,t.responder.signal));else{let t=Mm(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 Sie(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&&km(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Fm(n,r,i))}else t.reject(Fm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==Om)return;let t=hie(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Fm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?jm(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)}},wie=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)??Am.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Am.no(r):await n(t(r.params),r.responder,i)??Am.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Am.no(r):await n(t(r.params),i)??Am.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Pm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Fm=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}}},Tie=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 Eie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Tie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);km(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)+`
@@ -1176,7 +1176,7 @@ tags: [lore, history]
1176
1176
  `);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=>{Y.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(),Re.release(Li))}),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()),Re.release(Li))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Re.release(Li))})}let fa=`local-op-auth-signout`,pa=K(as,async(e,t,n)=>{let r=n.host??Gi();if(!Re.tryAcquire(Ri)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:fa,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=ue,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=eu(e,i,RM({...bi,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,Vo,{},{handler:fa})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:fa,cause:e})}finally{Re.release(Ri)}},{handler:fa,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:fa})}),ha=`/api/local-op/auth/set-identity`,ya=`local-op-auth-set-identity`,ba=K(wee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!A){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ya});return}if(!Re.tryAcquire(ha)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ya,extraHeaders:{"Retry-After":`5`}});return}try{pB(A,r,i),le?.()?.refreshIdentity().catch(()=>{}),q(t,200,Vo,{},{handler:ya})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ya,cause:e})}finally{Re.release(ha)}},{handler:ya,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ya})});async function xa(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=le?.();if(!e){q(t,200,fr,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,fr,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let Ca=K(At,async(e,t,n)=>{let r=le?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,St,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?le?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function Ta(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=le?.();q(t,200,Eee,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let Da=K(ht,async(e,t,n)=>{let r=le?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,_te,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?le?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function Oa(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!A){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Dx(i),s=o.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=le?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=hc({baseDir:A,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),a=Dx(i),s=o.documents.get(a),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Ee?Ee(a):null;t!==null&&(c=t,l=!0)}else{fL(F(A,i),A);try{c=B(F(A,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,es,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),a=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=Dx(i),t=o.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Ee?Ee(e):null;t!==null&&!Jve(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,es,{file:i,base:a,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ka(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=PJ(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,fi,{plan:await VJ({projectDir:c,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof xJ){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof SJ){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Aa=K(Gee,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=PJ(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,Uee,{result:await zJ(i,{projectDir:c,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})}),Pa=K(zee,async(e,t,n)=>{let r=PJ(n.packId);if(r===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-install-pack-skill`,detail:`Pack id "${n.packId}" is not registered.`});return}try{q(t,200,mte,await yge(c,r),{handler:`seed-install-pack-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install pack skill.`,{handler:`seed-install-pack-skill`,cause:e})}},{handler:`seed-install-pack-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-install-pack-skill`})});async function La(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,xte,{packs:FJ()},{handler:`seed-packs`})}}let Ra=K(Qee,async(e,t,n)=>{if(n.out!==void 0&&!FG(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,Ua,await kI({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function za(e,t){if(r(e,t,{handler:`installed-agents`}))try{await Ife(e,t,Je.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:Xx(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Ba(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=L(c),o=i===``?a:L(a,i);return o!==a&&!o.startsWith(`${a}${R}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function Ha(e,t,n=`template`){return!e||!Zn.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Wa(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:L(e,i);if(a!==e&&!a.startsWith(`${e}${R}`))continue;let o=L(a,`.ok`,`templates`,`${n}.md`);if(z(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function Ga(e){let t={};if(!e||typeof e!=`object`||Array.isArray(e))return t;for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}let Ka=fW({GET:K(Qt,async(e,t)=>{try{let n=Ba(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await Ak(n.folderRel,{projectDir:n.resolvedContentDir}),i=L(L(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(z(i))try{let e=(0,oD.parse)(await Bu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Y.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,Kee,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:K(rte,async(e,t,n)=>{try{if(Pe){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ba(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=Ik({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(nr(e,tr(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await rr(`folder-config-put`))}q(t,200,la,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`}),qa=K(Qt,async(e,t)=>{try{let{entries:e,truncated:n}=Ome({homedirOverride:ge});q(t,200,fee,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list saved themes.`,{handler:`saved-themes-list`,cause:e})}},{handler:`saved-themes-list`,method:`GET`,skipBodyParse:!0}),Ya=K(Ea,async(e,t,n)=>{try{let e=await jme({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:ge,lockTimeoutMs:_e});if(!e.ok){if(e.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-save`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`name-taken`){G(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}G(t,400,`urn:ok:error:theme-name-invalid`,`That name cannot be used as a theme id.`,{handler:`saved-theme-save`,detail:e.code});return}q(t,201,$e,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),Xa=K(Qt,async(e,t)=>{try{let n=Dc(e).get(`id`)??``;if(n===``){G(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await Nme({id:n,homedirOverride:ge,lockTimeoutMs:_e});if(!r.ok){if(r.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}G(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}q(t,200,hee,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete theme.`,{handler:`saved-theme-delete`,cause:e})}},{handler:`saved-theme-delete`,method:`DELETE`,skipBodyParse:!0}),Qa=fW({POST:Ya,PUT:K(va,async(e,t,n)=>{try{let e=await Mme({id:n.id,scheme:n.scheme,homedirOverride:ge,lockTimeoutMs:_e});if(!e.ok){if(e.code===`lock-timeout`){G(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-update`,detail:e.code,extraHeaders:{"Retry-After":`5`}});return}if(e.code===`not-found`){G(t,404,`urn:ok:error:not-found`,`Saved theme not found.`,{handler:`saved-theme-update`});return}if(e.code===`ambiguous-id`||e.code===`unsafe-target`){G(t,409,`urn:ok:error:invalid-request`,e.code===`ambiguous-id`?`Multiple saved theme files claim that id.`:`The saved theme id conflicts with a file that cannot be safely updated.`,{handler:`saved-theme-update`,detail:e.code});return}G(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}q(t,200,uee,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update theme.`,{handler:`saved-theme-update`,cause:e})}},{handler:`saved-theme-update`,method:`PUT`}),DELETE:Xa},{handler:`saved-theme`});function $a(e,t,n){let r=o.documents.get(e);return r&&nS(r)?(aS(n,new iS({file:`${e}.md`}),t),!0):!1}function eo(e,t,n){let r=o.documents.get(e);return r&&nS(r)?(aS(n,new iS({file:`${e}.md`}),t),!0):!1}let to=K(Qt,LB(async(e,t)=>{let n=await nk(L(c));q(t,200,Fa,{templates:n.templates.map(e=>{let{scope:t,...n}=e;return n}),truncated:n.truncated},{handler:`templates-list`})},{handler:`templates-list`,title:`Failed to list templates.`}),{handler:`templates-list`,method:`GET`,skipBodyParse:!0}),ro=e=>{let{body:t}=Za(e);return{frontmatter:Eo(e)??{},body:t}},io=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ha(r,t,`template-get`))return;let i=Ba(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Wa(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=Tt(await Bu(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,qee,{template:{name:r,folder:l,scope:u,path:I(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),ao=K(cte,async(e,t,n)=>{try{if(Pe){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Ha(r,t,`template-put`))return;let i=Ba(n.folder,t,`folder`,`template-put`);if(!i||$a(Io(i.folderRel,r),`template-put`,t))return;let a=pA({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Ga(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=L(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!z(o),l=I(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=Io(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=qn(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{xb(h.dc.document,a.content,`agent`)},h.origin);let g=await zt(u);if(g?.kind===`failure`){Bt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Vt(t,`template-put`);return}dn(u,a.content),nr(e,tr(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await rr(`template-put`),q(t,200,xi,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),oo=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Ha(r,t,`template-delete`))return;let i=Ba(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=vo(n,he);if(a.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if($a(Io(i.folderRel,r),`template-delete`,t))return;await yn([Io(i.folderRel,r)],`deleted-upstream`);let o=hA({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(nr(a,tr(`template`,i.folderRel,r),`template-delete: ${o.path}`),await rr(`template-delete`),Te?.setDeleted(Io(i.folderRel,r))),q(t,200,ute,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),so=fW({GET:io,PUT:ao,POST:K(Bee,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Ha(n.fromName,t,`template-move`)||!Ha(n.toName,t,`template-move`))return;let r=Ba(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ba(n.toFolder,t,`folder`,`template-move`);if(!i||$a(Io(r.folderRel,n.fromName),`template-move`,t))return;await yn([Io(r.folderRel,n.fromName)],`renamed`);let a=await _A({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await yZ(A,e,t);return n||vZ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Wa(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}Te?.setDeleted(Io(r.folderRel,n.fromName));let o=null;if(n.body!==void 0||n.frontmatter!==void 0){let e;if(typeof n.body==`string`)e=n.body;else try{e=sr(B(L(i.resolvedContentDir,a.toPath),`utf-8`))}catch{e=null}if(e===null)o={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=mA({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Ga(n.frontmatter)});t.ok||(o=t.error)}}try{dn(Io(i.folderRel,n.toName),B(L(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(nr(e,tr(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await rr(`template-move`),ae?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Yee,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:oo},{handler:`template`}),co=K(ite,async(e,t,n)=>{try{if(Pe){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!SZ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=Ct(r);if(Lx(i)||Rx(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=iZ(c,`file`,i);if(!z(a)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let l=o.documents.get(i);if(n.deleteSource){let e=le?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=l!==void 0&&nS(l),a=n.has(r);if(i||a){aS(t,new iS({file:r}),`template-import`);return}}let u=``;if(l)u=l.getText(`source`).toString();else{let e=await o.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=aZ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Ha(d,t,`template-import`))return;let f=Ba(n.targetFolder,t,`folder`,`template-import`);if(!f||$a(Io(f.folderRel,d),`template-import`,t))return;let{frontmatter:p,body:m}=Za(u),h=xo(p),_={};try{h.trim()&&(_=(0,oD.parse)(h))}catch{}let v=n.title||_?.title||kO(u,d),y=_?.description||``,b=Array.isArray(_?.tags)?_.tags:[],x={..._};delete x.template,delete x.title;let S=``;Object.keys(x).length>0&&(S=`${(0,oD.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=pA({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=L(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!z(w),E=I(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ee=Io(f.folderRel,d),{agentId:te,agentName:ne,colorSeed:re,clientName:ie}=qn(n),D=await s.getSession(ee,te,{displayName:ne,colorSeed:re,clientName:ie});D.dc.document.transact(()=>{xb(D.dc.document,C.content,`agent`)},D.origin);let O=await zt(ee);if(O?.kind===`failure`){Bt(t,O.failure,`template-import`);return}if(O?.kind===`divergence`){Vt(t,`template-import`);return}dn(ee,C.content),nr(e,tr(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await yn([i],`deleted-upstream`),Te&&Te.setDeleted(i),Ps(a),g?.({kind:`delete`,path:a,docName:i})),await rr(`template-import`),ae?.(`files`),q(t,200,da,{path:E,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function lo(e,t,n){return!e||e.length>64||!no.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function fo(e,t,n){let r=Tr.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let po=ge??Nu(),ho=xve({contentDir:c,skillsHome:po,effectiveInstallMode:Do});function go(e){return L(e===`global`?po:c,`.ok`,`skills`)}function _o(e,t,n){let r=L(go(e),t);if(e===`global`){if(n!==void 0){let e=lL(po).find(e=>e.name===t&&e.hosts.includes(n));return e?L(po,e.dir):null}let e=uL(po,t);return e===null?z(F(r,`SKILL.md`))?r:null:e}let i=cL(c).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?L(c,i.dir):n===void 0&&z(F(r,`SKILL.md`))?r:null}function vo(e,t){let n=e.searchParams;return uD({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 yo(e,t){let n=e===`project`?A:po;if(!n)return`symlink`;try{return vs(F(n,...CE)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function bo(e){let t=e===`project`?A:po;return t?F(t,...CE):null}function So(e,t,n,r={}){let i=bo(e);return i?pJ(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 Co(e,t,n){let r=bo(e),i=bo(t);if(!r||!i)return!1;let a=fJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await pJ(i,e=>({...e,skills:{...e.skills,[n]:o}})),await pJ(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function wo(e,t,n){let r=bo(e);return r?pJ(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function To(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];G(e,r,i,t.error,{handler:n,detail:t.code})}function Do(e,t,n){let r=e===`project`?A:po;return(r?yve(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function Oo(e){let t=_o(`project`,e);return t?I(c,t).split(R).join(`/`):`${Lr}/${e}`}let ko=WF.project;function Ao(e,t,n){let r=[],i=null,a=[...Rt.map(e=>({id:e,root:kn[e]??``})),{id:`agents`,root:Si}];for(let{id:o,root:s}of a){if(!s)continue;let a=L(e,...s.split(`/`),t);z(L(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=L(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:I(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function jo(e){let t=tde(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 No(e,t){if(!KF(t))return null;let n=Ao(e,t);if(!n)return null;let r=ME(n.dir)?.contentHash??``,i;try{i=ku(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:Ia,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function Po(e,t,n){let r=Ao(e,t);if(!r)return null;let i;try{let{frontmatter:e}=ro(B(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=No(e,t);return{name:t,...i===void 0?{}:{description:i},scope:n,path:r.relPath,absolutePath:r.skillMd,installed:r.hosts.length>0,hosts:r.hosts,managed:!0,...a?{origin:jo(a)}:{}}}function Fo(e,t,n){return KF(e)?(G(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 Io(e,t){return dte(e,t)}function Lo(e){return e===`navigation`||e===`relevance`?e:void 0}function Ro(e,t){return I(t===`global`?po:c,e).split(/[\\/]/).filter(Boolean).join(`/`)}function zo(e){return e===`global`?po:A}async function Bo(e,t,n,r={}){let i=await pN(e,t),a=n===`project`?c:po;if(r.purge!==void 0){qI(t,e,Rt,FI(n));for(let e of Lhe(a,n,t,r.purge.contentHash))Us(e,{recursive:!0,force:!0});return i!==null}if(!z(L(go(n),t,`SKILL.md`))){let r=(n===`project`?cL(c):lL(po)).find(e=>e.name===t);if(r){let a=n===`project`?c:po,o=L(a,r.dir),s=L(a,`.agents`,`skills`),l=F(s,t);if(z(s)&&!z(F(l,`SKILL.md`))){let e=!1;try{e=V(o)===V(l)}catch{e=!1}e||Hs(o,l,{recursive:!0,dereference:!0})}return KI({canonicalAbs:z(F(l,`SKILL.md`))?l:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...Rt],roots:FI(n)}),i!==null}}return qI(t,e,Rt,FI(n)),i!==null}function Ho(e,t){let n=[];if(!z(e))return{skills:n,truncated:!1};let r;try{r=wu(e,{withFileTypes:!0})}catch(r){return N(`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()||!no.test(a.name))continue;if(n.length>=500){i=!0;break}let r=L(e,a.name,`SKILL.md`);if(!z(r))continue;let o;try{let{frontmatter:e}=ro(B(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Ro(r,t),absolutePath:r})}return{skills:n,truncated:i}}function Uo(e){return`!/${P(e).split(R).join(`/`)}/`}let Wo=K(Ut,LB(async(e,t,n)=>{if(!lo(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){G(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(!A){G(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=cL(c).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=JX(L(c,r,`SKILL.md`),c)??`${r}/SKILL.md`,a=P(i),o=i,s=Uo(a),l=`.gitignore`,u=L(c,l);if(xe&&!xe.isPathIgnored(o)){q(t,200,gn,{line:s,gitignorePath:l,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){q(t,200,gn,{line:s,gitignorePath:l,applied:!1},{handler:`skill-track-in-git`});return}let d=z(u)?B(u,`utf-8`):null;if((d??``).split(`
1177
1177
  `).some(e=>e.trim()===s)){G(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${l}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(ju(u,`${d===null||d.endsWith(`
1178
1178
  `)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),await xe?.rebuildIgnorePatterns(),xe?.isPathIgnored(o)){d===null?Du(u,{force:!0}):ju(u,d,`utf-8`),await xe.rebuildIgnorePatterns(),G(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${l} was left unchanged.`,{handler:`skill-track-in-git`});return}ae?.(`files`),q(t,200,gn,{line:s,gitignorePath:l,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),Go={lastKey:null},Ko=K(Qt,LB(async(e,t)=>{let n=go(`project`),r=Ho(n,`project`),i=Ho(go(`global`),`global`),a=A?She(A):[],o=OI(po).map(e=>e.editorId),s=A?uN(A).skills:{},l=uN(po).skills,u=A?TE(z(F(A,...CE))?B(F(A,...CE),`utf-8`):``)??null:null,d=jo,f=(e,t,r)=>e.skills.map(e=>{let i=t[e.name]?.hosts??[],a=r?u?.skills[e.name]:void 0,o=a?d(a):void 0,s=a?.localHash!==void 0&&ys(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=A?nX(A):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=L(e,i.path);if(n!==void 0&&t===L(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(V(t)===V(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=A?$I(c,`project`):{},g=iL(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=nL(`project`),y=nL(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=A?cL(c).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??No(c,e.name):void 0,r=n?d(n):void 0,i=n?.localHash!==void 0&&e.contentHash!==n.localHash;return{name:e.name,...e.description?{description:e.description}:{},scope:`project`,path:`${e.dir}/SKILL.md`,absolutePath:L(c,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(A,b(t?p[e.name]:void 0,g),L(c,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...Do(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...KF(e.name)?{managed:!0}:{}}}):[],C=nX(po),w=vs(F(po,...CE)),T=$I(po,`global`),E=iL(T,`global`),ee=new Set(lL(po).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let te=new Set,ne=lL(po).map(e=>{let t=!te.has(e.name);te.add(e.name);let n=t?C[e.name]:void 0;return{name:e.name,...e.description?{description:e.description}:{},scope:`global`,path:`${e.dir}/SKILL.md`,absolutePath:L(po,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],size:e.size,installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(po,b(n,E),L(po,e.dir));return t.drift.length>0?{driftPaths:t.drift}:{}})(),...(()=>{let e=b(n,E).filter(e=>!_(e.path,y));return e.length?{customPlacements:e.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...Do(`global`,e.name,e)===`link`?{linkMode:!0}:{},...KF(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??No(po,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),re=new Set(S.map(e=>e.name)),ie=A&&!r.skills.some(e=>e.name===ko)&&!re.has(ko)?Po(A,ko,`project`):null,D=new Set(ne.map(e=>e.name)),O=YF.map(e=>WF[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!D.has(e)).map(e=>Po(po,e,`global`)).filter(e=>e!==null),k=new Set(S.map(e=>e.name)),ae={skills:[...f(r,s,!0).filter(e=>!k.has(e.name)),...S,...f(i,l,!1),...ne,...ie?[ie]:[],...O].map(e=>{let t=e.scope===`project`&&e.absolutePath?JX(e.absolutePath,c):null,n=t===null||t===e.path?e:{...e,canonicalPath:t},r=t??e.path;return e.scope===`project`&&xe?.isPathIgnored(r)===!0?{...n,ignored:!0}:n}),truncated:r.truncated||i.truncated};await Xve(S.map(e=>e.path),xe??null,Go),q(t,200,Fee,ae,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Jo=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!lo(r,t,`skill-get`))return;let i=fo(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(KF(r)){let e=i===`global`?po:A,a=e?Ao(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=ro(await Bu(a.skillMd,`utf-8`));q(t,200,ir,{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:YI(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=_o(i,r,a);if(o===null){G(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=L(o,`SKILL.md`),{frontmatter:c,body:l}=ro(await Bu(s,`utf-8`));q(t,200,ir,{skill:{name:r,scope:i,path:Ro(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:YI(o)}},{handler:`skill-get`})}catch(e){G(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 Yo(e,t){if(!(!O||Wx(e))){if(xe)try{await xe.rebuildIgnorePatterns()}catch{}await en(e,t,`skill-put`)}}let Xo=K(dee,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!lo(n.name,t,`skill-put`)||Fo(n.name,t,`skill-put`))return;let r=Uk({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?c:po,a=_o(n.scope,n.name);if(a===null){let a=aL(i,n.scope);if(a===null){G(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-put`,detail:`NO_USABLE_SKILL_HOME`});return}let o=Wk({skillsRoot:L(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){G(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`&&(nr(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await rr(`skill-put`)),await Yo(n.scope===`project`?`${a}/${n.name}/SKILL`:ja(`global`,n.name),r.content),ae?.(`files`),q(t,200,Kn,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=I(i,a).split(R).join(`/`),l=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:ja(n.scope,n.name);if(eo(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=qn(n),h=await s.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 zt(u);if(g?.kind===`failure`){Bt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Vt(t,`skill-put`);return}n.scope===`project`&&(nr(e,tr(`skill`,``,n.name),`skill-edit: ${l}`),await rr(`skill-put`)),await Yo(u,r.content),ae?.(`files`),q(t,200,Kn,{path:l,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function Qo(e,t){let n=e===`project`?c:po,r=_o(e,t);return{root:r===null?go(e):P(r),dirRel:r===null?`.ok/skills/${t}`:I(n,r).split(R).join(`/`),realDir:r}}function $o(e,t){let n=e===`project`?c:po,r=(e===`project`?cL(c):lL(po)).find(e=>e.name===t);r&&KI({canonicalAbs:L(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>Wi(e)),roots:FI(e)})}let ts=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!lo(r,t,`skill-delete`))return;let i=fo(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=Qo(i,r),s=vo(n,he);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await yn(i===`project`?[...new Set([`${o}/SKILL`,ja(i,r)])]:[ja(i,r)],`deleted-upstream`),$o(i,r);let c=Xk({skillsRoot:a,name:r}),l=go(i);if(c.ok&&l!==a&&z(L(l,r,`SKILL.md`))){let e=Xk({skillsRoot:l,name:r});e.ok||Y.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(nr(s,o,`skill-delete: ${o}`),await rr(`skill-delete`)),ae?.(`files`));let u=zo(i);u&&await Bo(u,r,i),q(t,200,fte,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),ns=K(wa,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!lo(n.fromName,t,`skill-move`)||!lo(n.toName,t,`skill-move`)||Fo(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=Qo(n.scope,n.fromName);if(_o(n.scope,n.toName)!==null){G(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=zo(n.scope),o=a?uN(a).skills[n.fromName]:void 0,s=n.scope===`project`?c:po,l=(n.scope===`project`?cL(c):lL(po)).find(e=>e.name===n.fromName),u=l?P(l.dir):null,d=u===null?[]:Object.entries($I(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?jI(o.hosts):[],...l?jI(l.hosts):[],...jI(d)])];await yn(n.scope===`project`?[...new Set([`${i}/SKILL`,ja(n.scope,n.fromName)])]:[ja(n.scope,n.fromName)],`renamed`),$o(n.scope,n.fromName);let p=await Zk({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await yZ(A,e,t);return n||vZ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){G(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;G(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=L(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=ro(B(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=Wk({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=Whe({base:n.scope===`project`?c:po,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){N(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await xe?.rebuildIgnorePatterns(),await ps(r,n.fromName,n.toName),await ms(x,n.toName)}catch(e){N(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`reindex of moved project skill docs failed — rename succeeded, deferring to next rescan`)}let S=Ro(L(r,n.fromName),n.scope),C=Ro(L(r,n.toName),n.scope);n.scope===`project`&&(nr(e,tr(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await rr(`skill-move`));let w=ys(r,n.toName),T=n.scope===`project`?await bs(Ss(e),C):void 0;if(await So(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await pN(a,n.fromName),qI(n.fromName,a,f,FI(n.scope));let e=L(r,n.toName);if(f.length>0){let t=BI(e,n.toName,a,f,yo(n.scope,n.toName),FI(n.scope));await fN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??NI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(ae?.(`files`),m){let e=m.code===`WRITE_ERROR`;G(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}q(t,200,cee,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),is=K(Zee,async(e,t,n)=>{let{name:r,home:i}=n;if(!lo(r,t,`skill-edit-external`))return;let a;try{a=V(i)}catch{G(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!ku(a).isDirectory()||!z(L(a,`SKILL.md`))){G(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}tz(r,a),q(t,200,Va,{docName:lte(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),os=K(Ze,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(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(!lo(r,t,`skill-move-scope`))return;if(i===a){G(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:l}=Qo(i,r),u=L(o,r),d=(()=>{try{return V(u)}catch{return u}})(),f=a===`project`?c:po,p=aL(f,a);if(p===null){G(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=L(f,p),h=L(m,r);if(l===null||!z(u)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(L(l)===L(h)||z(h)&&V(l)===V(h)){G(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(_o(a,r)!==null||z(h)){G(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let g=zo(i),_=zo(a),v=g?uN(g).skills[r]:void 0,y=i===`project`?c:po,b=(i===`project`?cL(c):lL(po)).find(e=>e.name===r),x=b?P(b.dir):null,S=x===null?[]:Object.entries($I(y,i)).filter(([,e])=>e===x).map(([e])=>e),C=[...new Set([...v?jI(v.hosts):[],...b?jI(b.hosts):[],...jI(S)])];await yn([...new Set([...i===`project`?[`${s}/SKILL`]:[],ja(i,r),ja(a,r)])],`renamed`),zs(m,{recursive:!0}),Hs(d,h,{recursive:!0,dereference:!0}),$o(i,r);let w=Xk({skillsRoot:o,name:r});if(w.ok&&d!==u){let e=I((()=>{try{return V(y)}catch{return y}})(),d);e!==``&&!e.startsWith(`..`)&&!ou(e)&&Us(d,{recursive:!0,force:!0})}if(!w.ok){Xk({skillsRoot:m,name:r}),G(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 Co(i,a,r);if(g&&await Bo(g,r,i,b?{purge:{contentHash:b.contentHash}}:{}),g&&await bve(g,r),_&&C.length>0){let e=BI(h,r,_,C,yo(a,n.name),FI(a));await fN(_,r,{...v,scope:a,hosts:e,scripts:v?.scripts??NI(h,r).hasScripts,installedAt:v?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(nr(e,i===`project`?s:I(c,h).split(R).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await rr(`skill-move-scope`)),T){let t=ys(m,r),n=a===`project`?await bs(Ss(e),I(c,h).split(R).join(`/`)):void 0;await wo(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!z(F(h,`SKILL.md`))){G(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:I(f,h).split(R).join(`/`)});return}await xe?.rebuildIgnorePatterns(),ae?.(`files`),q(t,200,ga,{scope:a,path:I(f,h).split(R).join(`/`)},{handler:`skill-move-scope`})}catch(e){G(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`}),ss=K(Oi,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!lo(n.name,t,`skill-duplicate`)||!lo(n.toName,t,`skill-duplicate`)||Fo(n.toName,t,`skill-duplicate`))return;let r=_o(n.scope,n.name);if(r===null||!z(F(r,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?c:po,a=aL(i,n.scope);if(a===null){G(t,400,`urn:ok:error:invalid-request`,`No agent skill host is available.`,{handler:`skill-duplicate`,detail:`NO_USABLE_SKILL_HOME`});return}let o=L(i,a),s=L(o,n.toName);if(_o(n.scope,n.toName)!==null||z(s)){G(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let l=ME(r);if(!l){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}zs(o,{recursive:!0}),Hs(r,s,{recursive:!0,dereference:!0});let{fenced:u,body:d}=Hi(l.skillMd),f=Di(u,{name:n.toName});if(!f.ok){Xk({skillsRoot:o,name:n.toName}),G(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:f.error.kind});return}try{Js(F(s,`SKILL.md`),`${f.nextFenced}${d}`)}catch(e){throw Xk({skillsRoot:o,name:n.toName}),e}if(n.scope===`project`){let t=I(c,s).split(R).join(`/`);nr(e,tr(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await rr(`skill-duplicate`)}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,Vee,{name:n.toName},{handler:`skill-duplicate`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),cs=fW({GET:Jo,PUT:Xo,POST:ns,DELETE:ts},{handler:`skill`});function ls(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 us(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function ds(e,t){let n=t.replace(/\.md$/i,``);return`${ate(e).replace(/\/SKILL$/,``)}/${n}`}function fs(e,t){let n=L(e,t,`references`);if(!z(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(L(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function ps(e,t,n){if(!O){N(`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=B(n,`utf-8`)}catch(i){N(`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=I(c,e).split(R).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),L(e,n,`SKILL.md`));for(let r of fs(e,n))i(o(t,r),o(n,r),L(e,n,r));await O.recordDirectMutations(r)}async function ms(e,t){if(!O||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 O.recordDirectMutations(n)}let hs=fW({GET:K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!lo(r,t,`skill-file-get`))return;let i=fo(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=KF(r)?i===`global`?po:A:void 0,s=n.searchParams.get(`host`)??void 0,c=o?Ao(o,r,s):null;if(a===``||a.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:ls(a))??`reference`,u=s,d=o?c?.dir??null:_o(i,r,u);if(d===null&&u!==void 0){G(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??L(go(i),r),p=L(f,a);if(p!==f&&!p.startsWith(`${f}${R}`)){G(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(!z(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?xr.map(t=>`${e[1]}${t}`).find(e=>e!==a&&z(L(f,e))):void 0;if(n===void 0){G(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=L(f,n)}let g=await Bu(m);if(g.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,Hee,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(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:K(Ree,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!lo(n.name,t,`skill-file-put`)||Fo(n.name,t,`skill-file-put`))return;let r=ls(n.path);if(r===null){G(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){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=_o(n.scope,n.name);if(i===null||!z(F(i,`SKILL.md`))){G(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=I(n.scope===`project`?c:po,i).split(R).join(`/`),o=n.path.replace(/\\/g,`/`),l=us(n.scope,r,o),u;if(l){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(eo(e,`skill-file-put`,t))return;if(u=!z(L(i,o)),u&&Kk(i)>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:c,colorSeed:l,clientName:d}=qn(n),f=await s.getSession(e,r,{displayName:c,colorSeed:l,clientName:d});f.dc.document.transact(()=>{xb(f.dc.document,n.content,`agent`)},f.origin);let p=await zt(e);if(p?.kind===`failure`){Bt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Vt(t,`skill-file-put`);return}}else{let e=qk({skillsRoot:P(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;G(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`&&(nr(e,tr(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await rr(`skill-file-put`)),ae?.(`files`),q(t,200,pte,{path:o,created:u,kind:r,content:l},{handler:`skill-file-put`})}catch(e){G(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:K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!lo(i,t,`skill-file-delete`)||Fo(i,t,`skill-file-delete`))return;let a=fo(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=ls(o);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let l=vo(n,he);if(l.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=_o(a,i),d=u===null?go(a):P(u);if(z(L(u??F(d,i),o))&&us(a,s,o)){let e=o.replace(/\.md$/i,``);await yn([u===null?ds(i,o):`${I(c,u).split(R).join(`/`)}/${e}`],`deleted-upstream`)}let f=Yk({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(nr(l,tr(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${I(c,u).split(R).join(`/`)}/${o}`}`),await rr(`skill-file-delete`)),f.existed&&ae?.(`files`),q(t,200,Wee,{path:o,existed:f.existed,kind:s},{handler:`skill-file-delete`})}catch(e){G(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`}),gs=K(bte,async(e,t,n)=>{try{if(!lo(n.name,t,`skill-file-rename`)||Fo(n.name,t,`skill-file-rename`))return;let e=uD(n,he);if(e.kind===`invalid-summary`){G(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=ls(r),o=ls(i);if(a===null||o===null){G(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=_o(n.scope,n.name);if(s===null){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let l=P(s),u=us(n.scope,a,r),d=us(n.scope,o,i),f=I(c,s).split(R).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&eo(p,`skill-file-rename`,t))return;p!==null&&await yn([p],`deleted-upstream`);let h=Jk({skillsRoot:l,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;G(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(O){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:B(L(l,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:p})}else if(p!==null)e.push({kind:`delete`,documentName:p});else if(m!==null)try{e.push({kind:`upsert`,documentName:m,markdown:B(L(l,n.name,i),`utf-8`)})}catch{}await $t(e,`skill-file-rename`)}n.scope===`project`&&(nr(e,tr(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await rr(`skill-file-rename`)),ae?.(`files`),q(t,200,di,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){Y.error({err:e},`[skill-file-rename] failed`),t.headersSent||G(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function _s(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let vs=fJ;function ys(e,t){return ME(L(e,t))?.contentHash}async function bs(e,t){let n=ee?.current;if(!(!n||!e))try{let r=nx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1179
- `).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 rr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Ss=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Cs(e){try{let t=zo(e.scope);if(!t)return;let n=PI(t);if(n.length===0)return;let r=BI(L(e.skillsRoot,e.name),e.name,t,n,`copy`,FI(e.scope));if(r.length===0)return;await fN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Y.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function ws(e,t){if(t.ok){q(e,200,gte,t.body,{handler:`skill-import`});return}G(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 Ts=pve({contentDir:c,skillsHome:po,...A===void 0?{}:{projectDir:A},resolveSkillDirForRead:_o,parseFrontmatterDoc:ro,attributeOkArtifactWrite:nr,commitOkArtifactWrite:rr,shadowHeadSha:bs,artifactWriterId:Ss,effectiveInstallMode:Do,signalFiles:()=>ae?.(`files`)}),Es=K(pt,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(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 LE(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??bE(d);if(!p){G(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(lX(t,p,`skill-import`))return;let m=await SE(p);r=m.cleanup,s=m.ref;let h=NE(m.dir);if(h.length===0){G(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=>AE(e.dir)?.name===f)??h.find(e=>e.name===Ai[f]);if(!e){G(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){G(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??_s(d)}catch(e){if(e instanceof fE){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Ts.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||uo(u))&&TI({source:u,skills:[d.body.name]},iI()),await xe?.rebuildIgnorePatterns(),ws(t,d)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Os=K(Nee,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(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 LE(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??bE(d);if(!f){G(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(lX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??_s(d),f.kind===`well-known`)a=f,o=await vE(f.origin);else{let e=await SE(f);r=e.cleanup,c=e.ref,s=NE(e.dir)}}catch(e){if(e instanceof fE){G(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){G(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 SE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof fE?`not-found`:`failed`,warnings:[],...e instanceof fE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>ME(e.dir)?.name===t)??s.find(e=>e.name===Ai[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Ts.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){N(`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){N(`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||uo(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&TI({source:u,skills:e},iI())}await xe?.rebuildIgnorePatterns(),q(t,200,Aee,{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){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),ks=8*1024*1024,As=32*1024*1024;function js(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=L(e,n);return r!==e&&!r.startsWith(e+R)?null:r}function Ms(e){return new Promise((t,n)=>{let r;try{r=Dq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:ks})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>As){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Ns(e,t){return new Promise((n,r)=>{(0,Ode.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=js(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){zs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>ks){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>As){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{zs(P(n),{recursive:!0}),Js(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 Fs(e,t){let n=bu(F(Iu(),`ok-skill-upload-`)),r=()=>{try{Us(n,{recursive:!0,force:!0})}catch{}};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){G(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=fo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=uD({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},he);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Ms(e)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){G(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 Ns(c.data,n)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=js(n,e.relPath);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}zs(P(r),{recursive:!0}),Js(r,e.data)}let u=NE(n);if(u.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){G(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];ws(t,await Ts.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Is=K(ur,async(e,t,n)=>{try{let e=go(n.scope);if(!lo(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){G(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=zo(n.scope),i=L(e,n.name),a=n.scope===`project`?c:po,o=(n.scope===`project`?cL(c):lL(po)).find(e=>e.name===n.name),s=o?L(a,o.dir):i;if(!z(s)){G(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 zt(n.scope===`project`?`${I(a,s).split(R).join(`/`)}/SKILL`:ja(n.scope,n.name));let l=NI(s,n.name,{allowReservedName:KF(n.name)});if(!l.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=ho.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:G(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:G(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:G(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`:G(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:G(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)}`)}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o.hosts.filter(Wi),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){G(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 ho.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`?G(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`}):G(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(Wi),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await ho.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){G(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}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:po;if(!e){G(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 Pr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?G(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):G(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||ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:po;if(!e){G(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 Pr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:G(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:G(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:G(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`:G(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)}`)}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){G(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`?A:po,c=await Pr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!c.ok)switch(c.kind){case`invalid-location`:G(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:G(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`:G(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`:G(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(c.kind)}`)}ae?.(`files`),q(t,200,bt,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?OI(po).map(e=>e.editorId).filter(e=>Rt.includes(e)):Rt.filter(e=>f?.some(t=>t===e)):f===void 0?PI(r):Rt.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(f===void 0?n.scope===`global`&&z(F(po,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?A:po,c=d===void 0?Do(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await ho.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?G(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}):G(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}ae?.(`files`),q(t,200,bt,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await ho.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:c,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),ae?.(`files`),q(t,200,bt,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=jI(uN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&qI(n.name,r,v,FI(n.scope));let y=F(r,...CE),b=z(y)?B(y,`utf-8`):null,x=b===null?null:TE(b);b!==null&&x===null&&Y.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=BI(s,n.name,r,h,C,FI(n.scope));w.length===0?await pN(r,n.name):await fN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),ae?.(`files`),q(t,200,bt,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Ls=K(ete,async(e,t,n)=>{try{if(!lo(n.name,t,`skill-uninstall`))return;let e=zo(n.scope);if(!e){G(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 Bo(e,n.name,n.scope);ae?.(`files`),q(t,200,nee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Rs=fW({GET:K(Qt,async(e,t)=>{try{let e=PI(A??``),n=(e,t)=>{let n=_ve(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};q(t,200,Xt,{targets:e,configured:!1,folders:[...A?YY(c,tL(c,`project`)).filter(e=>rL(c,`project`,e.root)).map(e=>({...e,scope:`project`,...n(c,e)})):[],...YY(po,tL(po,`global`)).filter(e=>rL(po,`global`,e.root)).map(e=>({...e,scope:`global`,...n(po,e)}))]},{handler:`skill-targets-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:K(vr,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?c:po;if(e.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await vve(r,i.join(`/`)),ae?.(`files`),q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(tL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){G(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}if(e.action===`link`&&e.preview){let n=ZY({base:r,folderRel:e.root,targetRootRel:a}),i=n.kind===`plan`?n.plan:null;q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],preview:{moves:i?[...i.linkedBundlesToMove.map(({name:e})=>e),...i.toMove]:[],drops:i?.toDrop??[],removes:i?.removes??[],replaces:i?.liveDestLinks??[],conflicts:n.kind===`conflicts`?n.conflicts:[],strays:n.kind===`stray-entries`?n.strays:[]}},{handler:`skill-targets-put`});return}let o=e.action===`link`?gve({base:r,folderRel:e.root,targetRootRel:a}):QY({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){G(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await tX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),ae?.(`files`),q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Bs=K(Sn,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!lo(n.name,t,`skill-restore`)||Fo(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(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=ee?.current;if(!r){G(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 dX({shadow:r,contentDir:c,contentRoot:D??`.`,name:n.name,version:n.version,skillDirRel:Oo(n.name)});if(!i.ok){To(t,i,`skill-restore`);return}let a=[],o=NI(L(c,Oo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),nr(e,tr(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await rr(`skill-restore`),ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,xee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Ws=K(Ft,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!lo(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?po:c,{root:a,dirRel:o,realDir:s}=Qo(n.scope,n.name),l=!o.startsWith(`${Lr}/`);if(s===null||!z(L(i,o,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=F(n.scope===`global`?po:A,...CE),d=vs(u).skills[n.name];if(!d){let e=Eue(n.name,ME(L(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:Wve(L(a,n.name))})??No(i,n.name);e&&(d=e)}if(!d){G(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 pJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=Ai[e],a=await LE(d.source,e).catch(async e=>{if(i===void 0)throw e;return LE(d.source,i)}),o=a?.source??nde(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??bE(o);if(!c){G(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(lX(t,c,`skill-reimport`))return;let l=await SE(c);r=l.cleanup,f=l.ref;let u=NE(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>ME(e.dir)?.name===n.name)??u.find(e=>e.name===Ai[s??n.name])??(u.length===1?u[0]:void 0);if(!m){G(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=jE(m.dir);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=ME(m.dir)}catch(e){if(e instanceof fE){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=JY(p);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=ME(L(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=ro(p.skillMd).body;if(n.dryRun){let e=ME(L(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=hc({baseDir:A,timeout:{block:15e3}}),t=I(A,L(a,n.name)).split(R).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!0,source:d.source,localBody:ro(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await yn(e,`deleted-upstream`)}let x=Wk({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){G(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=qk({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:qY});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Yk({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(nr(e,tr(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await rr(`skill-reimport`));let C=ys(a,n.name),w=n.scope===`project`?await bs(Ss(e),o):void 0;await pJ(u,e=>EE(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await Cs({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Gs=K(wte,async(e,t,n)=>{try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!lo(n.name,t,`skill-revert`)||Fo(n.name,t,`skill-revert`))return;if(n.scope===`global`){G(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=F(A,...CE),i=vs(r).skills[n.name];if(!i?.baselineRef){G(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=ee?.current;if(!a){G(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 dX({shadow:a,contentDir:c,contentRoot:D??`.`,name:n.name,version:i.baselineRef,skillDirRel:Oo(n.name)});if(!o.ok){To(t,o,`skill-revert`);return}nr(e,tr(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await rr(`skill-revert`);let s=L(c,Oo(n.name),`..`),l=ys(s,n.name);await pJ(r,e=>EE(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),s===go(`project`)&&await Cs({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),ae?.(`files`),q(t,200,it,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function qs(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ys(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Xs(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Zs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Qs=dve({contentDir:c,projectDir:A,getAllFilesIndex:h,getFileIndexGeneration:_,getSearchMaxEntries:Qve,semanticSearch:Oe,getSemanticSimilarityFloor:ke,ready:we,getProjectSkillsRoot:()=>go(`project`),parseFrontmatterDoc:ro});Qs.prewarm();let $s=fW({GET:K(Qt,LB(async(e,t)=>{let n=Dc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=qs(n.get(`intent`)),o=Lo(n.get(`ranking`)),s=Ys(n.get(`scope`)??n.get(`scopes`)),c=Xs(n.get(`semantic`)),l=Zs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,yi,await Qs.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:K(ste,LB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=qs(n.intent),a=Lo(n.ranking),o=Ys(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Xs(n.semantic),l=Zs(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,yi,await Qs.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),ec=K(Qt,LB(async(e,t)=>{q(t,200,Ot,{...await SI(Nu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function tc(e,t){if(r(e,t,{handler:`handoff`}))try{await Ufe(e,t,{contentDir:c,platform:process.platform,isSchemeRegistered:Je.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:Xx(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function nc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await KM(e,t,{contentDir:c,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:Xx(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let rc=K(gee,async(e,t,n)=>{try{if(!A){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Pme(e,n.kind)){EF(`invalid-path`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`invalid-path`},{handler:wF});return}let r=Rme(A);if(r===null){if(AF(A).kind===`no-remote`){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}EF(`detached-head`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`detached-head`},{handler:wF});return}let i=AF(A);if(i.kind===`no-remote`){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}if(i.kind===`non-github`){EF(`non-github-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`non-github-remote`},{handler:wF});return}if(!Ume(A,r)){EF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,It,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:wF});return}let a=pZ(A,c);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=a===``?e:e===``?a:`${a}/${e}`,s;s=n.kind===`doc`?Fme(i.host,i.owner,i.repo,r,o):TF(i.host,i.owner,i.repo,r,o);let l;try{let e=a===``?0:kee(TF(i.host,i.owner,i.repo,r,a)).targetSegments.length;l=`https://openknowledge.ai/d/${Mee(s,e)}`}catch(e){if(!(e instanceof tee))throw e;EF(`unsupported-share-url`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`unsupported-share-url`},{handler:wF});return}let u=await Ime(A,r,o,n.kind);EF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,It,{ok:!0,shareUrl:l,sharedUrl:s,branch:r,freshness:u},{handler:wF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:wF,cause:e})}},{handler:wF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:wF})}),ic=K(Qt,async(e,t)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:eB});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!aee(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:eB});return}if(!Qz(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:eB});return}q(t,200,Qe,await $z(A,r,i,a),{handler:eB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:eB,cause:e})}},{handler:eB,method:`GET`,skipBodyParse:!0});function ac(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let oc=K(Er,async(e,t,n)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:UF});return}if(!Qz(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:UF});return}let e=await Zme(A,n.branch,n.path,n.kind,{credentialConfig:mc(ue,{resetAmbient:MF(A)})});q(t,200,Zt,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:ac(n.path,e.renamedTo,n.contentRootDepth),{handler:UF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:UF,cause:e})}},{handler:UF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:UF})}),sc=K(_a,async(e,t,n)=>{if(uD(n,he).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:aB});return}if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:aB});return}try{q(t,200,lee,await lc(()=>sB(A,n.branch,{fastForward:n.fastForward===!0,credentialConfig:mc(ue,{resetAmbient:MF(A)})})),{handler:aB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:aB,cause:e})}},{handler:aB,method:`POST`});async function cc(e){let[t,...n]=ue,r=[...n,...e];return await new Promise((e,n)=>{let i=eu(t,r,RM({..._i,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},IF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${IF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=HF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let uc=K(Qt,async(e,t)=>{if(!Re.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:NF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await cc([`share`,`owners`,`--json`]),n=Wme(zF(e));VF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,See,n,{handler:NF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NF,cause:e})}finally{Re.release(`/api/share/publish/owners`)}},{handler:NF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:NF})}),dc=K(Qt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!RF(r)||!LF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:PF});return}if(!Re.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:PF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await cc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Gme(zF(e));VF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,Cn,n,{handler:PF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PF,cause:e})}finally{Re.release(`/api/share/publish/name-check`)}},{handler:PF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:PF})}),fc=K(Tte,async(e,t,n)=>{if(!A){VF(`publish-create`,`no-project`),q(t,200,at,{ok:!1,error:`no-project`},{handler:FF});return}if(!RF(n.owner)||!LF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:FF});return}if(!Re.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:FF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await cc(e),i=Jme(zF(r));VF(`publish-create`,i.ok?`ok`:i.error),i.ok&&le?.()?.refreshRemote().catch(()=>{}),q(t,200,at,i,{handler:FF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:FF,cause:e})}finally{Re.release(`/api/share/publish`)}},{handler:FF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:FF})}),pc=K(nte,async(e,t,n)=>{try{let e=N(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,oa,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),gc=A?RD(A):null;async function _c(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Fde(e.headers),previewUrl:null,port:gc?yc(gc)?.port??0:0,singleFile:Pe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,yte,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function vc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Le?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,pe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let bc=`local-op-embeddings-set-key`,xc=`local-op-embeddings-clear-key`,Sc=`/api/local-op/embeddings`;function Cc(){let e=je?.();return{projectDir:A??c,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let wc=K(lr,async(e,t,n)=>{if(!Re.tryAcquire(Sc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Cc();await new kj(Ae).setForProject(e,r,n.key),Oe?.reloadCredential(),q(t,200,qo,{keyPresent:!0},{handler:bc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bc,cause:e})}finally{Re.release(Sc)}},{handler:bc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:bc})}),Tc=K(Qt,async(e,t)=>{if(!Re.tryAcquire(Sc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Cc();await new kj(Ae).clearForProject(e,n),Oe?.reloadCredential(),q(t,200,qo,{keyPresent:!1},{handler:xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xc,cause:e})}finally{Re.release(Sc)}},{handler:xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:xc})}),Oc=`local-op-embeddings-test`,kc=`/api/local-op/embeddings/test`,Ac=K(Qt,async(e,t)=>{if(!Re.tryAcquire(kc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Oc,extraHeaders:{"Retry-After":`5`}});return}try{let e=je?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await vj(new kj(Ae),A??c,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await bj({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,Dt,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Oc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Oc,cause:e})}finally{Re.release(kc)}},{handler:Oc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Oc})}),jc=K(Qt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=je?.()?.baseUrl??`https://api.openai.com/v1`,o=await vj(new kj(Ae),A??c,a),s=o.apiKey!==null,l=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of p())!Lx(e)&&!Rx(e)&&!mo(e)&&(f+=1);q(t,200,Na,{enabled:e,keyPresent:s,keyNotRequired:l,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Mc=0;function Nc(){Mc+=1,ae?.(`lint-config`)}let Pc=()=>`${Mc} ${t.getActiveBranch()} ${O?.readLocalTargetGeneration?.()??0}`;async function Fc(e,t){let n=Me?.()??Fr;try{let r=await Ti(e,jP(c,n,{docName:t,projectDir:A??c,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ne?.()??`warning`;if(O&&a!==`off`&&!Wx(t)){await tn(t,e,`lint-validation`);let r=oF({projectDir:A??c,contentDir:c,baseConfig:n,derivedDocumentIndex:O,linksValidation:a,admittedDocNames:qt,docFilePathFor:e=>uZ(c,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:uZ(c,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ic(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=PP({projectDir:A??c,contentDir:c});return eP(t.schemas,n)}let Lc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!SZ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Me?.()??Fr,i=[],a=OP(c,n??void 0,e=>i.push(e)),o=AP(A??c,kP(r,a),e=>i.push(e));n===null&&i.push(...Ic(o)),q(t,200,Et,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Rc=K(Ye,async(e,t,n)=>{let r;try{r=WP(L(c),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(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}Nc();try{let e=Me?.()??Fr,n=[],r=OP(c,void 0,e=>n.push(e)),i=AP(A??c,kP(e,r),e=>n.push(e));n.push(...Ic(i)),q(t,200,Et,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(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`}),zc=K(ut,async(e,t,n)=>{let r;try{let e=L(A??c),t=n.parentPath??[];r=n.delete?Vpe(e,n.file):n.field!==void 0&&n.removeField?zpe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Bpe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Lpe(e,n.file,n.field,n.constraint,t):Rpe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(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`)&&ae?.(`files`),Nc();try{let e=Me?.()??Fr,n=[],r=OP(c,void 0,e=>n.push(e)),i=AP(A??c,kP(e,r),e=>n.push(e));n.push(...Ic(i)),q(t,200,Et,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(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`}),Bc=K(Qt,async(e,t)=>{try{let e=L(A??c),{schemas:n,truncated:r}=hpe(e),i=new Set(n),a=!1;if(xe!==void 0){let t=eZ({contentDir:c,contentFilter:xe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&li(a)){let t=I(e,L(c,a));!t.startsWith(`..`)&&!ou(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,hte,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Vc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=o.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Hc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!SZ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=uZ(c,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Me?.()??Fr,a=[],o=await NP({projectDir:A??c,contentDir:c,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Vc});q(t,200,vt,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof DM){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Uc=new XN,Wc=cX();function Gc(e,t,n){let r=`${n} ${Pc()} ${t??``}`;return Wc.run(r,()=>ome(e,{targetPath:t})).promise}function Kc(e,t){G(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let qc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!tZ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Me?.()??Fr;q(t,200,Dee,await FP({projectDir:A??c,contentDir:c,baseConfig:i,targetPath:r,liveSourceFor:Vc,cache:Uc,auditGeneration:Pc}),{handler:`lint-audit`})}catch(e){if(e instanceof MP){Kc(t,`lint-audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Jc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!tZ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!tZ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=uZ(c,o)??`${o}.md`}let s=Me?.()??Fr,l=await Gc(oF({projectDir:A??c,contentDir:c,baseConfig:s,liveSourceFor:Vc,derivedDocumentIndex:O??null,linksValidation:Ne?.(),admittedDocNames:qt,docFilePathFor:e=>uZ(c,e),cache:Uc,auditGeneration:Pc}),i,XN.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){q(t,200,ma,ame(l),{handler:`audit`});return}q(t,200,see,l,{handler:`audit`})}catch(e){if(e instanceof MP){Kc(t,`audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Yc=K(pee,async(t,n,r)=>{try{let t=rZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Ct(t),a=uD(r,he);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Lx(i)||Rx(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=uZ(c,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}IM(L(c,f),c);let p=Me?.()??Fr,{stored:m}=Yn(a.summary),h=await s.getSession(i,o,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Ppe({projectDir:A??c,contentDir:c,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Zo(d),n=Yr[t]??rs(u??o);se?.setPresence(o,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{QC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,XC(h))},h.origin),a.kind!==`anonymous`&&EA(i,o,l,u,void 0,a.kind===`agent`?Jn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{se?.touchMode(o,`idle`)}let t=await zt(i);if(t?.kind===`failure`){Bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Vt(n,`lint-fix`);return}Mt(i,`lint-fix`);try{b=await Ti(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,Sa,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof DM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof iS){aS(n,e,`lint-fix`);return}if(e instanceof lS){fS(n,e,`lint-fix`);return}if(e instanceof tw){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Xc=`link-preview`,Zc=new wG({cacheDir:Pe?null:L(A??c,`.ok`,`local`,`link-previews`)}),Qc=null,$c=()=>(Qc??=Zc.init(),Qc),el=Fe??hG;async function tl(e){let t=await el(e);return t.ok?{ok:!0,metadata:await bG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:el})}:{ok:!1,reason:t.reason}}let nl=()=>{try{return Ie?.()===!0}catch{return!1}},rl=K(Gn,async(e,t,n)=>{try{if(!nl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Pt,{ok:!1,reason:`disabled`},{handler:Xc});return}await $c();let e=!1,r=await Zc.load(n.url,()=>(e=!0,tl(n.url)));Zc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Pt,i,{handler:Xc})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Xc,cause:e})}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>{let n=DG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Xc}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Xc}),!1)}}),il=Gde({service:et,getPrincipal:he,onChanged:()=>ae?.(`comments`)}),al=fW({GET:il.list,POST:il.create},{handler:`comments`}),ol=fW({GET:il.read,POST:il.mutate,DELETE:il.remove},{handler:`comment`}),{handleSkillsSearch:sl,handleSkillsPopular:cl,handleSkillsPublisher:ll,handleSkillsDetail:ul,handleSkillsPreview:dl,handleSkillsDiscover:fl,handleSkillsResolveRef:pl}=kve({log:Y,skillsHome:po,projectDir:A,contentDir:c,resolveSkillDirForRead:_o}),ml={"/api/config":_c,"/api/config/diagnostics":vc,"/api/generated-index/settings":fW({GET:K(Qt,async(e,t)=>{if(!u){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}q(t,200,bZ,u(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:K(fye,async(e,t,n)=>{if(!d){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}q(t,200,bZ,await d(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":al,"/api/comment":ol,"/api/asset":Zr,"/api/asset-text":$r,"/api/comment-counts":hr,"/api/link-preview":rl,"/api/folder-config":Ka,"/api/saved-themes":qa,"/api/saved-theme":Qa,"/api/template":so,"/api/template/import":co,"/api/templates":to,"/api/skill":cs,"/api/skill-file":hs,"/api/skill-file/rename":gs,"/api/skills":Ko,"/api/skills/installed":mr,"/api/skills/search":sl,"/api/skills/popular":cl,"/api/skills/publisher":ll,"/api/skills/detail":ul,"/api/skills/preview":dl,"/api/skills/discover":fl,"/api/skills/resolve-ref":pl,"/api/skill/import":Es,"/api/skills/import-bulk":Os,"/api/skill/edit-external":is,"/api/skill/duplicate":ss,"/api/skill/move-scope":os,"/api/skill-upload":Fs,"/api/skill/install":Is,"/api/skill/uninstall":Ls,"/api/skill/restore":Bs,"/api/skill/reimport":Ws,"/api/skill/revert":Gs,"/api/skill/track-in-git":Wo,"/api/skill-targets":Rs,"/api/search":$s,"/api/semantic-status":jc,"/api/lint/config":Lc,"/api/lint/markdownlint-config":Rc,"/api/lint/frontmatter-schema":zc,"/api/lint/frontmatter-schemas":Bc,"/api/lint":Hc,"/api/lint/audit":qc,"/api/lint/fix":Yc,"/api/audit":Jc,"/api/create-page":ti,"/api/create-folder":ri,"/api/duplicate-path":ii,"/api/rename-path":ai,"/api/delete-path":oi,"/api/trash/cleanup":si,"/api/upload":ci,"/api/agent-write":ar,"/api/agent-write-md":or,"/api/agent-write-batch":cr,"/api/frontmatter-patch":pr,"/api/agent-patch":_r,"/api/agent-undo":yr,"/api/agent-activity":br,"/api/agent-burst-diff":Sr,"/api/save-version":Ir,"/api/history":Rr,"/api/rollback":Br,"/api/__embed-detect":Gr,"/api/server-info":Vr,"/api/acp/catalog":Ur,"/api/share/construct-url":rc,"/api/share/target-status":oc,"/api/git/branch-info":ic,"/api/git/checkout":sc,"/api/share/publish/owners":uc,"/api/share/publish/name-check":dc,"/api/share/publish":fc,"/api/principal":Wr,"/api/rescue":ei,"/api/workspace":Kr,"/api/sync/status":xa,"/api/sync/trigger":Ca,"/api/sync/conflicts":Ta,"/api/sync/conflict-content":Oa,"/api/sync/resolve-conflict":Da,"/api/local-op/clone":wi,"/api/local-op/ok-init":Pi,"/api/local-op/auth/login":Xi,"/api/local-op/auth/status":ra,"/api/local-op/auth/pat":aa,"/api/local-op/auth/gh-login":$i,"/api/local-op/auth/cancel":ta,"/api/local-op/auth/repos":ca,"/api/local-op/auth/signout":pa,"/api/local-op/auth/set-identity":ba,"/api/local-op/embeddings/set-key":wc,"/api/local-op/embeddings/clear-key":Tc,"/api/local-op/embeddings/test":Ac,"/api/installed-agents":za,"/api/spawn-cursor":nc,"/api/handoff":tc,"/api/install-skill":Ra,"/api/skill/install-state":ec,"/api/seed/plan":ka,"/api/seed/apply":Aa,"/api/seed/install-pack-skill":Pa,"/api/seed/packs":La,"/api/client-logs":pc};E&&(ml[`/api/test-reset`]=kr,ml[`/api/test-flush-git`]=Or,ml[`/api/test-rescan-backlinks`]=Ar,ml[`/api/test-rescan-files`]=jr);let hl=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/saved-theme./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),gl=[`/api/local-op/`],_l=IB({log:Y,policy:n,ephemeral:Pe,table:{resolve(e){let t=ml[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await zr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>hl.has(e)||gl.some(t=>e.startsWith(t))}}),vl=cW({hocuspocus:o,derivedDocumentIndex:O,getFileIndex:p,isSafeDocName:SZ,readPageTitleForDocName:tt,readPageTitleForLinkedDocName:st,readFrontmatterMetadataForLinkedDocName:gt,collectAdmittedDocNames:qt,resolveAlias:Ct,respondToDerivedIndexQueryFailure:sn}),yl=[vl,pW({hocuspocus:o,agentPresenceBroadcaster:se,isAllowedWorkspaceHostHeader:i,log:Y}),Ve],bl=yl.flatMap(e=>[...e.paths]);FU(bl,ml);let xl=yl.map(e=>IB({log:Y,policy:n,ephemeral:Pe,table:e.table})),Sl={paths:bl,dispatch:async(e,t)=>{for(let n of xl)if(await n(e,t))return!0;return!1}},Cl=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Cl)if(ml[e]===void 0&&vl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await _l(e,t)},nativeApi:Sl,localApi:dW({resolve:e=>{if(!Cl.has(e))return;let t=ml[e];return t===void 0?vl.table.resolve(e)?.dispatch:t}})}}function wZ(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&&!EB(f,o)){G(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!OB(e.headers.host,o)){G(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:xB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=RY(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=Ae.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 TZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function mye(e){let t;try{t=wu(e.contentDir,{withFileTypes:!0})}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ex(n.name,ne)&&e.basenameIndex.add(n.name)}async function EZ(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=TZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=F(i,o.name),s=MM(I(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await zu(a)}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Hu(a)}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!NM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Uu(i)}catch(t){let n=TZ(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()&&Ex(a,fe)&&!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()&&Ex(a,fe)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const DZ=w({principalId:v().optional(),tabSessionId:v().optional(),expectedServerInstanceId:v().optional(),expectedBranch:v().optional(),expectedDocLineageEpoch:v().optional(),clientProtocolVersion:j().optional(),clientRuntimeVersion:v().optional(),clientKind:v().optional()}).loose(),OZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function kZ(e){return OZ.includes(e)}function AZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function hye(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!kZ(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 jZ=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=AZ(e,this.payload)}};function MZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=DZ.safeParse(t);return n.success?n.data:void 0}var NZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function PZ(e,t,n=``){e=Qte(`.`,e);let r=Xte(e),i=0,a,o;for(;i<r.length;i++)a=Xu(e,r[i]),o=Zte(a),o.isDirectory()?PZ(a,t,Xu(n,r[i])):t(Xu(n,r[i]),a,o)}function gye(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=une.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const _ye=()=>{};function vye(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function FZ(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 yye(e,t,n){let r=0,i,a=FZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function bye(e,t,n,r){let i=0,a=FZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=su(F(e,c=a[i])),o.startsWith(e)&&fu.existsSync(o)){if(s=fu.statSync(o),s.isDirectory())continue;return l=IZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function xye(e,t){return t.statusCode=404,t.end()}function Sye(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 Cye={".br":`br`,".gz":`gzip`};function IZ(e,t,n){let r=Cye[e.slice(-3)],i=Q_e(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 LZ(e,t={}){e=L(e||`.`);let n=t.onNoMatch||xye,r=t.setHeaders||_ye,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||PZ(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=IZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?bye.bind(0,e+R,l):yye.bind(0,s);return function(e,t,s){let f=[``],m=gye(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&&!vye(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),Sye(e,t,g.abs,g.stats,g.headers)}}const RZ=N(`conflict-storage`);var zZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=F(RD(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){RZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){RZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=P(this.storePath);z(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 RZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n){let r=this.conflicts.find(t=>t.file===e);if(!r)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-Ci-ka9U-.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=L(this.projectDir),r=L(t,e);if(!NM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fL(r,t),Js(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),RZ.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:n});r=e.length>0}catch(e){RZ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),RZ.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=L(this.projectDir),i=L(r,e.file);if(!NM(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(fL(i,r),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-Ci-ka9U-.mjs`),n=await t(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,e.theirsSha]);fL(i,r),Js(i,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Js(i,n,`utf-8`);break;case`delete`:z(i)&&Ps(i);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function wye(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 Tye(e,t){let n=RD(e);try{yu(n,{recursive:!0}),ju(F(n,Ci),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=nc(e);yu(P(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 BZ=new Map;let VZ=!1;function Eye(e,t){try{let n=wye(e,t);for(let e of BZ.keys())Tye(e,n)}catch{}}function Dye(e){BZ.set(e,(BZ.get(e)??0)+1),VZ||(VZ=!0,process.on(`uncaughtExceptionMonitor`,Eye));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=BZ.get(e)??0;n<=1?BZ.delete(e):BZ.set(e,n-1)}}}function HZ(e){let t=e.scheduler??$r,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function UZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function WZ(e){if(!z(e))return{};let t;try{t=(0,oD.parse)(B(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(!UZ(t))return{};let n=t.telemetry;if(!UZ(n))return{};let r=n.localSink;return UZ(r)?r:{}}function GZ(e){return typeof e==`boolean`?e:void 0}function Oye(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function KZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function qZ(e){if(UZ(e))return Oye(e.maxBytes)}function kye(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=WZ(Rs(`project`,e.projectDir)),n=WZ(Rs(`project-local`,e.projectDir));if((GZ(n.enabled)??GZ(t.enabled)??!0)===!1)return null;let r=qZ(n.spans)??qZ(t.spans)??52428800,a=qZ(n.logs)??qZ(t.logs)??26214400,o=KZ(n.attributeDenylist)??KZ(t.attributeDenylist)??i;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:o},logs:{projectDir:e.projectDir,maxBytes:a}}}var JZ;(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})(JZ||={});var Aye;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Aye||={});const YZ=JZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),XZ=e=>{switch(typeof e){case`undefined`:return YZ.undefined;case`string`:return YZ.string;case`number`:return Number.isNaN(e)?YZ.nan:YZ.number;case`boolean`:return YZ.boolean;case`function`:return YZ.function;case`bigint`:return YZ.bigint;case`symbol`:return YZ.symbol;case`object`:return Array.isArray(e)?YZ.array:e===null?YZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?YZ.promise:typeof Map<`u`&&e instanceof Map?YZ.map:typeof Set<`u`&&e instanceof Set?YZ.set:typeof Date<`u`&&e instanceof Date?YZ.date:YZ.object;default:return YZ.unknown}},X=JZ.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 ZZ=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,JZ.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()}};ZZ.create=e=>new ZZ(e);const QZ=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===YZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,JZ.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${JZ.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${JZ.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${JZ.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.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}"`:JZ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.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 X.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 X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,JZ.assertNever(e)}return{message:n}};let jye=QZ;function $Z(){return jye}const eQ=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 tQ(e,t){let n=$Z(),r=eQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===QZ?void 0:QZ].filter(e=>!!e)});e.common.issues.push(r)}var nQ=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 rQ;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 rQ;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 rQ=Object.freeze({status:`aborted`}),iQ=e=>({status:`dirty`,value:e}),aQ=e=>({status:`valid`,value:e}),oQ=e=>e.status===`aborted`,sQ=e=>e.status===`dirty`,cQ=e=>e.status===`valid`,lQ=e=>typeof Promise<`u`&&e instanceof Promise;var uQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(uQ||={});var dQ=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 fQ=(e,t)=>{if(cQ(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 ZZ(e.common.issues);return this._error=t,this._error}}};function pQ(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 mQ=class{get description(){return this._def.description}_getType(e){return XZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:XZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nQ,ctx:{common:e.parent.common,data:e.data,parsedType:XZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lQ(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:XZ(e)};return fQ(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:XZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return cQ(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=>cQ(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:XZ(e)},r=this._parse({data:e,path:n.path,parent:n});return fQ(n,await(lQ(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:X.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 KQ({schema:this,typeName:Z.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 qQ.create(this,this._def)}nullable(){return JQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return AQ.create(this)}promise(){return GQ.create(this,this._def)}or(e){return NQ.create([this,e],this._def)}and(e){return IQ.create(this,e,this._def)}transform(e){return new KQ({...pQ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new YQ({...pQ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new QQ({typeName:Z.ZodBranded,type:this,...pQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new XQ({...pQ(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return $Q.create(this,e)}readonly(){return e$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Mye=/^c[^\s-]{8,}$/i,Nye=/^[0-9a-z]+$/,Pye=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fye=/^[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,Iye=/^[a-z0-9_-]{21}$/i,Lye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rye=/^[-+]?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)?)??$/,zye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let hQ;const Bye=/^(?:(?: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])$/,Vye=/^(?:(?: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])$/,Hye=/^(([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]))$/,Uye=/^(([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])$/,Wye=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gQ=`((\\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])))`,Kye=RegExp(`^${gQ}$`);function _Q(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 qye(e){return RegExp(`^${_Q(e)}$`)}function Jye(e){let t=`${gQ}T${_Q(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Yye(e,t){return!!((t===`v4`||!t)&&Bye.test(e)||(t===`v6`||!t)&&Hye.test(e))}function Xye(e,t){if(!Lye.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 Zye(e,t){return!!((t===`v4`||!t)&&Vye.test(e)||(t===`v6`||!t)&&Uye.test(e))}var vQ=class e extends mQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==YZ.string){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.string,received:t.parsedType}),rQ}let t=new nQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.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),tQ(n,{code:X.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?tQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&tQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)zye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)hQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),hQ.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Fye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Iye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Mye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Nye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Pye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),tQ(n,{validation:`url`,code:X.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),tQ(n,{validation:`regex`,code:X.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),tQ(n,{code:X.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),tQ(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Jye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Kye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?qye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Rye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Yye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Xye(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Zye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):JZ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...uQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...uQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...uQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...uQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...uQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...uQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...uQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...uQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...uQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...uQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...uQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...uQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...uQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...uQ.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,...uQ.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,...uQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...uQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...uQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...uQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...uQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...uQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...uQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...uQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...uQ.errToObj(t)})}nonempty(e){return this.min(1,uQ.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}};vQ.create=e=>new vQ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...pQ(e)});function Qye(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 yQ=class e extends mQ{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)!==YZ.number){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.number,received:t.parsedType}),rQ}let t,n=new nQ;for(let r of this._def.checks)r.kind===`int`?JZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.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),tQ(t,{code:X.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),tQ(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Qye(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.not_finite,message:r.message}),n.dirty()):JZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,uQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,uQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,uQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,uQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:uQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:uQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:uQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:uQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:uQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:uQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:uQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:uQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:uQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:uQ.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`&&JZ.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)}};yQ.create=e=>new yQ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...pQ(e)});var bQ=class e extends mQ{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)!==YZ.bigint)return this._getInvalidInput(e);let t,n=new nQ;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),tQ(t,{code:X.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),tQ(t,{code:X.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),tQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):JZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.bigint,received:t.parsedType}),rQ}gte(e,t){return this.setLimit(`min`,e,!0,uQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,uQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,uQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,uQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:uQ.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:uQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:uQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:uQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:uQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:uQ.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}};bQ.create=e=>new bQ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...pQ(e)});var xQ=class extends mQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==YZ.boolean){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.boolean,received:t.parsedType}),rQ}return aQ(e.data)}};xQ.create=e=>new xQ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...pQ(e)});var SQ=class e extends mQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==YZ.date){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.date,received:t.parsedType}),rQ}if(Number.isNaN(e.data.getTime()))return tQ(this._getOrReturnCtx(e),{code:X.invalid_date}),rQ;let t=new nQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.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),tQ(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):JZ.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:uQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:uQ.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)}};SQ.create=e=>new SQ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...pQ(e)});var CQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.symbol){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.symbol,received:t.parsedType}),rQ}return aQ(e.data)}};CQ.create=e=>new CQ({typeName:Z.ZodSymbol,...pQ(e)});var wQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.undefined){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.undefined,received:t.parsedType}),rQ}return aQ(e.data)}};wQ.create=e=>new wQ({typeName:Z.ZodUndefined,...pQ(e)});var TQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.null){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.null,received:t.parsedType}),rQ}return aQ(e.data)}};TQ.create=e=>new TQ({typeName:Z.ZodNull,...pQ(e)});var EQ=class extends mQ{constructor(){super(...arguments),this._any=!0}_parse(e){return aQ(e.data)}};EQ.create=e=>new EQ({typeName:Z.ZodAny,...pQ(e)});var DQ=class extends mQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return aQ(e.data)}};DQ.create=e=>new DQ({typeName:Z.ZodUnknown,...pQ(e)});var OQ=class extends mQ{_parse(e){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.never,received:t.parsedType}),rQ}};OQ.create=e=>new OQ({typeName:Z.ZodNever,...pQ(e)});var kQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.undefined){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.void,received:t.parsedType}),rQ}return aQ(e.data)}};kQ.create=e=>new kQ({typeName:Z.ZodVoid,...pQ(e)});var AQ=class e extends mQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==YZ.array)return tQ(t,{code:X.invalid_type,expected:YZ.array,received:t.parsedType}),rQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(tQ(t,{code:e?X.too_big:X.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&&(tQ(t,{code:X.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&&(tQ(t,{code:X.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 dQ(t,e,t.path,n)))).then(e=>nQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new dQ(t,e,t.path,n)));return nQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:uQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:uQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:uQ.toString(n)}})}nonempty(e){return this.min(1,e)}};AQ.create=(e,t)=>new AQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...pQ(t)});function jQ(e){if(e instanceof MQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=qQ.create(jQ(r))}return new MQ({...e._def,shape:()=>t})}else if(e instanceof AQ)return new AQ({...e._def,type:jQ(e.element)});else if(e instanceof qQ)return qQ.create(jQ(e.unwrap()));else if(e instanceof JQ)return JQ.create(jQ(e.unwrap()));else if(e instanceof LQ)return LQ.create(e.items.map(e=>jQ(e)));else return e}var MQ=class e extends mQ{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=JZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==YZ.object){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.object,received:t.parsedType}),rQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof OQ&&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 dQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof OQ){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&&(tQ(n,{code:X.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 dQ(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=>nQ.mergeObjectSync(t,e)):nQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return uQ.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:uQ.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:Z.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 JZ.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 JZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return jQ(this)}partial(t){let n={};for(let e of JZ.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 JZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof qQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return HQ(JZ.objectKeys(this.shape))}};MQ.create=(e,t)=>new MQ({shape:()=>e,unknownKeys:`strip`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)}),MQ.strictCreate=(e,t)=>new MQ({shape:()=>e,unknownKeys:`strict`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)}),MQ.lazycreate=(e,t)=>new MQ({shape:e,unknownKeys:`strip`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)});var NQ=class extends mQ{_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 ZZ(e.ctx.common.issues));return tQ(t,{code:X.invalid_union,unionErrors:n}),rQ}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 ZZ(e));return tQ(t,{code:X.invalid_union,unionErrors:i}),rQ}}get options(){return this._def.options}};NQ.create=(e,t)=>new NQ({options:e,typeName:Z.ZodUnion,...pQ(t)});const PQ=e=>e instanceof BQ?PQ(e.schema):e instanceof KQ?PQ(e.innerType()):e instanceof VQ?[e.value]:e instanceof UQ?e.options:e instanceof WQ?JZ.objectValues(e.enum):e instanceof YQ?PQ(e._def.innerType):e instanceof wQ?[void 0]:e instanceof TQ?[null]:e instanceof qQ?[void 0,...PQ(e.unwrap())]:e instanceof JQ?[null,...PQ(e.unwrap())]:e instanceof QQ||e instanceof e$?PQ(e.unwrap()):e instanceof XQ?PQ(e._def.innerType):[];var $ye=class e extends mQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==YZ.object)return tQ(t,{code:X.invalid_type,expected:YZ.object,received:t.parsedType}),rQ;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}):(tQ(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),rQ)}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=PQ(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:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...pQ(r)})}};function FQ(e,t){let n=XZ(e),r=XZ(t);if(e===t)return{valid:!0,data:e};if(n===YZ.object&&r===YZ.object){let n=JZ.objectKeys(t),r=JZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=FQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===YZ.array&&r===YZ.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=FQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===YZ.date&&r===YZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var IQ=class extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(oQ(e)||oQ(r))return rQ;let i=FQ(e.value,r.value);return i.valid?((sQ(e)||sQ(r))&&t.dirty(),{status:t.value,value:i.data}):(tQ(n,{code:X.invalid_intersection_types}),rQ)};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}))}};IQ.create=(e,t,n)=>new IQ({left:e,right:t,typeName:Z.ZodIntersection,...pQ(n)});var LQ=class e extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==YZ.array)return tQ(n,{code:X.invalid_type,expected:YZ.array,received:n.parsedType}),rQ;if(n.data.length<this._def.items.length)return tQ(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),rQ;!this._def.rest&&n.data.length>this._def.items.length&&(tQ(n,{code:X.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 dQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>nQ.mergeArray(t,e)):nQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};LQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new LQ({items:e,typeName:Z.ZodTuple,rest:null,...pQ(t)})};var ebe=class e extends mQ{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!==YZ.object)return tQ(n,{code:X.invalid_type,expected:YZ.object,received:n.parsedType}),rQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new dQ(n,e,n.path,e)),value:a._parse(new dQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?nQ.mergeObjectAsync(t,r):nQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof mQ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...pQ(r)}):new e({keyType:vQ.create(),valueType:t,typeName:Z.ZodRecord,...pQ(n)})}},RQ=class extends mQ{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!==YZ.map)return tQ(n,{code:X.invalid_type,expected:YZ.map,received:n.parsedType}),rQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new dQ(n,e,n.path,[a,`key`])),value:i._parse(new dQ(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 rQ;(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 rQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};RQ.create=(e,t,n)=>new RQ({valueType:t,keyType:e,typeName:Z.ZodMap,...pQ(n)});var zQ=class e extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==YZ.set)return tQ(n,{code:X.invalid_type,expected:YZ.set,received:n.parsedType}),rQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(tQ(n,{code:X.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&&(tQ(n,{code:X.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 rQ;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 dQ(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:uQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:uQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};zQ.create=(e,t)=>new zQ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...pQ(t)});var tbe=class e extends mQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==YZ.function)return tQ(t,{code:X.invalid_type,expected:YZ.function,received:t.parsedType}),rQ;function n(e,n){return eQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$Z(),QZ].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return eQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$Z(),QZ].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof GQ){let e=this;return aQ(async function(...t){let o=new ZZ([]),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 aQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new ZZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new ZZ([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:LQ.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||LQ.create([]).rest(DQ.create()),returns:n||DQ.create(),typeName:Z.ZodFunction,...pQ(r)})}},BQ=class extends mQ{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})}};BQ.create=(e,t)=>new BQ({getter:e,typeName:Z.ZodLazy,...pQ(t)});var VQ=class extends mQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return tQ(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),rQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};VQ.create=(e,t)=>new VQ({value:e,typeName:Z.ZodLiteral,...pQ(t)});function HQ(e,t){return new UQ({values:e,typeName:Z.ZodEnum,...pQ(t)})}var UQ=class e extends mQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return tQ(t,{expected:JZ.joinValues(n),received:t.parsedType,code:X.invalid_type}),rQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return tQ(t,{received:t.data,code:X.invalid_enum_value,options:n}),rQ}return aQ(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})}};UQ.create=HQ;var WQ=class extends mQ{_parse(e){let t=JZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==YZ.string&&n.parsedType!==YZ.number){let e=JZ.objectValues(t);return tQ(n,{expected:JZ.joinValues(e),received:n.parsedType,code:X.invalid_type}),rQ}if(this._cache||=new Set(JZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=JZ.objectValues(t);return tQ(n,{received:n.data,code:X.invalid_enum_value,options:e}),rQ}return aQ(e.data)}get enum(){return this._def.values}};WQ.create=(e,t)=>new WQ({values:e,typeName:Z.ZodNativeEnum,...pQ(t)});var GQ=class extends mQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==YZ.promise&&t.common.async===!1?(tQ(t,{code:X.invalid_type,expected:YZ.promise,received:t.parsedType}),rQ):aQ((t.parsedType===YZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};GQ.create=(e,t)=>new GQ({type:e,typeName:Z.ZodPromise,...pQ(t)});var KQ=class extends mQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.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=>{tQ(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 rQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?rQ:r.status===`dirty`||t.value===`dirty`?iQ(r.value):r});{if(t.value===`aborted`)return rQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?rQ:r.status===`dirty`||t.value===`dirty`?iQ(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`?rQ:(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`?rQ:(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(!cQ(e))return rQ;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=>cQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):rQ);JZ.assertNever(r)}};KQ.create=(e,t,n)=>new KQ({schema:e,typeName:Z.ZodEffects,effect:t,...pQ(n)}),KQ.createWithPreprocess=(e,t,n)=>new KQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...pQ(n)});var qQ=class extends mQ{_parse(e){return this._getType(e)===YZ.undefined?aQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qQ.create=(e,t)=>new qQ({innerType:e,typeName:Z.ZodOptional,...pQ(t)});var JQ=class extends mQ{_parse(e){return this._getType(e)===YZ.null?aQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};JQ.create=(e,t)=>new JQ({innerType:e,typeName:Z.ZodNullable,...pQ(t)});var YQ=class extends mQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===YZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};YQ.create=(e,t)=>new YQ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...pQ(t)});var XQ=class extends mQ{_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 lQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new ZZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};XQ.create=(e,t)=>new XQ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...pQ(t)});var ZQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.nan){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.nan,received:t.parsedType}),rQ}return{status:`valid`,value:e.data}}};ZQ.create=e=>new ZQ({typeName:Z.ZodNaN,...pQ(e)});var QQ=class extends mQ{_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}},$Q=class e extends mQ{_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`?rQ:e.status===`dirty`?(t.dirty(),iQ(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`?rQ: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:Z.ZodPipeline})}},e$=class extends mQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(cQ(e)&&(e.value=Object.freeze(e.value)),e);return lQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};e$.create=(e,t)=>new e$({innerType:e,typeName:Z.ZodReadonly,...pQ(t)}),MQ.lazycreate;var Z;(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`})(Z||={}),vQ.create,yQ.create,ZQ.create,bQ.create,xQ.create,SQ.create,CQ.create,wQ.create,TQ.create,EQ.create,DQ.create,OQ.create,kQ.create,AQ.create;const nbe=MQ.create;MQ.strictCreate,NQ.create,$ye.create,IQ.create,LQ.create,ebe.create,RQ.create,zQ.create,tbe.create,BQ.create,VQ.create,UQ.create,WQ.create,GQ.create,KQ.create,qQ.create,JQ.create,KQ.createWithPreprocess,$Q.create;const rbe=Me(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);b.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Oe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>le(e,t,n),e.parseAsync=async(t,n)=>y(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ce(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)=>re(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ibe=Me(`ZodMiniObject`,(e,t)=>{m.init(e,t),rbe.init(e,t),r(e,`shape`,()=>t.shape)});function t$(e,t){return new ibe({type:`object`,shape:e??{},...he(t)})}function n$(e){return!!e._zod}function r$(e){let t=Object.values(e);if(t.length===0)return t$({});let n=t.every(n$),r=t.every(e=>!n$(e));if(n)return t$(e);if(r)return nbe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function i$(e,t){return n$(e)?le(e,t):e.safeParse(t)}async function a$(e,t){return n$(e)?await ce(e,t):await e.safeParseAsync(t)}function o$(e){if(!e)return;let t;if(t=n$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function s$(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 r$(e)}}if(n$(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 c$(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 abe(e){return e.description}function obe(e){if(n$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function l$(e){if(n$(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 u$=`2025-11-25`,d$=[u$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],f$=`io.modelcontextprotocol/related-task`,p$=Le(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),m$=S([v(),j().int()]),h$=v();a({ttl:j().optional(),pollInterval:j().optional()});const sbe=w({ttl:j().optional()}),cbe=w({taskId:v()}),g$=a({progressToken:m$.optional(),[f$]:cbe.optional()}),_$=w({_meta:g$.optional()}),v$=_$.extend({task:sbe.optional()}),lbe=e=>v$.safeParse(e).success,y$=w({method:v(),params:_$.loose().optional()}),b$=w({_meta:g$.optional()}),x$=w({method:v(),params:b$.loose().optional()}),S$=a({_meta:g$.optional()}),C$=S([v(),j().int()]),w$=w({jsonrpc:M(`2.0`),id:C$,...y$.shape}).strict(),T$=e=>w$.safeParse(e).success,E$=w({jsonrpc:M(`2.0`),...x$.shape}).strict(),ube=e=>E$.safeParse(e).success,D$=w({jsonrpc:M(`2.0`),id:C$,result:S$}).strict(),O$=e=>D$.safeParse(e).success;var k$;(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`})(k$||={});const A$=w({jsonrpc:M(`2.0`),id:C$.optional(),error:w({code:j().int(),message:v(),data:D().optional()})}).strict(),j$=e=>A$.safeParse(e).success,M$=S([w$,E$,D$,A$]);S([D$,A$]);const N$=S$.strict(),dbe=b$.extend({requestId:C$.optional(),reason:v().optional()}),P$=x$.extend({method:M(`notifications/cancelled`),params:dbe}),F$=w({icons:k(w({src:v(),mimeType:v().optional(),sizes:k(v()).optional(),theme:ze([`light`,`dark`]).optional()})).optional()}),I$=w({name:v(),title:v().optional()}),L$=I$.extend({...I$.shape,...F$.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),fbe=te(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,u(w({form:u(w({applyDefaults:l().optional()}),p(v(),D())).optional(),url:p$.optional()}),p(v(),D()).optional())),pbe=a({list:p$.optional(),cancel:p$.optional(),requests:a({sampling:a({createMessage:p$.optional()}).optional(),elicitation:a({create:p$.optional()}).optional()}).optional()}),mbe=a({list:p$.optional(),cancel:p$.optional(),requests:a({tools:a({call:p$.optional()}).optional()}).optional()}),hbe=w({experimental:p(v(),p$).optional(),sampling:w({context:p$.optional(),tools:p$.optional()}).optional(),elicitation:fbe.optional(),roots:w({listChanged:l().optional()}).optional(),tasks:pbe.optional(),extensions:p(v(),p$).optional()}),gbe=_$.extend({protocolVersion:v(),capabilities:hbe,clientInfo:L$}),R$=y$.extend({method:M(`initialize`),params:gbe}),z$=e=>R$.safeParse(e).success,_be=w({experimental:p(v(),p$).optional(),logging:p$.optional(),completions:p$.optional(),prompts:w({listChanged:l().optional()}).optional(),resources:w({subscribe:l().optional(),listChanged:l().optional()}).optional(),tools:w({listChanged:l().optional()}).optional(),tasks:mbe.optional(),extensions:p(v(),p$).optional()}),vbe=S$.extend({protocolVersion:v(),capabilities:_be,serverInfo:L$,instructions:v().optional()}),B$=x$.extend({method:M(`notifications/initialized`),params:b$.optional()}),ybe=e=>B$.safeParse(e).success,V$=y$.extend({method:M(`ping`),params:_$.optional()}),bbe=w({progress:j(),total:E(j()),message:E(v())}),xbe=w({...b$.shape,...bbe.shape,progressToken:m$}),H$=x$.extend({method:M(`notifications/progress`),params:xbe}),Sbe=_$.extend({cursor:h$.optional()}),U$=y$.extend({params:Sbe.optional()}),W$=S$.extend({nextCursor:h$.optional()}),Cbe=ze([`working`,`input_required`,`completed`,`failed`,`cancelled`]),G$=w({taskId:v(),status:Cbe,ttl:S([j(),A()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:E(j()),statusMessage:E(v())}),K$=S$.extend({task:G$}),wbe=b$.merge(G$),q$=x$.extend({method:M(`notifications/tasks/status`),params:wbe}),J$=y$.extend({method:M(`tasks/get`),params:_$.extend({taskId:v()})}),Y$=S$.merge(G$),X$=y$.extend({method:M(`tasks/result`),params:_$.extend({taskId:v()})});S$.loose();const Z$=U$.extend({method:M(`tasks/list`)}),Q$=W$.extend({tasks:k(G$)}),$$=y$.extend({method:M(`tasks/cancel`),params:_$.extend({taskId:v()})}),Tbe=S$.merge(G$),e1=w({uri:v(),mimeType:E(v()),_meta:p(v(),D()).optional()}),t1=e1.extend({text:v()}),n1=v().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),r1=e1.extend({blob:n1}),i1=ze([`user`,`assistant`]),a1=w({audience:k(i1).optional(),priority:j().min(0).max(1).optional(),lastModified:se({offset:!0}).optional()}),o1=w({...I$.shape,...F$.shape,uri:v(),description:E(v()),mimeType:E(v()),size:E(j()),annotations:a1.optional(),_meta:E(a({}))}),Ebe=w({...I$.shape,...F$.shape,uriTemplate:v(),description:E(v()),mimeType:E(v()),annotations:a1.optional(),_meta:E(a({}))}),s1=U$.extend({method:M(`resources/list`)}),Dbe=W$.extend({resources:k(o1)}),c1=U$.extend({method:M(`resources/templates/list`)}),Obe=W$.extend({resourceTemplates:k(Ebe)}),l1=_$.extend({uri:v()}),kbe=l1,u1=y$.extend({method:M(`resources/read`),params:kbe}),Abe=S$.extend({contents:k(S([t1,r1]))}),jbe=x$.extend({method:M(`notifications/resources/list_changed`),params:b$.optional()}),Mbe=l1,Nbe=y$.extend({method:M(`resources/subscribe`),params:Mbe}),Pbe=l1,Fbe=y$.extend({method:M(`resources/unsubscribe`),params:Pbe}),Ibe=b$.extend({uri:v()}),Lbe=x$.extend({method:M(`notifications/resources/updated`),params:Ibe}),Rbe=w({name:v(),description:E(v()),required:E(l())}),zbe=w({...I$.shape,...F$.shape,description:E(v()),arguments:E(k(Rbe)),_meta:E(a({}))}),d1=U$.extend({method:M(`prompts/list`)}),Bbe=W$.extend({prompts:k(zbe)}),Vbe=_$.extend({name:v(),arguments:p(v(),v()).optional()}),f1=y$.extend({method:M(`prompts/get`),params:Vbe}),p1=w({type:M(`text`),text:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),m1=w({type:M(`image`),data:n1,mimeType:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),h1=w({type:M(`audio`),data:n1,mimeType:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),Hbe=w({type:M(`tool_use`),name:v(),id:v(),input:p(v(),D()),_meta:p(v(),D()).optional()}),Ube=w({type:M(`resource`),resource:S([t1,r1]),annotations:a1.optional(),_meta:p(v(),D()).optional()}),g1=S([p1,m1,h1,o1.extend({type:M(`resource_link`)}),Ube]),Wbe=w({role:i1,content:g1}),Gbe=S$.extend({description:v().optional(),messages:k(Wbe)}),Kbe=x$.extend({method:M(`notifications/prompts/list_changed`),params:b$.optional()}),qbe=w({title:v().optional(),readOnlyHint:l().optional(),destructiveHint:l().optional(),idempotentHint:l().optional(),openWorldHint:l().optional()}),Jbe=w({taskSupport:ze([`required`,`optional`,`forbidden`]).optional()}),_1=w({...I$.shape,...F$.shape,description:v().optional(),inputSchema:w({type:M(`object`),properties:p(v(),p$).optional(),required:k(v()).optional()}).catchall(D()),outputSchema:w({type:M(`object`),properties:p(v(),p$).optional(),required:k(v()).optional()}).catchall(D()).optional(),annotations:qbe.optional(),execution:Jbe.optional(),_meta:p(v(),D()).optional()}),v1=U$.extend({method:M(`tools/list`)}),Ybe=W$.extend({tools:k(_1)}),y1=S$.extend({content:k(g1).default([]),structuredContent:p(v(),D()).optional(),isError:l().optional()});y1.or(S$.extend({toolResult:D()}));const Xbe=v$.extend({name:v(),arguments:p(v(),D()).optional()}),b1=y$.extend({method:M(`tools/call`),params:Xbe}),Zbe=x$.extend({method:M(`notifications/tools/list_changed`),params:b$.optional()});w({autoRefresh:l().default(!0),debounceMs:j().int().nonnegative().default(300)});const x1=ze([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Qbe=_$.extend({level:x1}),S1=y$.extend({method:M(`logging/setLevel`),params:Qbe}),$be=b$.extend({level:x1,logger:v().optional(),data:D()}),exe=x$.extend({method:M(`notifications/message`),params:$be}),txe=w({hints:k(w({name:v().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),nxe=w({mode:ze([`auto`,`required`,`none`]).optional()}),rxe=w({type:M(`tool_result`),toolUseId:v().describe(`The unique identifier for the corresponding tool call.`),content:k(g1).default([]),structuredContent:w({}).loose().optional(),isError:l().optional(),_meta:p(v(),D()).optional()}),ixe=oe(`type`,[p1,m1,h1]),C1=oe(`type`,[p1,m1,h1,Hbe,rxe]),axe=w({role:i1,content:S([C1,k(C1)]),_meta:p(v(),D()).optional()}),oxe=v$.extend({messages:k(axe),modelPreferences:txe.optional(),systemPrompt:v().optional(),includeContext:ze([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:k(v()).optional(),metadata:p$.optional(),tools:k(_1).optional(),toolChoice:nxe.optional()}),sxe=y$.extend({method:M(`sampling/createMessage`),params:oxe}),w1=S$.extend({model:v(),stopReason:E(ze([`endTurn`,`stopSequence`,`maxTokens`]).or(v())),role:i1,content:ixe}),T1=S$.extend({model:v(),stopReason:E(ze([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(v())),role:i1,content:S([C1,k(C1)])}),cxe=w({type:M(`boolean`),title:v().optional(),description:v().optional(),default:l().optional()}),lxe=w({type:M(`string`),title:v().optional(),description:v().optional(),minLength:j().optional(),maxLength:j().optional(),format:ze([`email`,`uri`,`date`,`date-time`]).optional(),default:v().optional()}),uxe=w({type:ze([`number`,`integer`]),title:v().optional(),description:v().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),dxe=w({type:M(`string`),title:v().optional(),description:v().optional(),enum:k(v()),default:v().optional()}),fxe=w({type:M(`string`),title:v().optional(),description:v().optional(),oneOf:k(w({const:v(),title:v()})),default:v().optional()}),pxe=S([S([w({type:M(`string`),title:v().optional(),description:v().optional(),enum:k(v()),enumNames:k(v()).optional(),default:v().optional()}),S([dxe,fxe]),S([w({type:M(`array`),title:v().optional(),description:v().optional(),minItems:j().optional(),maxItems:j().optional(),items:w({type:M(`string`),enum:k(v())}),default:k(v()).optional()}),w({type:M(`array`),title:v().optional(),description:v().optional(),minItems:j().optional(),maxItems:j().optional(),items:w({anyOf:k(w({const:v(),title:v()}))}),default:k(v()).optional()})])]),cxe,lxe,uxe]),mxe=S([v$.extend({mode:M(`form`).optional(),message:v(),requestedSchema:w({type:M(`object`),properties:p(v(),pxe),required:k(v()).optional()})}),v$.extend({mode:M(`url`),message:v(),elicitationId:v(),url:v().url()})]),hxe=y$.extend({method:M(`elicitation/create`),params:mxe}),gxe=b$.extend({elicitationId:v()}),_xe=x$.extend({method:M(`notifications/elicitation/complete`),params:gxe}),E1=S$.extend({action:ze([`accept`,`decline`,`cancel`]),content:te(e=>e===null?void 0:e,p(v(),S([v(),j(),l(),k(v())])).optional())}),vxe=w({type:M(`ref/resource`),uri:v()}),yxe=w({type:M(`ref/prompt`),name:v()}),bxe=_$.extend({ref:S([yxe,vxe]),argument:w({name:v(),value:v()}),context:w({arguments:p(v(),v()).optional()}).optional()}),D1=y$.extend({method:M(`completion/complete`),params:bxe});function xxe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Sxe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Cxe=S$.extend({completion:a({values:k(v()).max(100),total:E(j().int()),hasMore:E(l())})}),wxe=w({uri:v().startsWith(`file://`),name:v().optional(),_meta:p(v(),D()).optional()}),Txe=y$.extend({method:M(`roots/list`),params:_$.optional()}),O1=S$.extend({roots:k(wxe)}),Exe=x$.extend({method:M(`notifications/roots/list_changed`),params:b$.optional()});S([V$,R$,D1,S1,f1,d1,s1,c1,u1,Nbe,Fbe,b1,v1,J$,X$,Z$,$$]),S([P$,H$,B$,Exe,q$]),S([N$,w1,T1,E1,O1,Y$,Q$,K$]),S([V$,sxe,hxe,Txe,J$,X$,Z$,$$]),S([P$,H$,exe,Lbe,jbe,Zbe,Kbe,q$,_xe]),S([N$,vbe,Cxe,Gbe,Bbe,Dbe,Obe,Abe,y1,Ybe,Y$,Q$,K$]);var k1=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===k$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Dxe(e.elicitations,n)}return new e(t,n,r)}},Dxe=class extends k1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(k$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function A1(e){return e===`completed`||e===`failed`||e===`cancelled`}const Oxe=Symbol(`Let zodToJsonSchema decide on which parser to use`),j1={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`},kxe=e=>typeof e==`string`?{...j1,name:e}:{...j1,...e},Axe=e=>{let t=kxe(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 M1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function N1(e,t,n,r,i){e[t]=n,M1(e,t,r,i)}const P1=(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 F1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?P1(t,e.currentPath):t.join(`/`)}}function jxe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=J1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&N1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&N1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(N1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),N1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Mxe(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?N1(n,`minimum`,r.value,r.message,t):N1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),N1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?N1(n,`maximum`,r.value,r.message,t):N1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),N1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:N1(n,`multipleOf`,r.value,r.message,t);break}return n}function Nxe(){return{type:`boolean`}}function I1(e,t){return J1(e.type._def,t)}const Pxe=(e,t)=>J1(e.innerType._def,t);function L1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>L1(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 Fxe(e,t)}}const Fxe=(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`:N1(n,`minimum`,r.value,r.message,t);break;case`max`:N1(n,`maximum`,r.value,r.message,t);break}return n};function Ixe(e,t){return{...J1(e.innerType._def,t),default:e.defaultValue()}}function Lxe(e,t){return t.effectStrategy===`input`?J1(e.schema._def,t):F1(t)}function Rxe(e){return{type:`string`,enum:Array.from(e.values)}}const zxe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Bxe(e,t){let n=[J1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),J1(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(zxe(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 Vxe(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 R1;const z1={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:()=>(R1===void 0&&(R1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),R1),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 B1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:N1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:N1(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`:H1(n,`email`,r.message,t);break;case`format:idn-email`:H1(n,`idn-email`,r.message,t);break;case`pattern:zod`:U1(n,z1.email,r.message,t);break}break;case`url`:H1(n,`uri`,r.message,t);break;case`uuid`:H1(n,`uuid`,r.message,t);break;case`regex`:U1(n,r.regex,r.message,t);break;case`cuid`:U1(n,z1.cuid,r.message,t);break;case`cuid2`:U1(n,z1.cuid2,r.message,t);break;case`startsWith`:U1(n,RegExp(`^${V1(r.value,t)}`),r.message,t);break;case`endsWith`:U1(n,RegExp(`${V1(r.value,t)}$`),r.message,t);break;case`datetime`:H1(n,`date-time`,r.message,t);break;case`date`:H1(n,`date`,r.message,t);break;case`time`:H1(n,`time`,r.message,t);break;case`duration`:H1(n,`duration`,r.message,t);break;case`length`:N1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),N1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:U1(n,RegExp(V1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&H1(n,`ipv4`,r.message,t),r.version!==`v4`&&H1(n,`ipv6`,r.message,t);break;case`base64url`:U1(n,z1.base64url,r.message,t);break;case`jwt`:U1(n,z1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&U1(n,z1.ipv4Cidr,r.message,t),r.version!==`v4`&&U1(n,z1.ipv6Cidr,r.message,t);break;case`emoji`:U1(n,z1.emoji(),r.message,t);break;case`ulid`:U1(n,z1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:H1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:N1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:U1(n,z1.base64,r.message,t);break}break;case`nanoid`:U1(n,z1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function V1(e,t){return t.patternStrategy===`escape`?Uxe(e):e}const Hxe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Uxe(e){let t=``;for(let n=0;n<e.length;n++)Hxe.has(e[n])||(t+=`\\`),t+=e[n];return t}function H1(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}}})):N1(e,`format`,t,n,r)}function U1(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:W1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):N1(e,`pattern`,W1(t,r),n,r)}function W1(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
1179
+ `).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 rr(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let Ss=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function Cs(e){try{let t=zo(e.scope);if(!t)return;let n=PI(t);if(n.length===0)return;let r=BI(L(e.skillsRoot,e.name),e.name,t,n,`copy`,FI(e.scope));if(r.length===0)return;await fN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){Y.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function ws(e,t){if(t.ok){q(e,200,gte,t.body,{handler:`skill-import`});return}G(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 Ts=pve({contentDir:c,skillsHome:po,...A===void 0?{}:{projectDir:A},resolveSkillDirForRead:_o,parseFrontmatterDoc:ro,attributeOkArtifactWrite:nr,commitOkArtifactWrite:rr,shadowHeadSha:bs,artifactWriterId:Ss,effectiveInstallMode:Do,signalFiles:()=>ae?.(`files`)}),Es=K(pt,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(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 LE(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??bE(d);if(!p){G(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(lX(t,p,`skill-import`))return;let m=await SE(p);r=m.cleanup,s=m.ref;let h=NE(m.dir);if(h.length===0){G(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=>AE(e.dir)?.name===f)??h.find(e=>e.name===Ai[f]);if(!e){G(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){G(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??_s(d)}catch(e){if(e instanceof fE){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await Ts.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||uo(u))&&TI({source:u,skills:[d.body.name]},iI()),await xe?.rebuildIgnorePatterns(),ws(t,d)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),Os=K(Nee,async(e,t,n)=>{let r=()=>{};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(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 LE(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??bE(d);if(!f){G(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(lX(t,f,`skills-import-bulk`))return;if(l=e?.publisher??_s(d),f.kind===`well-known`)a=f,o=await vE(f.origin);else{let e=await SE(f);r=e.cleanup,c=e.ref,s=NE(e.dir)}}catch(e){if(e instanceof fE){G(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){G(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 SE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof fE?`not-found`:`failed`,warnings:[],...e instanceof fE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>ME(e.dir)?.name===t)??s.find(e=>e.name===Ai[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await Ts.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){N(`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){N(`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||uo(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&TI({source:u,skills:e},iI())}await xe?.rebuildIgnorePatterns(),q(t,200,Aee,{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){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),ks=8*1024*1024,As=32*1024*1024;function js(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=L(e,n);return r!==e&&!r.startsWith(e+R)?null:r}function Ms(e){return new Promise((t,n)=>{let r;try{r=Dq(e,{files:200,fields:10,fieldSize:2*1024,fileSize:ks})}catch(e){n(e);return}let i=[],a=0,o=null,s=t=>{o||(o=t,e.unpipe(r),e.destroy(),r.destroy(),n(t))};r.on(`file`,(e,t,n)=>{let r=[],c=!1;t.on(`data`,e=>{if(!o){if(a+=e.length,a>As){s(Error(`Upload too large.`));return}r.push(e)}}),t.on(`limit`,()=>{c=!0}),t.on(`end`,()=>{if(!o){if(c){o=Error(`File "${n.filename}" exceeds the per-file size limit.`);return}i.push({relPath:n.filename||`file`,data:Buffer.concat(r)})}})}),r.on(`error`,n),r.on(`close`,()=>o?n(o):t(i)),e.pipe(r)})}function Ns(e,t){return new Promise((n,r)=>{(0,Ode.fromBuffer)(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(e??Error(`Unreadable archive.`));return}let a=0,o=0,s=e=>{try{i.close()}catch{}r(e instanceof Error?e:Error(String(e)))};i.on(`entry`,e=>{if(++o>200){s(Error(`Archive has too many entries.`));return}let n=js(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){zs(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>ks){s(Error(`Archive entry too large: ${e.fileName}`));return}i.openReadStream(e,(e,t)=>{if(e||!t){s(e??Error(`Could not read archive entry.`));return}let r=[];t.on(`data`,e=>{if(a+=e.length,a>As){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{zs(P(n),{recursive:!0}),Js(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 Fs(e,t){let n=bu(F(Iu(),`ok-skill-upload-`)),r=()=>{try{Us(n,{recursive:!0,force:!0})}catch{}};try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){G(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=fo(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=uD({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},he);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await Ms(e)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){G(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 Ns(c.data,n)}catch(e){G(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=js(n,e.relPath);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}zs(P(r),{recursive:!0}),Js(r,e.data)}let u=NE(n);if(u.length===0){G(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){G(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];ws(t,await Ts.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Is=K(ur,async(e,t,n)=>{try{let e=go(n.scope);if(!lo(n.name,t,`skill-install`))return;if(n.scope===`project`&&!A){G(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=zo(n.scope),i=L(e,n.name),a=n.scope===`project`?c:po,o=(n.scope===`project`?cL(c):lL(po)).find(e=>e.name===n.name),s=o?L(a,o.dir):i;if(!z(s)){G(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 zt(n.scope===`project`?`${I(a,s).split(R).join(`/`)}/SKILL`:ja(n.scope,n.name));let l=NI(s,n.name,{allowReservedName:KF(n.name)});if(!l.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${l.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){G(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=ho.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:G(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:G(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:G(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`:G(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:G(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)}`)}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o.hosts.filter(Wi),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){G(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 ho.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`?G(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`}):G(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(Wi),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await ho.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){G(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}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?A:po;if(!e){G(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 Pr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?G(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):G(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||ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?A:po;if(!e){G(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 Pr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:G(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:G(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:G(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`:G(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)}`)}ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,bt,{name:n.name,hosts:o?[...o.hosts]:[],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){G(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`?A:po,c=await Pr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!c.ok)switch(c.kind){case`invalid-location`:G(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:G(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`:G(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`:G(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(c.kind)}`)}ae?.(`files`),q(t,200,bt,{name:n.name,hosts:[...o.hosts],scripts:l.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f===void 0?OI(po).map(e=>e.editorId).filter(e=>Rt.includes(e)):Rt.filter(e=>f?.some(t=>t===e)):f===void 0?PI(r):Rt.filter(e=>f?.some(t=>t===e)),g=[],_=[];if(h.length===0&&f===void 0&&(g.push(n.scope===`global`?`No editor skill folders are configured to install into.`:"No project-configured editors detected — nothing was projected. Set up an editor for this project (add .mcp.json / .cursor/mcp.json / .codex/config.toml) or pass explicit `targets`."),_.push(`no-targets`)),l.hasScripts&&(g.push("This skill includes executable `scripts/`. After you install it, the AI agent in your editor (Claude, Cursor, Codex) can run them — Open Knowledge itself never runs anything. Review the scripts before sharing."),_.push(`scripts-present`)),l.warnings.length>0&&(g.push(l.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=(f===void 0?n.scope===`global`&&z(F(po,`.agents`)):f.includes(`agents`))?[...h,`agents`]:[...h],a=n.scope===`project`?A:po,c=d===void 0?Do(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await ho.promoteInPlaceSource({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,newSource:u});if(!e.ok){e.kind===`invalid-target`?G(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}):G(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}ae?.(`files`),q(t,200,bt,{name:n.name,hosts:e.hosts,scripts:l.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await ho.fanOutInPlace({scope:n.scope,name:n.name,base:r,...a?{prefBase:a}:{},skillDir:s,inPlaceEntry:o,canonicalRootRel:e,inPlaceTargets:i,setExact:f!==void 0,installMode:c,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){G(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),ae?.(`files`),q(t,200,bt,{name:n.name,hosts:v.hosts,scripts:l.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=jI(uN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&qI(n.name,r,v,FI(n.scope));let y=F(r,...CE),b=z(y)?B(y,`utf-8`):null,x=b===null?null:TE(b);b!==null&&x===null&&Y.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=BI(s,n.name,r,h,C,FI(n.scope));w.length===0?await pN(r,n.name):await fN(r,n.name,{hosts:w,scope:n.scope,scripts:l.hasScripts,installedAt:new Date().toISOString(),projection:C}),ae?.(`files`),q(t,200,bt,{name:n.name,hosts:w,scripts:l.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Ls=K(ete,async(e,t,n)=>{try{if(!lo(n.name,t,`skill-uninstall`))return;let e=zo(n.scope);if(!e){G(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 Bo(e,n.name,n.scope);ae?.(`files`),q(t,200,nee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),Rs=fW({GET:K(Qt,async(e,t)=>{try{let e=PI(A??``),n=(e,t)=>{let n=_ve(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};q(t,200,Xt,{targets:e,configured:!1,folders:[...A?YY(c,tL(c,`project`)).filter(e=>rL(c,`project`,e.root)).map(e=>({...e,scope:`project`,...n(c,e)})):[],...YY(po,tL(po,`global`)).filter(e=>rL(po,`global`,e.root)).map(e=>({...e,scope:`global`,...n(po,e)}))]},{handler:`skill-targets-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:K(vr,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?c:po;if(e.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await vve(r,i.join(`/`)),ae?.(`files`),q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(tL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){G(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}if(e.action===`link`&&e.preview){let n=ZY({base:r,folderRel:e.root,targetRootRel:a}),i=n.kind===`plan`?n.plan:null;q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],preview:{moves:i?[...i.linkedBundlesToMove.map(({name:e})=>e),...i.toMove]:[],drops:i?.toDrop??[],removes:i?.removes??[],replaces:i?.liveDestLinks??[],conflicts:n.kind===`conflicts`?n.conflicts:[],strays:n.kind===`stray-entries`?n.strays:[]}},{handler:`skill-targets-put`});return}let o=e.action===`link`?gve({base:r,folderRel:e.root,targetRootRel:a}):QY({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){G(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await tX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),ae?.(`files`),q(t,200,Mr,{targets:PI(A??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),Bs=K(Sn,async(e,t,n)=>{try{let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!lo(n.name,t,`skill-restore`)||Fo(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(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=ee?.current;if(!r){G(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 dX({shadow:r,contentDir:c,contentRoot:D??`.`,name:n.name,version:n.version,skillDirRel:Oo(n.name)});if(!i.ok){To(t,i,`skill-restore`);return}let a=[],o=NI(L(c,Oo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),nr(e,tr(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await rr(`skill-restore`),ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,xee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),Ws=K(Ft,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!lo(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?po:c,{root:a,dirRel:o,realDir:s}=Qo(n.scope,n.name),l=!o.startsWith(`${Lr}/`);if(s===null||!z(L(i,o,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=F(n.scope===`global`?po:A,...CE),d=vs(u).skills[n.name];if(!d){let e=Eue(n.name,ME(L(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:Wve(L(a,n.name))})??No(i,n.name);e&&(d=e)}if(!d){G(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 pJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let f,p=null,m=!1;try{let e=d.skill??n.name,i=Ai[e],a=await LE(d.source,e).catch(async e=>{if(i===void 0)throw e;return LE(d.source,i)}),o=a?.source??nde(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??bE(o);if(!c){G(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(lX(t,c,`skill-reimport`))return;let l=await SE(c);r=l.cleanup,f=l.ref;let u=NE(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>ME(e.dir)?.name===n.name)??u.find(e=>e.name===Ai[s??n.name])??(u.length===1?u[0]:void 0);if(!m){G(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=jE(m.dir);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=ME(m.dir)}catch(e){if(e instanceof fE){G(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){G(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=JY(p);if(h){G(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=ME(L(a,n.name)),_=new Set(p.files.map(e=>e.relPath)),v=new Set((g?.files??[]).map(e=>e.relPath)),y=(d.files??(d.localHash!==void 0&&g?.contentHash===d.localHash?g.files.map(e=>e.relPath):[])).filter(e=>!_.has(e)).filter(e=>v.has(e));if(p.contentHash===d.contentHash&&y.length===0){await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=ro(p.skillMd).body;if(n.dryRun){let e=ME(L(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&A)try{let e=hc({baseDir:A,timeout:{block:15e3}}),t=I(A,L(a,n.name)).split(R).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!0,source:d.source,localBody:ro(e).body,upstreamBody:b,...r===void 0?{}:{gitTracked:r},warnings:[]},{handler:`skill-reimport`});return}if(n.scope===`project`){let e=y.filter(e=>/\.mdx?$/i.test(e)).map(e=>`${o}/${e.replace(/\.mdx?$/i,``)}`);e.length>0&&await yn(e,`deleted-upstream`)}let x=Wk({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){G(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=qk({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:qY});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=Yk({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(nr(e,tr(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await rr(`skill-reimport`));let C=ys(a,n.name),w=n.scope===`project`?await bs(Ss(e),o):void 0;await pJ(u,e=>EE(e,n.name,{...e.skills[n.name]??d,contentHash:p.contentHash,files:p.files.map(e=>e.relPath),...C===void 0?{}:{localHash:C},...w===void 0?{}:{baselineRef:w},ref:f,importedAt:new Date().toISOString()})),!l&&n.scope===`project`&&await Cs({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),ae?.(`files`),await xe?.rebuildIgnorePatterns(),q(t,200,an,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Gs=K(wte,async(e,t,n)=>{try{if(!A){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=uD(n,he);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!lo(n.name,t,`skill-revert`)||Fo(n.name,t,`skill-revert`))return;if(n.scope===`global`){G(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=F(A,...CE),i=vs(r).skills[n.name];if(!i?.baselineRef){G(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=ee?.current;if(!a){G(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 dX({shadow:a,contentDir:c,contentRoot:D??`.`,name:n.name,version:i.baselineRef,skillDirRel:Oo(n.name)});if(!o.ok){To(t,o,`skill-revert`);return}nr(e,tr(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await rr(`skill-revert`);let s=L(c,Oo(n.name),`..`),l=ys(s,n.name);await pJ(r,e=>EE(e,n.name,{...e.skills[n.name]??i,...l===void 0?{}:{localHash:l}})),s===go(`project`)&&await Cs({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),ae?.(`files`),q(t,200,it,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function qs(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Ys(e){let t=typeof e==`string`?e.split(`,`):Array.isArray(e)?e:void 0;if(!t)return;let n=t.filter(e=>e===`page`||e===`folder`||e===`content`||e===`file`);return n.length>0?n:void 0}function Xs(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Zs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let Qs=dve({contentDir:c,projectDir:A,getAllFilesIndex:h,getFileIndexGeneration:_,getSearchMaxEntries:Qve,semanticSearch:Oe,getSemanticSimilarityFloor:ke,ready:we,getProjectSkillsRoot:()=>go(`project`),parseFrontmatterDoc:ro});Qs.prewarm();let $s=fW({GET:K(Qt,LB(async(e,t)=>{let n=Dc(e),r=n.get(`limit`),i=n.get(`query`)??``,a=qs(n.get(`intent`)),o=Lo(n.get(`ranking`)),s=Ys(n.get(`scope`)??n.get(`scopes`)),c=Xs(n.get(`semantic`)),l=Zs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,yi,await Qs.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:K(ste,LB(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=qs(n.intent),a=Lo(n.ranking),o=Ys(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Xs(n.semantic),l=Zs(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,yi,await Qs.buildSearchResponse({query:r,intent:i,ranking:a,scopes:o,limit:s,semanticParam:c,source:l}),{handler:`search-post`})},{handler:`search-post`,title:`Failed to search workspace.`}),{handler:`search-post`,method:`POST`})},{handler:`search`}),ec=K(Qt,LB(async(e,t)=>{q(t,200,Ot,{...await SI(Nu())},{handler:`skill-install-state`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`skill-install-state`,title:`Failed to read skill install state.`}),{handler:`skill-install-state`,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:`skill-install-state`})});async function tc(e,t){if(r(e,t,{handler:`handoff`}))try{await Ufe(e,t,{contentDir:c,platform:process.platform,isSchemeRegistered:Je.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:Xx(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function nc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await KM(e,t,{contentDir:c,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:Xx(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let rc=K(gee,async(e,t,n)=>{try{if(!A){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!Pme(e,n.kind)){EF(`invalid-path`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`invalid-path`},{handler:wF});return}let r=Rme(A);if(r===null){if(AF(A).kind===`no-remote`){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}EF(`detached-head`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`detached-head`},{handler:wF});return}let i=AF(A);if(i.kind===`no-remote`){EF(`no-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`no-remote`},{handler:wF});return}if(i.kind===`non-github`){EF(`non-github-remote`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`non-github-remote`},{handler:wF});return}if(!Ume(A,r)){EF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,It,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:wF});return}let a=pZ(A,c);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=a===``?e:e===``?a:`${a}/${e}`,s;s=n.kind===`doc`?Fme(i.host,i.owner,i.repo,r,o):TF(i.host,i.owner,i.repo,r,o);let l;try{let e=a===``?0:kee(TF(i.host,i.owner,i.repo,r,a)).targetSegments.length;l=`https://openknowledge.ai/d/${Mee(s,e)}`}catch(e){if(!(e instanceof tee))throw e;EF(`unsupported-share-url`,{kind:n.kind}),q(t,200,It,{ok:!1,error:`unsupported-share-url`},{handler:wF});return}let u=await Ime(A,r,o,n.kind);EF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,It,{ok:!0,shareUrl:l,sharedUrl:s,branch:r,freshness:u},{handler:wF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:wF,cause:e})}},{handler:wF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:wF})}),ic=K(Qt,async(e,t)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:eB});return}let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`branch`),i=n.searchParams.get(`path`),a=n.searchParams.get(`kind`)===`folder`?`folder`:`doc`;if(!aee(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:eB});return}if(!Qz(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:eB});return}q(t,200,Qe,await $z(A,r,i,a),{handler:eB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:eB,cause:e})}},{handler:eB,method:`GET`,skipBodyParse:!0});function ac(e,t,n){let r=e.split(`/`),i=t.split(`/`);if(n>=r.length||n>=i.length)return{verdict:`unknown`};for(let e=0;e<n;e+=1)if(r[e]!==i[e])return{verdict:`unknown`};return{verdict:`renamed`,renamedTo:i.slice(n).join(`/`)}}let oc=K(Er,async(e,t,n)=>{try{if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:UF});return}if(!Qz(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:UF});return}let e=await Zme(A,n.branch,n.path,n.kind,{credentialConfig:mc(ue,{resetAmbient:MF(A)})});q(t,200,Zt,e.verdict!==`renamed`||n.contentRootDepth===void 0?e:ac(n.path,e.renamedTo,n.contentRootDepth),{handler:UF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:UF,cause:e})}},{handler:UF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:UF})}),sc=K(_a,async(e,t,n)=>{if(uD(n,he).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:aB});return}if(!A){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:aB});return}try{q(t,200,lee,await lc(()=>sB(A,n.branch,{fastForward:n.fastForward===!0,credentialConfig:mc(ue,{resetAmbient:MF(A)})})),{handler:aB})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:aB,cause:e})}},{handler:aB,method:`POST`});async function cc(e){let[t,...n]=ue,r=[...n,...e];return await new Promise((e,n)=>{let i=eu(t,r,RM({..._i,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},IF),s=[],c=[];i.stdout.on(`data`,e=>s.push(e)),i.stderr.on(`data`,e=>c.push(e)),i.on(`close`,t=>{if(clearTimeout(o),a){n(Error(`share subprocess timed out after ${IF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=HF(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let uc=K(Qt,async(e,t)=>{if(!Re.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:NF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await cc([`share`,`owners`,`--json`]),n=Wme(zF(e));VF(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,See,n,{handler:NF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:NF,cause:e})}finally{Re.release(`/api/share/publish/owners`)}},{handler:NF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:NF})}),dc=K(Qt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!RF(r)||!LF(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:PF});return}if(!Re.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:PF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await cc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=Gme(zF(e));VF(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,Cn,n,{handler:PF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:PF,cause:e})}finally{Re.release(`/api/share/publish/name-check`)}},{handler:PF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:PF})}),fc=K(Tte,async(e,t,n)=>{if(!A){VF(`publish-create`,`no-project`),q(t,200,at,{ok:!1,error:`no-project`},{handler:FF});return}if(!RF(n.owner)||!LF(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:FF});return}if(!Re.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:FF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,A,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await cc(e),i=Jme(zF(r));VF(`publish-create`,i.ok?`ok`:i.error),i.ok&&le?.()?.refreshRemote().catch(()=>{}),q(t,200,at,i,{handler:FF})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:FF,cause:e})}finally{Re.release(`/api/share/publish`)}},{handler:FF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:FF})}),pc=K(nte,async(e,t,n)=>{try{let e=N(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}q(t,200,oa,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),gc=A?RD(A):null;async function _c(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Fde(e.headers),previewUrl:null,port:gc?yc(gc)?.port??0:0,singleFile:Pe};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,yte,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function vc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Le?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,pe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let bc=`local-op-embeddings-set-key`,xc=`local-op-embeddings-clear-key`,Sc=`/api/local-op/embeddings`;function Cc(){let e=je?.();return{projectDir:A??c,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let wc=K(lr,async(e,t,n)=>{if(!Re.tryAcquire(Sc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:bc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=Cc();await new kj(Ae).setForProject(e,r,n.key),Oe?.reloadCredential(),q(t,200,qo,{keyPresent:!0},{handler:bc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:bc,cause:e})}finally{Re.release(Sc)}},{handler:bc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:bc})}),Tc=K(Qt,async(e,t)=>{if(!Re.tryAcquire(Sc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:xc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=Cc();await new kj(Ae).clearForProject(e,n),Oe?.reloadCredential(),q(t,200,qo,{keyPresent:!1},{handler:xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:xc,cause:e})}finally{Re.release(Sc)}},{handler:xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:xc})}),Oc=`local-op-embeddings-test`,kc=`/api/local-op/embeddings/test`,Ac=K(Qt,async(e,t)=>{if(!Re.tryAcquire(kc)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:Oc,extraHeaders:{"Retry-After":`5`}});return}try{let e=je?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await vj(new kj(Ae),A??c,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await bj({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,Dt,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:Oc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:Oc,cause:e})}finally{Re.release(kc)}},{handler:Oc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Oc})}),jc=K(Qt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Oe){let t=Oe.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=je?.()?.baseUrl??`https://api.openai.com/v1`,o=await vj(new kj(Ae),A??c,a),s=o.apiKey!==null,l=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,f=0;for(let[e]of p())!Lx(e)&&!Rx(e)&&!mo(e)&&(f+=1);q(t,200,Na,{enabled:e,keyPresent:s,keyNotRequired:l,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),Mc=0;function Nc(){Mc+=1,ae?.(`lint-config`)}let Pc=()=>`${Mc} ${t.getActiveBranch()} ${O?.readLocalTargetGeneration?.()??0}`;async function Fc(e,t){let n=Me?.()??Fr;try{let r=await Ti(e,jP(c,n,{docName:t,projectDir:A??c,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=Ne?.()??`warning`;if(O&&a!==`off`&&!Wx(t)){await tn(t,e,`lint-validation`);let r=oF({projectDir:A??c,contentDir:c,baseConfig:n,derivedDocumentIndex:O,linksValidation:a,admittedDocNames:qt,docFilePathFor:e=>uZ(c,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:uZ(c,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function Ic(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=PP({projectDir:A??c,contentDir:c});return eP(t.schemas,n)}let Lc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!SZ(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Me?.()??Fr,i=[],a=OP(c,n??void 0,e=>i.push(e)),o=AP(A??c,kP(r,a),e=>i.push(e));n===null&&i.push(...Ic(o)),q(t,200,Et,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),Rc=K(Ye,async(e,t,n)=>{let r;try{r=WP(L(c),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(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}Nc();try{let e=Me?.()??Fr,n=[],r=OP(c,void 0,e=>n.push(e)),i=AP(A??c,kP(e,r),e=>n.push(e));n.push(...Ic(i)),q(t,200,Et,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(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`}),zc=K(ut,async(e,t,n)=>{let r;try{let e=L(A??c),t=n.parentPath??[];r=n.delete?Vpe(e,n.file):n.field!==void 0&&n.removeField?zpe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?Bpe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Lpe(e,n.file,n.field,n.constraint,t):Rpe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(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`)&&ae?.(`files`),Nc();try{let e=Me?.()??Fr,n=[],r=OP(c,void 0,e=>n.push(e)),i=AP(A??c,kP(e,r),e=>n.push(e));n.push(...Ic(i)),q(t,200,Et,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(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`}),Bc=K(Qt,async(e,t)=>{try{let e=L(A??c),{schemas:n,truncated:r}=hpe(e),i=new Set(n),a=!1;if(xe!==void 0){let t=eZ({contentDir:c,contentFilter:xe,dirFilter:null,maxEntries:2e4}),n=await t.next();for(;!n.done;){let r=n.value,a=r.kind===`asset`?r.path:void 0;if(a!==void 0&&li(a)){let t=I(e,L(c,a));!t.startsWith(`..`)&&!ou(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,hte,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),Vc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=o.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Hc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!SZ(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=uZ(c,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Me?.()??Fr,a=[],o=await NP({projectDir:A??c,contentDir:c,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:Vc});q(t,200,vt,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof DM){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Uc=new XN,Wc=cX();function Gc(e,t,n){let r=`${n} ${Pc()} ${t??``}`;return Wc.run(r,()=>ome(e,{targetPath:t})).promise}function Kc(e,t){G(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let qc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!tZ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Me?.()??Fr;q(t,200,Dee,await FP({projectDir:A??c,contentDir:c,baseConfig:i,targetPath:r,liveSourceFor:Vc,cache:Uc,auditGeneration:Pc}),{handler:`lint-audit`})}catch(e){if(e instanceof MP){Kc(t,`lint-audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),Jc=K(Qt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!tZ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!tZ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=uZ(c,o)??`${o}.md`}let s=Me?.()??Fr,l=await Gc(oF({projectDir:A??c,contentDir:c,baseConfig:s,liveSourceFor:Vc,derivedDocumentIndex:O??null,linksValidation:Ne?.(),admittedDocNames:qt,docFilePathFor:e=>uZ(c,e),cache:Uc,auditGeneration:Pc}),i,XN.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){q(t,200,ma,ame(l),{handler:`audit`});return}q(t,200,see,l,{handler:`audit`})}catch(e){if(e instanceof MP){Kc(t,`audit`);return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Yc=K(pee,async(t,n,r)=>{try{let t=rZ(r.docName,n,`lint-fix`);if(t===null)return;let i=Ct(t),a=uD(r,he);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,l=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Lx(i)||Rx(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=uZ(c,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}IM(L(c,f),c);let p=Me?.()??Fr,{stored:m}=Yn(a.summary),h=await s.getSession(i,o,{displayName:l,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Ppe({projectDir:A??c,contentDir:c,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Zo(d),n=Yr[t]??rs(u??o);se?.setPresence(o,{displayName:l,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{QC(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,XC(h))},h.origin),a.kind!==`anonymous`&&EA(i,o,l,u,void 0,a.kind===`agent`?Jn({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{se?.touchMode(o,`idle`)}let t=await zt(i);if(t?.kind===`failure`){Bt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Vt(n,`lint-fix`);return}Mt(i,`lint-fix`);try{b=await Ti(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,Sa,{file:f,fixedCount:Math.max(0,v.length-b.length),diagnostics:b,errorCount:S,warningCount:C,...x?{warning:x}:{}},{handler:`lint-fix`})}catch(e){if(e instanceof DM){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof iS){aS(n,e,`lint-fix`);return}if(e instanceof lS){fS(n,e,`lint-fix`);return}if(e instanceof tw){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Xc=`link-preview`,Zc=new wG({cacheDir:Pe?null:L(A??c,`.ok`,`local`,`link-previews`)}),Qc=null,$c=()=>(Qc??=Zc.init(),Qc),el=Fe??hG;async function tl(e){let t=await el(e);return t.ok?{ok:!0,metadata:await bG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:el})}:{ok:!1,reason:t.reason}}let nl=()=>{try{return Ie?.()===!0}catch{return!1}},rl=K(Gn,async(e,t,n)=>{try{if(!nl()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,Pt,{ok:!1,reason:`disabled`},{handler:Xc});return}await $c();let e=!1,r=await Zc.load(n.url,()=>(e=!0,tl(n.url)));Zc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,Pt,i,{handler:Xc})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Xc,cause:e})}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>{let n=DG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Xc}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Xc}),!1)}}),il=Gde({service:et,getPrincipal:he,onChanged:()=>ae?.(`comments`)}),al=fW({GET:il.list,POST:il.create},{handler:`comments`}),ol=fW({GET:il.read,POST:il.mutate,DELETE:il.remove},{handler:`comment`}),{handleSkillsSearch:sl,handleSkillsPopular:cl,handleSkillsPublisher:ll,handleSkillsDetail:ul,handleSkillsPreview:dl,handleSkillsDiscover:fl,handleSkillsResolveRef:pl}=kve({log:Y,skillsHome:po,projectDir:A,contentDir:c,resolveSkillDirForRead:_o}),ml={"/api/config":_c,"/api/config/diagnostics":vc,"/api/generated-index/settings":fW({GET:K(Qt,async(e,t)=>{if(!u){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-get`});return}q(t,200,bZ,u(),{handler:`generated-index-settings-get`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-get`,method:`GET`,skipBodyParse:!0}),POST:K(fye,async(e,t,n)=>{if(!d){G(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`generated-index-settings-set`});return}q(t,200,bZ,await d(n.enabled),{handler:`generated-index-settings-set`,extraHeaders:{"Cache-Control":`no-store`}})},{handler:`generated-index-settings-set`,method:`POST`})},{handler:`generated-index-settings`}),"/api/comments":al,"/api/comment":ol,"/api/asset":Zr,"/api/asset-text":$r,"/api/comment-counts":hr,"/api/link-preview":rl,"/api/folder-config":Ka,"/api/saved-themes":qa,"/api/saved-theme":Qa,"/api/template":so,"/api/template/import":co,"/api/templates":to,"/api/skill":cs,"/api/skill-file":hs,"/api/skill-file/rename":gs,"/api/skills":Ko,"/api/skills/installed":mr,"/api/skills/search":sl,"/api/skills/popular":cl,"/api/skills/publisher":ll,"/api/skills/detail":ul,"/api/skills/preview":dl,"/api/skills/discover":fl,"/api/skills/resolve-ref":pl,"/api/skill/import":Es,"/api/skills/import-bulk":Os,"/api/skill/edit-external":is,"/api/skill/duplicate":ss,"/api/skill/move-scope":os,"/api/skill-upload":Fs,"/api/skill/install":Is,"/api/skill/uninstall":Ls,"/api/skill/restore":Bs,"/api/skill/reimport":Ws,"/api/skill/revert":Gs,"/api/skill/track-in-git":Wo,"/api/skill-targets":Rs,"/api/search":$s,"/api/semantic-status":jc,"/api/lint/config":Lc,"/api/lint/markdownlint-config":Rc,"/api/lint/frontmatter-schema":zc,"/api/lint/frontmatter-schemas":Bc,"/api/lint":Hc,"/api/lint/audit":qc,"/api/lint/fix":Yc,"/api/audit":Jc,"/api/create-page":ti,"/api/create-folder":ri,"/api/duplicate-path":ii,"/api/rename-path":ai,"/api/delete-path":oi,"/api/trash/cleanup":si,"/api/upload":ci,"/api/agent-write":ar,"/api/agent-write-md":or,"/api/agent-write-batch":cr,"/api/frontmatter-patch":pr,"/api/agent-patch":_r,"/api/agent-undo":yr,"/api/agent-activity":br,"/api/agent-burst-diff":Sr,"/api/save-version":Ir,"/api/history":Rr,"/api/rollback":Br,"/api/__embed-detect":Gr,"/api/server-info":Vr,"/api/acp/catalog":Ur,"/api/share/construct-url":rc,"/api/share/target-status":oc,"/api/git/branch-info":ic,"/api/git/checkout":sc,"/api/share/publish/owners":uc,"/api/share/publish/name-check":dc,"/api/share/publish":fc,"/api/principal":Wr,"/api/rescue":ei,"/api/workspace":Kr,"/api/sync/status":xa,"/api/sync/trigger":Ca,"/api/sync/conflicts":Ta,"/api/sync/conflict-content":Oa,"/api/sync/resolve-conflict":Da,"/api/local-op/clone":wi,"/api/local-op/ok-init":Pi,"/api/local-op/auth/login":Xi,"/api/local-op/auth/status":ra,"/api/local-op/auth/pat":aa,"/api/local-op/auth/gh-login":$i,"/api/local-op/auth/cancel":ta,"/api/local-op/auth/repos":ca,"/api/local-op/auth/signout":pa,"/api/local-op/auth/set-identity":ba,"/api/local-op/embeddings/set-key":wc,"/api/local-op/embeddings/clear-key":Tc,"/api/local-op/embeddings/test":Ac,"/api/installed-agents":za,"/api/spawn-cursor":nc,"/api/handoff":tc,"/api/install-skill":Ra,"/api/skill/install-state":ec,"/api/seed/plan":ka,"/api/seed/apply":Aa,"/api/seed/install-pack-skill":Pa,"/api/seed/packs":La,"/api/client-logs":pc};E&&(ml[`/api/test-reset`]=kr,ml[`/api/test-flush-git`]=Or,ml[`/api/test-rescan-backlinks`]=Ar,ml[`/api/test-rescan-files`]=jr);let hl=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/generated-index/settings./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/saved-theme./api/template./api/template/import./api/skill./api/skill-file./api/skill-file/rename./api/skill/import./api/skills/import-bulk./api/skill/duplicate./api/skill/move-scope./api/skill/edit-external./api/skill-upload./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/reimport./api/skill/revert./api/skill/track-in-git./api/skills/preview./api/skills/discover./api/skills/resolve-ref./api/skill-targets./api/seed/apply./api/seed/install-pack-skill./api/client-logs`.split(`.`)),gl=[`/api/local-op/`],_l=IB({log:Y,policy:n,ephemeral:Pe,table:{resolve(e){let t=ml[e];if(t)return{template:e,dispatch:(e,n)=>t(e,n)};if(e.startsWith(`/api/history/`)){let t=e.slice(13);return{template:`/api/history/:sha`,dispatch:t?async(e,n)=>{await zr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>hl.has(e)||gl.some(t=>e.startsWith(t))}}),vl=cW({hocuspocus:o,derivedDocumentIndex:O,getFileIndex:p,isSafeDocName:SZ,readPageTitleForDocName:tt,readPageTitleForLinkedDocName:st,readFrontmatterMetadataForLinkedDocName:gt,collectAdmittedDocNames:qt,resolveAlias:Ct,respondToDerivedIndexQueryFailure:sn}),yl=[vl,pW({hocuspocus:o,agentPresenceBroadcaster:se,isAllowedWorkspaceHostHeader:i,log:Y}),Ve],bl=yl.flatMap(e=>[...e.paths]);FU(bl,ml);let xl=yl.map(e=>IB({log:Y,policy:n,ephemeral:Pe,table:e.table})),Sl={paths:bl,dispatch:async(e,t)=>{for(let n of xl)if(await n(e,t))return!0;return!1}},Cl=new Set([`/api/search`,`/api/delete-path`,`/api/create-folder`,`/api/save-version`,`/api/skill/import`,`/api/skill/install`,`/api/upload`,`/api/orphans`,`/api/hubs`,`/api/backlinks`,`/api/forward-links`,`/api/dead-links`,`/api/suggest-links`]);for(let e of Cl)if(ml[e]===void 0&&vl.table.resolve(e)?.dispatch===void 0)throw Error(`MCP_LOCAL_API_PATHS has no handler for ${e}`);return{priority:100,async onRequest({request:e,response:t}){await _l(e,t)},nativeApi:Sl,localApi:dW({resolve:e=>{if(!Cl.has(e))return;let t=ml[e];return t===void 0?vl.table.resolve(e)?.dispatch:t}})}}function wZ(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&&!EB(f,o)){G(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!OB(e.headers.host,o)){G(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:xB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=RY(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=Ae.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 TZ(e){let t=e?.code;return typeof t==`string`?t:void 0}function mye(e){let t;try{t=wu(e.contentDir,{withFileTypes:!0})}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Ex(n.name,ne)&&e.basenameIndex.add(n.name)}async function EZ(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=TZ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=F(i,o.name),s=MM(I(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await zu(a)}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await Hu(a)}catch(t){let n=TZ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!NM(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await Uu(i)}catch(t){let n=TZ(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()&&Ex(a,fe)&&!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()&&Ex(a,fe)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const DZ=w({principalId:v().optional(),tabSessionId:v().optional(),expectedServerInstanceId:v().optional(),expectedBranch:v().optional(),expectedDocLineageEpoch:v().optional(),clientProtocolVersion:j().optional(),clientRuntimeVersion:v().optional(),clientKind:v().optional()}).loose(),OZ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function kZ(e){return OZ.includes(e)}function AZ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function hye(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!kZ(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 jZ=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=AZ(e,this.payload)}};function MZ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=DZ.safeParse(t);return n.success?n.data:void 0}var NZ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};function PZ(e,t,n=``){e=Qte(`.`,e);let r=Xte(e),i=0,a,o;for(;i<r.length;i++)a=Xu(e,r[i]),o=Zte(a),o.isDirectory()?PZ(a,t,Xu(n,r[i])):t(Xu(n,r[i]),a,o)}function gye(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=une.parse(i.substring(1))))}return e._parsedUrl={pathname:r,search:i,query:a,hash:o,raw:t}}const _ye=()=>{};function vye(e,t){for(let n=0;n<t.length;n++)if(t[n].test(e))return!0}function FZ(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 yye(e,t,n){let r=0,i,a=FZ(t,n);for(;r<a.length;r++)if(i=e[a[r]])return i}function bye(e,t,n,r){let i=0,a=FZ(n,r),o,s,c,l;for(;i<a.length;i++)if(o=su(F(e,c=a[i])),o.startsWith(e)&&fu.existsSync(o)){if(s=fu.statSync(o),s.isDirectory())continue;return l=IZ(c,s,t),l[`Cache-Control`]=t?`no-cache`:`no-store`,{abs:o,stats:s,headers:l}}}function xye(e,t){return t.statusCode=404,t.end()}function Sye(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 Cye={".br":`br`,".gz":`gzip`};function IZ(e,t,n){let r=Cye[e.slice(-3)],i=Q_e(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 LZ(e,t={}){e=L(e||`.`);let n=t.onNoMatch||xye,r=t.setHeaders||_ye,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||PZ(e,(e,n,r)=>{if(!/\.well-known[\\+\/]/.test(e)&&!t.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(e))return;let i=IZ(e,r,l);f&&(i[`Cache-Control`]=f),s[`/`+e.normalize().replace(/\\+/g,`/`)]={abs:n,stats:r,headers:i}});let p=t.dev?bye.bind(0,e+R,l):yye.bind(0,s);return function(e,t,s){let f=[``],m=gye(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&&!vye(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),Sye(e,t,g.abs,g.stats,g.headers)}}const RZ=N(`conflict-storage`);var zZ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=F(RD(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!z(this.storePath)){this.conflicts=[];return}try{let e=B(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){RZ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){RZ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=P(this.storePath);z(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 RZ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n){let r=this.conflicts.find(t=>t.file===e);if(!r)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(r.variant===`working-tree`){await this.resolveWorkingTreeConflict(r,t,n);return}let{createGitInstance:i}=await import(`./git-handle-DaYxKcxM.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=L(this.projectDir),r=L(t,e);if(!NM(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);fL(r,t),Js(r,n,`utf-8`),await a.git.raw([`add`,`--`,e]);break}case`delete`:await a.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await a.git.raw([`commit`,`--no-edit`]),RZ.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:n});r=e.length>0}catch(e){RZ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),RZ.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=L(this.projectDir),i=L(r,e.file);if(!NM(i,r))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(fL(i,r),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-DaYxKcxM.mjs`),n=await t(this.projectDir,{credentialConfig:[]}).git.raw([`cat-file`,`blob`,e.theirsSha]);fL(i,r),Js(i,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);Js(i,n,`utf-8`);break;case`delete`:z(i)&&Ps(i);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function wye(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 Tye(e,t){let n=RD(e);try{yu(n,{recursive:!0}),ju(F(n,Ci),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=nc(e);yu(P(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 BZ=new Map;let VZ=!1;function Eye(e,t){try{let n=wye(e,t);for(let e of BZ.keys())Tye(e,n)}catch{}}function Dye(e){BZ.set(e,(BZ.get(e)??0)+1),VZ||(VZ=!0,process.on(`uncaughtExceptionMonitor`,Eye));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=BZ.get(e)??0;n<=1?BZ.delete(e):BZ.set(e,n-1)}}}function HZ(e){let t=e.scheduler??$r,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function UZ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function WZ(e){if(!z(e))return{};let t;try{t=(0,oD.parse)(B(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(!UZ(t))return{};let n=t.telemetry;if(!UZ(n))return{};let r=n.localSink;return UZ(r)?r:{}}function GZ(e){return typeof e==`boolean`?e:void 0}function Oye(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function KZ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function qZ(e){if(UZ(e))return Oye(e.maxBytes)}function kye(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=WZ(Rs(`project`,e.projectDir)),n=WZ(Rs(`project-local`,e.projectDir));if((GZ(n.enabled)??GZ(t.enabled)??!0)===!1)return null;let r=qZ(n.spans)??qZ(t.spans)??52428800,a=qZ(n.logs)??qZ(t.logs)??26214400,o=KZ(n.attributeDenylist)??KZ(t.attributeDenylist)??i;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:o},logs:{projectDir:e.projectDir,maxBytes:a}}}var JZ;(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})(JZ||={});var Aye;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Aye||={});const YZ=JZ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),XZ=e=>{switch(typeof e){case`undefined`:return YZ.undefined;case`string`:return YZ.string;case`number`:return Number.isNaN(e)?YZ.nan:YZ.number;case`boolean`:return YZ.boolean;case`function`:return YZ.function;case`bigint`:return YZ.bigint;case`symbol`:return YZ.symbol;case`object`:return Array.isArray(e)?YZ.array:e===null?YZ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?YZ.promise:typeof Map<`u`&&e instanceof Map?YZ.map:typeof Set<`u`&&e instanceof Set?YZ.set:typeof Date<`u`&&e instanceof Date?YZ.date:YZ.object;default:return YZ.unknown}},X=JZ.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 ZZ=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,JZ.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()}};ZZ.create=e=>new ZZ(e);const QZ=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===YZ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,JZ.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${JZ.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${JZ.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${JZ.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.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}"`:JZ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.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 X.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 X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,JZ.assertNever(e)}return{message:n}};let jye=QZ;function $Z(){return jye}const eQ=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 tQ(e,t){let n=$Z(),r=eQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===QZ?void 0:QZ].filter(e=>!!e)});e.common.issues.push(r)}var nQ=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 rQ;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 rQ;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 rQ=Object.freeze({status:`aborted`}),iQ=e=>({status:`dirty`,value:e}),aQ=e=>({status:`valid`,value:e}),oQ=e=>e.status===`aborted`,sQ=e=>e.status===`dirty`,cQ=e=>e.status===`valid`,lQ=e=>typeof Promise<`u`&&e instanceof Promise;var uQ;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(uQ||={});var dQ=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 fQ=(e,t)=>{if(cQ(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 ZZ(e.common.issues);return this._error=t,this._error}}};function pQ(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 mQ=class{get description(){return this._def.description}_getType(e){return XZ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:XZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nQ,ctx:{common:e.parent.common,data:e.data,parsedType:XZ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lQ(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:XZ(e)};return fQ(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:XZ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return cQ(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=>cQ(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:XZ(e)},r=this._parse({data:e,path:n.path,parent:n});return fQ(n,await(lQ(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:X.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 KQ({schema:this,typeName:Z.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 qQ.create(this,this._def)}nullable(){return JQ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return AQ.create(this)}promise(){return GQ.create(this,this._def)}or(e){return NQ.create([this,e],this._def)}and(e){return IQ.create(this,e,this._def)}transform(e){return new KQ({...pQ(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new YQ({...pQ(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new QQ({typeName:Z.ZodBranded,type:this,...pQ(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new XQ({...pQ(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return $Q.create(this,e)}readonly(){return e$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Mye=/^c[^\s-]{8,}$/i,Nye=/^[0-9a-z]+$/,Pye=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fye=/^[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,Iye=/^[a-z0-9_-]{21}$/i,Lye=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Rye=/^[-+]?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)?)??$/,zye=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let hQ;const Bye=/^(?:(?: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])$/,Vye=/^(?:(?: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])$/,Hye=/^(([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]))$/,Uye=/^(([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])$/,Wye=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Gye=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gQ=`((\\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])))`,Kye=RegExp(`^${gQ}$`);function _Q(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 qye(e){return RegExp(`^${_Q(e)}$`)}function Jye(e){let t=`${gQ}T${_Q(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Yye(e,t){return!!((t===`v4`||!t)&&Bye.test(e)||(t===`v6`||!t)&&Hye.test(e))}function Xye(e,t){if(!Lye.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 Zye(e,t){return!!((t===`v4`||!t)&&Vye.test(e)||(t===`v6`||!t)&&Uye.test(e))}var vQ=class e extends mQ{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==YZ.string){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.string,received:t.parsedType}),rQ}let t=new nQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.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),tQ(n,{code:X.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?tQ(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&tQ(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)zye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)hQ||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),hQ.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Fye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Iye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Mye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Nye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Pye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),tQ(n,{validation:`url`,code:X.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),tQ(n,{validation:`regex`,code:X.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),tQ(n,{code:X.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),tQ(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Jye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Kye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?qye(r).test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?Rye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Yye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Xye(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?Zye(e.data,r.version)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Wye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Gye.test(e.data)||(n=this._getOrReturnCtx(e,n),tQ(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):JZ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...uQ.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...uQ.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...uQ.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...uQ.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...uQ.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...uQ.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...uQ.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...uQ.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...uQ.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...uQ.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...uQ.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...uQ.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...uQ.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...uQ.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,...uQ.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,...uQ.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...uQ.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...uQ.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...uQ.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...uQ.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...uQ.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...uQ.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...uQ.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...uQ.errToObj(t)})}nonempty(e){return this.min(1,uQ.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}};vQ.create=e=>new vQ({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...pQ(e)});function Qye(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 yQ=class e extends mQ{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)!==YZ.number){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.number,received:t.parsedType}),rQ}let t,n=new nQ;for(let r of this._def.checks)r.kind===`int`?JZ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.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),tQ(t,{code:X.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),tQ(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Qye(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),tQ(t,{code:X.not_finite,message:r.message}),n.dirty()):JZ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,uQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,uQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,uQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,uQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:uQ.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:uQ.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:uQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:uQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:uQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:uQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:uQ.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:uQ.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:uQ.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:uQ.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`&&JZ.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)}};yQ.create=e=>new yQ({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...pQ(e)});var bQ=class e extends mQ{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)!==YZ.bigint)return this._getInvalidInput(e);let t,n=new nQ;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),tQ(t,{code:X.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),tQ(t,{code:X.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),tQ(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):JZ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.bigint,received:t.parsedType}),rQ}gte(e,t){return this.setLimit(`min`,e,!0,uQ.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,uQ.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,uQ.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,uQ.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:uQ.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:uQ.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:uQ.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:uQ.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:uQ.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:uQ.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}};bQ.create=e=>new bQ({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...pQ(e)});var xQ=class extends mQ{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==YZ.boolean){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.boolean,received:t.parsedType}),rQ}return aQ(e.data)}};xQ.create=e=>new xQ({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...pQ(e)});var SQ=class e extends mQ{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==YZ.date){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.date,received:t.parsedType}),rQ}if(Number.isNaN(e.data.getTime()))return tQ(this._getOrReturnCtx(e),{code:X.invalid_date}),rQ;let t=new nQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),tQ(n,{code:X.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),tQ(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):JZ.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:uQ.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:uQ.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)}};SQ.create=e=>new SQ({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...pQ(e)});var CQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.symbol){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.symbol,received:t.parsedType}),rQ}return aQ(e.data)}};CQ.create=e=>new CQ({typeName:Z.ZodSymbol,...pQ(e)});var wQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.undefined){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.undefined,received:t.parsedType}),rQ}return aQ(e.data)}};wQ.create=e=>new wQ({typeName:Z.ZodUndefined,...pQ(e)});var TQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.null){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.null,received:t.parsedType}),rQ}return aQ(e.data)}};TQ.create=e=>new TQ({typeName:Z.ZodNull,...pQ(e)});var EQ=class extends mQ{constructor(){super(...arguments),this._any=!0}_parse(e){return aQ(e.data)}};EQ.create=e=>new EQ({typeName:Z.ZodAny,...pQ(e)});var DQ=class extends mQ{constructor(){super(...arguments),this._unknown=!0}_parse(e){return aQ(e.data)}};DQ.create=e=>new DQ({typeName:Z.ZodUnknown,...pQ(e)});var OQ=class extends mQ{_parse(e){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.never,received:t.parsedType}),rQ}};OQ.create=e=>new OQ({typeName:Z.ZodNever,...pQ(e)});var kQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.undefined){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.void,received:t.parsedType}),rQ}return aQ(e.data)}};kQ.create=e=>new kQ({typeName:Z.ZodVoid,...pQ(e)});var AQ=class e extends mQ{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==YZ.array)return tQ(t,{code:X.invalid_type,expected:YZ.array,received:t.parsedType}),rQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(tQ(t,{code:e?X.too_big:X.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&&(tQ(t,{code:X.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&&(tQ(t,{code:X.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 dQ(t,e,t.path,n)))).then(e=>nQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new dQ(t,e,t.path,n)));return nQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:uQ.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:uQ.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:uQ.toString(n)}})}nonempty(e){return this.min(1,e)}};AQ.create=(e,t)=>new AQ({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...pQ(t)});function jQ(e){if(e instanceof MQ){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=qQ.create(jQ(r))}return new MQ({...e._def,shape:()=>t})}else if(e instanceof AQ)return new AQ({...e._def,type:jQ(e.element)});else if(e instanceof qQ)return qQ.create(jQ(e.unwrap()));else if(e instanceof JQ)return JQ.create(jQ(e.unwrap()));else if(e instanceof LQ)return LQ.create(e.items.map(e=>jQ(e)));else return e}var MQ=class e extends mQ{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=JZ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==YZ.object){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.object,received:t.parsedType}),rQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof OQ&&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 dQ(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof OQ){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&&(tQ(n,{code:X.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 dQ(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=>nQ.mergeObjectSync(t,e)):nQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return uQ.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:uQ.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:Z.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 JZ.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 JZ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return jQ(this)}partial(t){let n={};for(let e of JZ.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 JZ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof qQ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return HQ(JZ.objectKeys(this.shape))}};MQ.create=(e,t)=>new MQ({shape:()=>e,unknownKeys:`strip`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)}),MQ.strictCreate=(e,t)=>new MQ({shape:()=>e,unknownKeys:`strict`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)}),MQ.lazycreate=(e,t)=>new MQ({shape:e,unknownKeys:`strip`,catchall:OQ.create(),typeName:Z.ZodObject,...pQ(t)});var NQ=class extends mQ{_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 ZZ(e.ctx.common.issues));return tQ(t,{code:X.invalid_union,unionErrors:n}),rQ}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 ZZ(e));return tQ(t,{code:X.invalid_union,unionErrors:i}),rQ}}get options(){return this._def.options}};NQ.create=(e,t)=>new NQ({options:e,typeName:Z.ZodUnion,...pQ(t)});const PQ=e=>e instanceof BQ?PQ(e.schema):e instanceof KQ?PQ(e.innerType()):e instanceof VQ?[e.value]:e instanceof UQ?e.options:e instanceof WQ?JZ.objectValues(e.enum):e instanceof YQ?PQ(e._def.innerType):e instanceof wQ?[void 0]:e instanceof TQ?[null]:e instanceof qQ?[void 0,...PQ(e.unwrap())]:e instanceof JQ?[null,...PQ(e.unwrap())]:e instanceof QQ||e instanceof e$?PQ(e.unwrap()):e instanceof XQ?PQ(e._def.innerType):[];var $ye=class e extends mQ{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==YZ.object)return tQ(t,{code:X.invalid_type,expected:YZ.object,received:t.parsedType}),rQ;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}):(tQ(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),rQ)}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=PQ(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:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...pQ(r)})}};function FQ(e,t){let n=XZ(e),r=XZ(t);if(e===t)return{valid:!0,data:e};if(n===YZ.object&&r===YZ.object){let n=JZ.objectKeys(t),r=JZ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=FQ(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===YZ.array&&r===YZ.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=FQ(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===YZ.date&&r===YZ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var IQ=class extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(oQ(e)||oQ(r))return rQ;let i=FQ(e.value,r.value);return i.valid?((sQ(e)||sQ(r))&&t.dirty(),{status:t.value,value:i.data}):(tQ(n,{code:X.invalid_intersection_types}),rQ)};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}))}};IQ.create=(e,t,n)=>new IQ({left:e,right:t,typeName:Z.ZodIntersection,...pQ(n)});var LQ=class e extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==YZ.array)return tQ(n,{code:X.invalid_type,expected:YZ.array,received:n.parsedType}),rQ;if(n.data.length<this._def.items.length)return tQ(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),rQ;!this._def.rest&&n.data.length>this._def.items.length&&(tQ(n,{code:X.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 dQ(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>nQ.mergeArray(t,e)):nQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};LQ.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new LQ({items:e,typeName:Z.ZodTuple,rest:null,...pQ(t)})};var ebe=class e extends mQ{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!==YZ.object)return tQ(n,{code:X.invalid_type,expected:YZ.object,received:n.parsedType}),rQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new dQ(n,e,n.path,e)),value:a._parse(new dQ(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?nQ.mergeObjectAsync(t,r):nQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof mQ?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...pQ(r)}):new e({keyType:vQ.create(),valueType:t,typeName:Z.ZodRecord,...pQ(n)})}},RQ=class extends mQ{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!==YZ.map)return tQ(n,{code:X.invalid_type,expected:YZ.map,received:n.parsedType}),rQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new dQ(n,e,n.path,[a,`key`])),value:i._parse(new dQ(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 rQ;(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 rQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};RQ.create=(e,t,n)=>new RQ({valueType:t,keyType:e,typeName:Z.ZodMap,...pQ(n)});var zQ=class e extends mQ{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==YZ.set)return tQ(n,{code:X.invalid_type,expected:YZ.set,received:n.parsedType}),rQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(tQ(n,{code:X.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&&(tQ(n,{code:X.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 rQ;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 dQ(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:uQ.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:uQ.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};zQ.create=(e,t)=>new zQ({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...pQ(t)});var tbe=class e extends mQ{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==YZ.function)return tQ(t,{code:X.invalid_type,expected:YZ.function,received:t.parsedType}),rQ;function n(e,n){return eQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$Z(),QZ].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return eQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,$Z(),QZ].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof GQ){let e=this;return aQ(async function(...t){let o=new ZZ([]),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 aQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new ZZ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new ZZ([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:LQ.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||LQ.create([]).rest(DQ.create()),returns:n||DQ.create(),typeName:Z.ZodFunction,...pQ(r)})}},BQ=class extends mQ{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})}};BQ.create=(e,t)=>new BQ({getter:e,typeName:Z.ZodLazy,...pQ(t)});var VQ=class extends mQ{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return tQ(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),rQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};VQ.create=(e,t)=>new VQ({value:e,typeName:Z.ZodLiteral,...pQ(t)});function HQ(e,t){return new UQ({values:e,typeName:Z.ZodEnum,...pQ(t)})}var UQ=class e extends mQ{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return tQ(t,{expected:JZ.joinValues(n),received:t.parsedType,code:X.invalid_type}),rQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return tQ(t,{received:t.data,code:X.invalid_enum_value,options:n}),rQ}return aQ(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})}};UQ.create=HQ;var WQ=class extends mQ{_parse(e){let t=JZ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==YZ.string&&n.parsedType!==YZ.number){let e=JZ.objectValues(t);return tQ(n,{expected:JZ.joinValues(e),received:n.parsedType,code:X.invalid_type}),rQ}if(this._cache||=new Set(JZ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=JZ.objectValues(t);return tQ(n,{received:n.data,code:X.invalid_enum_value,options:e}),rQ}return aQ(e.data)}get enum(){return this._def.values}};WQ.create=(e,t)=>new WQ({values:e,typeName:Z.ZodNativeEnum,...pQ(t)});var GQ=class extends mQ{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==YZ.promise&&t.common.async===!1?(tQ(t,{code:X.invalid_type,expected:YZ.promise,received:t.parsedType}),rQ):aQ((t.parsedType===YZ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};GQ.create=(e,t)=>new GQ({type:e,typeName:Z.ZodPromise,...pQ(t)});var KQ=class extends mQ{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.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=>{tQ(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 rQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?rQ:r.status===`dirty`||t.value===`dirty`?iQ(r.value):r});{if(t.value===`aborted`)return rQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?rQ:r.status===`dirty`||t.value===`dirty`?iQ(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`?rQ:(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`?rQ:(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(!cQ(e))return rQ;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=>cQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):rQ);JZ.assertNever(r)}};KQ.create=(e,t,n)=>new KQ({schema:e,typeName:Z.ZodEffects,effect:t,...pQ(n)}),KQ.createWithPreprocess=(e,t,n)=>new KQ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...pQ(n)});var qQ=class extends mQ{_parse(e){return this._getType(e)===YZ.undefined?aQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qQ.create=(e,t)=>new qQ({innerType:e,typeName:Z.ZodOptional,...pQ(t)});var JQ=class extends mQ{_parse(e){return this._getType(e)===YZ.null?aQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};JQ.create=(e,t)=>new JQ({innerType:e,typeName:Z.ZodNullable,...pQ(t)});var YQ=class extends mQ{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===YZ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};YQ.create=(e,t)=>new YQ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...pQ(t)});var XQ=class extends mQ{_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 lQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new ZZ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new ZZ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};XQ.create=(e,t)=>new XQ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...pQ(t)});var ZQ=class extends mQ{_parse(e){if(this._getType(e)!==YZ.nan){let t=this._getOrReturnCtx(e);return tQ(t,{code:X.invalid_type,expected:YZ.nan,received:t.parsedType}),rQ}return{status:`valid`,value:e.data}}};ZQ.create=e=>new ZQ({typeName:Z.ZodNaN,...pQ(e)});var QQ=class extends mQ{_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}},$Q=class e extends mQ{_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`?rQ:e.status===`dirty`?(t.dirty(),iQ(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`?rQ: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:Z.ZodPipeline})}},e$=class extends mQ{_parse(e){let t=this._def.innerType._parse(e),n=e=>(cQ(e)&&(e.value=Object.freeze(e.value)),e);return lQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};e$.create=(e,t)=>new e$({innerType:e,typeName:Z.ZodReadonly,...pQ(t)}),MQ.lazycreate;var Z;(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`})(Z||={}),vQ.create,yQ.create,ZQ.create,bQ.create,xQ.create,SQ.create,CQ.create,wQ.create,TQ.create,EQ.create,DQ.create,OQ.create,kQ.create,AQ.create;const nbe=MQ.create;MQ.strictCreate,NQ.create,$ye.create,IQ.create,LQ.create,ebe.create,RQ.create,zQ.create,tbe.create,BQ.create,VQ.create,UQ.create,WQ.create,GQ.create,KQ.create,qQ.create,JQ.create,KQ.createWithPreprocess,$Q.create;const rbe=Me(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);b.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Oe(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>le(e,t,n),e.parseAsync=async(t,n)=>y(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ce(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)=>re(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),ibe=Me(`ZodMiniObject`,(e,t)=>{m.init(e,t),rbe.init(e,t),r(e,`shape`,()=>t.shape)});function t$(e,t){return new ibe({type:`object`,shape:e??{},...he(t)})}function n$(e){return!!e._zod}function r$(e){let t=Object.values(e);if(t.length===0)return t$({});let n=t.every(n$),r=t.every(e=>!n$(e));if(n)return t$(e);if(r)return nbe(e);throw Error(`Mixed Zod versions detected in object shape.`)}function i$(e,t){return n$(e)?le(e,t):e.safeParse(t)}async function a$(e,t){return n$(e)?await ce(e,t):await e.safeParseAsync(t)}function o$(e){if(!e)return;let t;if(t=n$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function s$(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 r$(e)}}if(n$(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 c$(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 abe(e){return e.description}function obe(e){if(n$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function l$(e){if(n$(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 u$=`2025-11-25`,d$=[u$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],f$=`io.modelcontextprotocol/related-task`,p$=Le(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),m$=S([v(),j().int()]),h$=v();a({ttl:j().optional(),pollInterval:j().optional()});const sbe=w({ttl:j().optional()}),cbe=w({taskId:v()}),g$=a({progressToken:m$.optional(),[f$]:cbe.optional()}),_$=w({_meta:g$.optional()}),v$=_$.extend({task:sbe.optional()}),lbe=e=>v$.safeParse(e).success,y$=w({method:v(),params:_$.loose().optional()}),b$=w({_meta:g$.optional()}),x$=w({method:v(),params:b$.loose().optional()}),S$=a({_meta:g$.optional()}),C$=S([v(),j().int()]),w$=w({jsonrpc:M(`2.0`),id:C$,...y$.shape}).strict(),T$=e=>w$.safeParse(e).success,E$=w({jsonrpc:M(`2.0`),...x$.shape}).strict(),ube=e=>E$.safeParse(e).success,D$=w({jsonrpc:M(`2.0`),id:C$,result:S$}).strict(),O$=e=>D$.safeParse(e).success;var k$;(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`})(k$||={});const A$=w({jsonrpc:M(`2.0`),id:C$.optional(),error:w({code:j().int(),message:v(),data:D().optional()})}).strict(),j$=e=>A$.safeParse(e).success,M$=S([w$,E$,D$,A$]);S([D$,A$]);const N$=S$.strict(),dbe=b$.extend({requestId:C$.optional(),reason:v().optional()}),P$=x$.extend({method:M(`notifications/cancelled`),params:dbe}),F$=w({icons:k(w({src:v(),mimeType:v().optional(),sizes:k(v()).optional(),theme:ze([`light`,`dark`]).optional()})).optional()}),I$=w({name:v(),title:v().optional()}),L$=I$.extend({...I$.shape,...F$.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),fbe=te(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,u(w({form:u(w({applyDefaults:l().optional()}),p(v(),D())).optional(),url:p$.optional()}),p(v(),D()).optional())),pbe=a({list:p$.optional(),cancel:p$.optional(),requests:a({sampling:a({createMessage:p$.optional()}).optional(),elicitation:a({create:p$.optional()}).optional()}).optional()}),mbe=a({list:p$.optional(),cancel:p$.optional(),requests:a({tools:a({call:p$.optional()}).optional()}).optional()}),hbe=w({experimental:p(v(),p$).optional(),sampling:w({context:p$.optional(),tools:p$.optional()}).optional(),elicitation:fbe.optional(),roots:w({listChanged:l().optional()}).optional(),tasks:pbe.optional(),extensions:p(v(),p$).optional()}),gbe=_$.extend({protocolVersion:v(),capabilities:hbe,clientInfo:L$}),R$=y$.extend({method:M(`initialize`),params:gbe}),z$=e=>R$.safeParse(e).success,_be=w({experimental:p(v(),p$).optional(),logging:p$.optional(),completions:p$.optional(),prompts:w({listChanged:l().optional()}).optional(),resources:w({subscribe:l().optional(),listChanged:l().optional()}).optional(),tools:w({listChanged:l().optional()}).optional(),tasks:mbe.optional(),extensions:p(v(),p$).optional()}),vbe=S$.extend({protocolVersion:v(),capabilities:_be,serverInfo:L$,instructions:v().optional()}),B$=x$.extend({method:M(`notifications/initialized`),params:b$.optional()}),ybe=e=>B$.safeParse(e).success,V$=y$.extend({method:M(`ping`),params:_$.optional()}),bbe=w({progress:j(),total:E(j()),message:E(v())}),xbe=w({...b$.shape,...bbe.shape,progressToken:m$}),H$=x$.extend({method:M(`notifications/progress`),params:xbe}),Sbe=_$.extend({cursor:h$.optional()}),U$=y$.extend({params:Sbe.optional()}),W$=S$.extend({nextCursor:h$.optional()}),Cbe=ze([`working`,`input_required`,`completed`,`failed`,`cancelled`]),G$=w({taskId:v(),status:Cbe,ttl:S([j(),A()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:E(j()),statusMessage:E(v())}),K$=S$.extend({task:G$}),wbe=b$.merge(G$),q$=x$.extend({method:M(`notifications/tasks/status`),params:wbe}),J$=y$.extend({method:M(`tasks/get`),params:_$.extend({taskId:v()})}),Y$=S$.merge(G$),X$=y$.extend({method:M(`tasks/result`),params:_$.extend({taskId:v()})});S$.loose();const Z$=U$.extend({method:M(`tasks/list`)}),Q$=W$.extend({tasks:k(G$)}),$$=y$.extend({method:M(`tasks/cancel`),params:_$.extend({taskId:v()})}),Tbe=S$.merge(G$),e1=w({uri:v(),mimeType:E(v()),_meta:p(v(),D()).optional()}),t1=e1.extend({text:v()}),n1=v().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),r1=e1.extend({blob:n1}),i1=ze([`user`,`assistant`]),a1=w({audience:k(i1).optional(),priority:j().min(0).max(1).optional(),lastModified:se({offset:!0}).optional()}),o1=w({...I$.shape,...F$.shape,uri:v(),description:E(v()),mimeType:E(v()),size:E(j()),annotations:a1.optional(),_meta:E(a({}))}),Ebe=w({...I$.shape,...F$.shape,uriTemplate:v(),description:E(v()),mimeType:E(v()),annotations:a1.optional(),_meta:E(a({}))}),s1=U$.extend({method:M(`resources/list`)}),Dbe=W$.extend({resources:k(o1)}),c1=U$.extend({method:M(`resources/templates/list`)}),Obe=W$.extend({resourceTemplates:k(Ebe)}),l1=_$.extend({uri:v()}),kbe=l1,u1=y$.extend({method:M(`resources/read`),params:kbe}),Abe=S$.extend({contents:k(S([t1,r1]))}),jbe=x$.extend({method:M(`notifications/resources/list_changed`),params:b$.optional()}),Mbe=l1,Nbe=y$.extend({method:M(`resources/subscribe`),params:Mbe}),Pbe=l1,Fbe=y$.extend({method:M(`resources/unsubscribe`),params:Pbe}),Ibe=b$.extend({uri:v()}),Lbe=x$.extend({method:M(`notifications/resources/updated`),params:Ibe}),Rbe=w({name:v(),description:E(v()),required:E(l())}),zbe=w({...I$.shape,...F$.shape,description:E(v()),arguments:E(k(Rbe)),_meta:E(a({}))}),d1=U$.extend({method:M(`prompts/list`)}),Bbe=W$.extend({prompts:k(zbe)}),Vbe=_$.extend({name:v(),arguments:p(v(),v()).optional()}),f1=y$.extend({method:M(`prompts/get`),params:Vbe}),p1=w({type:M(`text`),text:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),m1=w({type:M(`image`),data:n1,mimeType:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),h1=w({type:M(`audio`),data:n1,mimeType:v(),annotations:a1.optional(),_meta:p(v(),D()).optional()}),Hbe=w({type:M(`tool_use`),name:v(),id:v(),input:p(v(),D()),_meta:p(v(),D()).optional()}),Ube=w({type:M(`resource`),resource:S([t1,r1]),annotations:a1.optional(),_meta:p(v(),D()).optional()}),g1=S([p1,m1,h1,o1.extend({type:M(`resource_link`)}),Ube]),Wbe=w({role:i1,content:g1}),Gbe=S$.extend({description:v().optional(),messages:k(Wbe)}),Kbe=x$.extend({method:M(`notifications/prompts/list_changed`),params:b$.optional()}),qbe=w({title:v().optional(),readOnlyHint:l().optional(),destructiveHint:l().optional(),idempotentHint:l().optional(),openWorldHint:l().optional()}),Jbe=w({taskSupport:ze([`required`,`optional`,`forbidden`]).optional()}),_1=w({...I$.shape,...F$.shape,description:v().optional(),inputSchema:w({type:M(`object`),properties:p(v(),p$).optional(),required:k(v()).optional()}).catchall(D()),outputSchema:w({type:M(`object`),properties:p(v(),p$).optional(),required:k(v()).optional()}).catchall(D()).optional(),annotations:qbe.optional(),execution:Jbe.optional(),_meta:p(v(),D()).optional()}),v1=U$.extend({method:M(`tools/list`)}),Ybe=W$.extend({tools:k(_1)}),y1=S$.extend({content:k(g1).default([]),structuredContent:p(v(),D()).optional(),isError:l().optional()});y1.or(S$.extend({toolResult:D()}));const Xbe=v$.extend({name:v(),arguments:p(v(),D()).optional()}),b1=y$.extend({method:M(`tools/call`),params:Xbe}),Zbe=x$.extend({method:M(`notifications/tools/list_changed`),params:b$.optional()});w({autoRefresh:l().default(!0),debounceMs:j().int().nonnegative().default(300)});const x1=ze([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Qbe=_$.extend({level:x1}),S1=y$.extend({method:M(`logging/setLevel`),params:Qbe}),$be=b$.extend({level:x1,logger:v().optional(),data:D()}),exe=x$.extend({method:M(`notifications/message`),params:$be}),txe=w({hints:k(w({name:v().optional()})).optional(),costPriority:j().min(0).max(1).optional(),speedPriority:j().min(0).max(1).optional(),intelligencePriority:j().min(0).max(1).optional()}),nxe=w({mode:ze([`auto`,`required`,`none`]).optional()}),rxe=w({type:M(`tool_result`),toolUseId:v().describe(`The unique identifier for the corresponding tool call.`),content:k(g1).default([]),structuredContent:w({}).loose().optional(),isError:l().optional(),_meta:p(v(),D()).optional()}),ixe=oe(`type`,[p1,m1,h1]),C1=oe(`type`,[p1,m1,h1,Hbe,rxe]),axe=w({role:i1,content:S([C1,k(C1)]),_meta:p(v(),D()).optional()}),oxe=v$.extend({messages:k(axe),modelPreferences:txe.optional(),systemPrompt:v().optional(),includeContext:ze([`none`,`thisServer`,`allServers`]).optional(),temperature:j().optional(),maxTokens:j().int(),stopSequences:k(v()).optional(),metadata:p$.optional(),tools:k(_1).optional(),toolChoice:nxe.optional()}),sxe=y$.extend({method:M(`sampling/createMessage`),params:oxe}),w1=S$.extend({model:v(),stopReason:E(ze([`endTurn`,`stopSequence`,`maxTokens`]).or(v())),role:i1,content:ixe}),T1=S$.extend({model:v(),stopReason:E(ze([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(v())),role:i1,content:S([C1,k(C1)])}),cxe=w({type:M(`boolean`),title:v().optional(),description:v().optional(),default:l().optional()}),lxe=w({type:M(`string`),title:v().optional(),description:v().optional(),minLength:j().optional(),maxLength:j().optional(),format:ze([`email`,`uri`,`date`,`date-time`]).optional(),default:v().optional()}),uxe=w({type:ze([`number`,`integer`]),title:v().optional(),description:v().optional(),minimum:j().optional(),maximum:j().optional(),default:j().optional()}),dxe=w({type:M(`string`),title:v().optional(),description:v().optional(),enum:k(v()),default:v().optional()}),fxe=w({type:M(`string`),title:v().optional(),description:v().optional(),oneOf:k(w({const:v(),title:v()})),default:v().optional()}),pxe=S([S([w({type:M(`string`),title:v().optional(),description:v().optional(),enum:k(v()),enumNames:k(v()).optional(),default:v().optional()}),S([dxe,fxe]),S([w({type:M(`array`),title:v().optional(),description:v().optional(),minItems:j().optional(),maxItems:j().optional(),items:w({type:M(`string`),enum:k(v())}),default:k(v()).optional()}),w({type:M(`array`),title:v().optional(),description:v().optional(),minItems:j().optional(),maxItems:j().optional(),items:w({anyOf:k(w({const:v(),title:v()}))}),default:k(v()).optional()})])]),cxe,lxe,uxe]),mxe=S([v$.extend({mode:M(`form`).optional(),message:v(),requestedSchema:w({type:M(`object`),properties:p(v(),pxe),required:k(v()).optional()})}),v$.extend({mode:M(`url`),message:v(),elicitationId:v(),url:v().url()})]),hxe=y$.extend({method:M(`elicitation/create`),params:mxe}),gxe=b$.extend({elicitationId:v()}),_xe=x$.extend({method:M(`notifications/elicitation/complete`),params:gxe}),E1=S$.extend({action:ze([`accept`,`decline`,`cancel`]),content:te(e=>e===null?void 0:e,p(v(),S([v(),j(),l(),k(v())])).optional())}),vxe=w({type:M(`ref/resource`),uri:v()}),yxe=w({type:M(`ref/prompt`),name:v()}),bxe=_$.extend({ref:S([yxe,vxe]),argument:w({name:v(),value:v()}),context:w({arguments:p(v(),v()).optional()}).optional()}),D1=y$.extend({method:M(`completion/complete`),params:bxe});function xxe(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Sxe(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Cxe=S$.extend({completion:a({values:k(v()).max(100),total:E(j().int()),hasMore:E(l())})}),wxe=w({uri:v().startsWith(`file://`),name:v().optional(),_meta:p(v(),D()).optional()}),Txe=y$.extend({method:M(`roots/list`),params:_$.optional()}),O1=S$.extend({roots:k(wxe)}),Exe=x$.extend({method:M(`notifications/roots/list_changed`),params:b$.optional()});S([V$,R$,D1,S1,f1,d1,s1,c1,u1,Nbe,Fbe,b1,v1,J$,X$,Z$,$$]),S([P$,H$,B$,Exe,q$]),S([N$,w1,T1,E1,O1,Y$,Q$,K$]),S([V$,sxe,hxe,Txe,J$,X$,Z$,$$]),S([P$,H$,exe,Lbe,jbe,Zbe,Kbe,q$,_xe]),S([N$,vbe,Cxe,Gbe,Bbe,Dbe,Obe,Abe,y1,Ybe,Y$,Q$,K$]);var k1=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===k$.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Dxe(e.elicitations,n)}return new e(t,n,r)}},Dxe=class extends k1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(k$.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function A1(e){return e===`completed`||e===`failed`||e===`cancelled`}const Oxe=Symbol(`Let zodToJsonSchema decide on which parser to use`),j1={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`},kxe=e=>typeof e==`string`?{...j1,name:e}:{...j1,...e},Axe=e=>{let t=kxe(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 M1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function N1(e,t,n,r,i){e[t]=n,M1(e,t,r,i)}const P1=(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 F1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?P1(t,e.currentPath):t.join(`/`)}}function jxe(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=J1(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&N1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&N1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(N1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),N1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Mxe(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?N1(n,`minimum`,r.value,r.message,t):N1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),N1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?N1(n,`maximum`,r.value,r.message,t):N1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),N1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:N1(n,`multipleOf`,r.value,r.message,t);break}return n}function Nxe(){return{type:`boolean`}}function I1(e,t){return J1(e.type._def,t)}const Pxe=(e,t)=>J1(e.innerType._def,t);function L1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>L1(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 Fxe(e,t)}}const Fxe=(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`:N1(n,`minimum`,r.value,r.message,t);break;case`max`:N1(n,`maximum`,r.value,r.message,t);break}return n};function Ixe(e,t){return{...J1(e.innerType._def,t),default:e.defaultValue()}}function Lxe(e,t){return t.effectStrategy===`input`?J1(e.schema._def,t):F1(t)}function Rxe(e){return{type:`string`,enum:Array.from(e.values)}}const zxe=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Bxe(e,t){let n=[J1(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),J1(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(zxe(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 Vxe(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 R1;const z1={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:()=>(R1===void 0&&(R1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),R1),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 B1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:N1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:N1(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`:H1(n,`email`,r.message,t);break;case`format:idn-email`:H1(n,`idn-email`,r.message,t);break;case`pattern:zod`:U1(n,z1.email,r.message,t);break}break;case`url`:H1(n,`uri`,r.message,t);break;case`uuid`:H1(n,`uuid`,r.message,t);break;case`regex`:U1(n,r.regex,r.message,t);break;case`cuid`:U1(n,z1.cuid,r.message,t);break;case`cuid2`:U1(n,z1.cuid2,r.message,t);break;case`startsWith`:U1(n,RegExp(`^${V1(r.value,t)}`),r.message,t);break;case`endsWith`:U1(n,RegExp(`${V1(r.value,t)}$`),r.message,t);break;case`datetime`:H1(n,`date-time`,r.message,t);break;case`date`:H1(n,`date`,r.message,t);break;case`time`:H1(n,`time`,r.message,t);break;case`duration`:H1(n,`duration`,r.message,t);break;case`length`:N1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),N1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:U1(n,RegExp(V1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&H1(n,`ipv4`,r.message,t),r.version!==`v4`&&H1(n,`ipv6`,r.message,t);break;case`base64url`:U1(n,z1.base64url,r.message,t);break;case`jwt`:U1(n,z1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&U1(n,z1.ipv4Cidr,r.message,t),r.version!==`v4`&&U1(n,z1.ipv6Cidr,r.message,t);break;case`emoji`:U1(n,z1.emoji(),r.message,t);break;case`ulid`:U1(n,z1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:H1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:N1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:U1(n,z1.base64,r.message,t);break}break;case`nanoid`:U1(n,z1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function V1(e,t){return t.patternStrategy===`escape`?Uxe(e):e}const Hxe=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Uxe(e){let t=``;for(let n=0;n<e.length;n++)Hxe.has(e[n])||(t+=`\\`),t+=e[n];return t}function H1(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}}})):N1(e,`format`,t,n,r)}function U1(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:W1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):N1(e,`pattern`,W1(t,r),n,r)}function W1(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
1180
1180
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1181
1181
  ]))`;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 G1(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===Z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:J1(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??F1(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:J1(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=B1(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=I1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function Wxe(e,t){return t.mapStrategy===`record`?G1(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[J1(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||F1(t),J1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||F1(t)],minItems:2,maxItems:2}}}function Gxe(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 Kxe(e){return e.target===`openAi`?void 0:{not:F1({...e,currentPath:[...e.currentPath,`not`]})}}function qxe(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const K1={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Jxe(e,t){if(t.target===`openApi3`)return q1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in K1&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=K1[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 q1(e,t)}const q1=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>J1(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 Yxe(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:K1[e.innerType._def.typeName],nullable:!0}:{type:[K1[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=J1(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=J1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Xxe(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`,M1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?N1(n,`minimum`,r.value,r.message,t):N1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),N1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?N1(n,`maximum`,r.value,r.message,t):N1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),N1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:N1(n,`multipleOf`,r.value,r.message,t);break}return n}function Zxe(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=$xe(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=J1(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=Qxe(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Qxe(e,t){if(e.catchall._def.typeName!==`ZodNever`)return J1(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 $xe(e){try{return e.isOptional()}catch{return!0}}const eSe=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return J1(e.innerType._def,t);let n=J1(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:F1(t)},n]}:F1(t)},tSe=(e,t)=>{if(t.pipeStrategy===`input`)return J1(e.in._def,t);if(t.pipeStrategy===`output`)return J1(e.out._def,t);let n=J1(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,J1(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function nSe(e,t){return J1(e.type._def,t)}function rSe(e,t){let n={type:`array`,uniqueItems:!0,items:J1(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&N1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&N1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function iSe(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>J1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:J1(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>J1(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function aSe(e){return{not:F1(e)}}function oSe(e){return F1(e)}const sSe=(e,t)=>J1(e.innerType._def,t),cSe=(e,t,n)=>{switch(t){case Z.ZodString:return B1(e,n);case Z.ZodNumber:return Xxe(e,n);case Z.ZodObject:return Zxe(e,n);case Z.ZodBigInt:return Mxe(e,n);case Z.ZodBoolean:return Nxe();case Z.ZodDate:return L1(e,n);case Z.ZodUndefined:return aSe(n);case Z.ZodNull:return qxe(n);case Z.ZodArray:return jxe(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return Jxe(e,n);case Z.ZodIntersection:return Bxe(e,n);case Z.ZodTuple:return iSe(e,n);case Z.ZodRecord:return G1(e,n);case Z.ZodLiteral:return Vxe(e,n);case Z.ZodEnum:return Rxe(e);case Z.ZodNativeEnum:return Gxe(e);case Z.ZodNullable:return Yxe(e,n);case Z.ZodOptional:return eSe(e,n);case Z.ZodMap:return Wxe(e,n);case Z.ZodSet:return rSe(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return nSe(e,n);case Z.ZodNaN:case Z.ZodNever:return Kxe(n);case Z.ZodEffects:return Lxe(e,n);case Z.ZodAny:return F1(n);case Z.ZodUnknown:return oSe(n);case Z.ZodDefault:return Ixe(e,n);case Z.ZodBranded:return I1(e,n);case Z.ZodReadonly:return sSe(e,n);case Z.ZodCatch:return Pxe(e,n);case Z.ZodPipeline:return tSe(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.ZodSymbol:return;default:return(e=>void 0)(t)}};function J1(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Oxe)return i}if(r&&!n){let e=lSe(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=cSe(e,e.typeName,t),o=typeof a==`function`?J1(a(),t):a;if(o&&uSe(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const lSe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:P1(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`),F1(t)):t.$refStrategy===`seen`?F1(t):void 0}},uSe=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),dSe=(e,t)=>{let n=Axe(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:J1(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??F1(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=J1(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??F1(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 fSe(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Y1(e,t){return n$(e)?g(e,{target:fSe(t?.target),io:t?.pipeStrategy??`input`}):dSe(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function X1(e){let t=o$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=l$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Z1(e,t){let n=i$(e,t);if(!n.success)throw n.error;return n.data}var pSe=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(P$,e=>{this._oncancel(e)}),this.setNotificationHandler(H$,e=>{this._onprogress(e)}),this.setRequestHandler(V$,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(J$,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new k1(k$.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(X$,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 k1(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 k1(k$.InvalidParams,`Task not found: ${r}`);if(!A1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(A1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[f$]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Z$,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 k1(k$.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler($$,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new k1(k$.InvalidParams,`Task not found: ${e.params.taskId}`);if(A1(n.status))throw new k1(k$.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 k1(k$.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof k1?e:new k1(k$.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),k1.fromError(k$.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),O$(e)||j$(e)?this._onresponse(e):T$(e)?this._onrequest(e,t):ube(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=k1.fromError(k$.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?.[f$]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:k$.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=lbe(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 k1(k$.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:k$.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),O$(e)?n(e):n(new k1(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(O$(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),O$(e)?r(e):r(k1.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 k1?e:new k1(k$.InternalError,String(e))}}return}let i;try{let r=await this.request(e,K$,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new k1(k$.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},A1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new k1(k$.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new k1(k$.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 k1?e:new k1(k$.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||{},[f$]: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 k1?e:new k1(k$.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=i$(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(k1.fromError(k$.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},Y$,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},Q$,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Tbe,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||{},[f$]: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||{},[f$]: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||{},[f$]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=X1(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Z1(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=X1(e);this._notificationHandlers.set(n,n=>{let r=Z1(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`&&T$(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new k1(k$.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 k1(k$.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new k1(k$.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 k1(k$.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=q$.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),A1(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 k1(k$.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(A1(a.status))throw new k1(k$.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=q$.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),A1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Q1(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mSe(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];Q1(a)&&Q1(i)?n[r]={...a,...i}:n[r]=i}return n}var hSe=t(Pa(),1),gSe=t(bi(),1);function _Se(){let e=new hSe.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,gSe.default)(e),e}var vSe=class{constructor(e){this._ajv=e??_Se()}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)}}},ySe=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},w1,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},E1,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 bSe(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 xSe(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 SSe=class extends pSe{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(x1.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 vSe,this.setRequestHandler(R$,e=>this._oninitialize(e)),this.setNotificationHandler(B$,()=>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=x1.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new ySe(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=mSe(this._capabilities,e)}setRequestHandler(e,t){let n=o$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(n$(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=i$(b1,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new k1(k$.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=i$(K$,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new k1(k$.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=i$(y1,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new k1(k$.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){xSe(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&bSe(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:d$.includes(t)?t:u$,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`},N$)}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},T1,t):this.request({method:`sampling/createMessage`,params:e},w1,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},E1,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},E1,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new k1(k$.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof k1?e:new k1(k$.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},O1,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 $1=Symbol.for(`mcp.completable`);function e0(e){return!!e&&typeof e==`object`&&$1 in e}function CSe(e){return e[$1]?.complete}var wSe;(function(e){e.Completable=`McpCompletable`})(wSe||={});const TSe=/^[A-Za-z0-9._-]{1,128}$/;function ESe(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`),!TSe.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 DSe(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 t0(e){let t=ESe(e);return DSe(e,t.warnings),t.isValid}var OSe=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)}},n0=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 SSe(e,t)}get experimental(){return this._experimental||={tasks:new OSe(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(s0(v1)),this.server.assertCanSetRequestHandler(s0(b1)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(v1,()=>({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=s$(t.inputSchema);return e?Y1(e,{strictUnions:!0,pipeStrategy:`input`}):kSe})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=s$(t.outputSchema);e&&(n.outputSchema=Y1(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(b1,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new k1(k$.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new k1(k$.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 k1(k$.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new k1(k$.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 k1&&e.code===k$.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 a$(s$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=c$(`error`in r?r.error:`Unknown error`);throw new k1(k$.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 k1(k$.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await a$(s$(e.outputSchema),t.structuredContent);if(!r.success){let e=c$(`error`in r?r.error:`Unknown error`);throw new k1(k$.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 k1(k$.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(s0(D1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(D1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return xxe(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Sxe(e),this.handleResourceCompletion(e,e.params.ref);default:throw new k1(k$.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new k1(k$.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new k1(k$.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return l0;let r=o$(n.argsSchema)?.[e.params.argument.name];if(!e0(r))return l0;let i=CSe(r);return i?c0(await i(e.params.argument.value,e.params.context)):l0}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 l0;throw new k1(k$.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?c0(await r(e.params.argument.value,e.params.context)):l0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(s0(s1)),this.server.assertCanSetRequestHandler(s0(c1)),this.server.assertCanSetRequestHandler(s0(u1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(s1,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(c1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(u1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new k1(k$.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 k1(k$.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(s0(d1)),this.server.assertCanSetRequestHandler(s0(f1)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(d1,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?ASe(t.argsSchema):void 0}))})),this.server.setRequestHandler(f1,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new k1(k$.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new k1(k$.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await a$(s$(n.argsSchema),e.params.arguments);if(!r.success){let t=c$(`error`in r?r.error:`Unknown error`);throw new k1(k$.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:r$(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=r$(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=>e0(e instanceof Fe?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){t0(e);let l={title:t,description:n,inputSchema:o0(r),outputSchema:o0(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`&&t0(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=r$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=r$(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(a0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!a0(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 kSe={type:`object`,properties:{}};function r0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function i0(e){return`_def`in e||`_zod`in e||r0(e)}function a0(e){return typeof e!=`object`||!e||i0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(r0)}function o0(e){if(e){if(a0(e))return r$(e);if(!i0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function ASe(e){let t=o$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:abe(t),required:!obe(t)})):[]}function s0(e){let t=o$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=l$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function c0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const l0={completion:{values:[],hasMore:!1}};var u0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},jSe=e=>e instanceof u0?e:new u0(e.message,{cause:e}),MSe=global.Request,d0=class extends MSe{constructor(e,t){typeof e==`object`&&p0 in e&&(e=e[p0]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},NSe=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)},f0=Symbol(`wrapBodyStream`),PSe=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new d0(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[f0]){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 d0(t,a)},p0=Symbol(`getRequestCache`),m0=Symbol(`requestCache`),h0=Symbol(`incomingKey`),g0=Symbol(`urlKey`),FSe=Symbol(`headersKey`),_0=Symbol(`abortControllerKey`),v0={get method(){return this[h0].method||`GET`},get url(){return this[g0]},get headers(){return this[FSe]||=NSe(this[h0])},[Symbol(`getAbortController`)](){return this[p0](),this[_0]},[p0](){return this[_0]||=new AbortController,this[m0]||=PSe(this.method,this[g0],this.headers,this[h0],this[_0])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(v0,e,{get(){return this[p0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(v0,e,{value:function(){return this[p0]()[e]()}})}),Object.defineProperty(v0,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[m0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(v0,d0.prototype);var ISe=(e,t)=>{let n=Object.create(v0);n[h0]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof nd)throw new u0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[g0]=new URL(r).href}catch(e){throw new u0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof nd?e.authority:e.headers.host)||t;if(!i)throw new u0(`Missing host header`);let a;if(e instanceof nd){if(a=e.scheme,!(a===`http`||a===`https`))throw new u0(`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 u0(`Invalid host header`);return n[g0]=o.href,n},y0=Symbol(`responseCache`),b0=Symbol(`getResponseCache`),x0=Symbol(`cache`),S0=global.Response,C0=class e{#e;#t;[b0](){return delete this[x0],this[y0]||=new S0(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[y0];if(e){this.#t=e,this[b0]();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[x0]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[x0];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[b0]().headers}get status(){return this[x0]?.[0]??this[b0]().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[b0]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(C0.prototype,e,{value:function(){return this[b0]()[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[y0]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(C0,S0),Object.setPrototypeOf(C0.prototype,S0.prototype);async function LSe(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function w0(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 RSe(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:w0(e.getReader(),t)}var T0=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},zSe=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Jte);var E0=Symbol(`outgoingEnded`),D0=Symbol(`incomingDraining`),BSe=500,VSe=64*1024*1024,O0=e=>{let t=e;if(e.destroyed||t[D0])return;if(t[D0]=!0,e instanceof nd){try{e.stream?.close?.(dne.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,BSe);a.unref?.();let o=e=>{n+=e.length,n>VSe&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},HSe=()=>new Response(null,{status:400}),k0=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),A0=(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))},j0=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},M0=async(e,t)=>{let[n,r,i]=e[x0],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=T0(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=T0(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())):(j0(t),await RSe(r,t)?.catch(e=>A0(e,t))),t[E0]?.()},USe=e=>typeof e.then==`function`,WSe=async(e,t,n={})=>{if(USe(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(k0);if(x0 in e)return M0(e,t);let r=T0(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 LSe(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&&j0(t),await w0(n,t,o))}else r[zSe]||(t.writeHead(e.status,r),t.end());t[E0]?.()},N0=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==d0&&(Object.defineProperty(global,`Request`,{value:d0}),Object.defineProperty(global,`Response`,{value:C0})),async(r,i)=>{let a,o;try{o=ISe(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[f0]=!0,r.on(`end`,()=>{s=!0}),r instanceof nd&&(i[E0]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{O0(r)})})}),i.on(`finish`,()=>{s||O0(r)})),i.on(`close`,()=>{o[_0]&&(r.errored?o[_0].abort(r.errored.toString()):i.writableFinished||o[_0].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{O0(r)})})}),a=e(o,{incoming:r,outgoing:i}),x0 in a)return M0(a,i)}catch(e){if(a)return A0(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:jSe(e)),!a)return}else a=o?k0(e):HSe()}try{return await WSe(a,i,t)}catch(e){return A0(e,i)}}},GSe=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
1182
1182
  `;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=>M$.parse(e)):[M$.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(z$);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(T$)){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=>z$(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)T$(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)T$(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;T$(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&&!d$.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${d$.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${d$.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((O$(e)||j$(e))&&(n=e.id),n===void 0){if(O$(e)||j$(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(O$(e)||j$(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)}}}},KSe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new GSe(e),this._requestListener=N0(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 N0(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 P0=`https://json-schema.org/draft/2020-12/schema`,F0=`tools/list`;function I0(e){let t=e;if(t.__jsonSchemaDialectInstalled===!0)return;let n=e.server._requestHandlers?.get(F0);if(typeof n!=`function`){console.warn(`[json-schema-dialect] No ${F0} 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(v1,async(e,t)=>{let r=await n(e,t);for(let e of r.tools??[])e.inputSchema&&(e.inputSchema.$schema=P0),e.outputSchema&&(e.outputSchema.$schema=P0);return r}),t.__jsonSchemaDialectInstalled=!0}function L0(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||!qSe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=ue(i.error);throw new k1(k$.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function qSe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const R0=2e3,z0=2e3,JSe=[/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 B0(e){return JSe.some(t=>t.test(e))}function YSe(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 XSe(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 ZSe(e){let t=[];for(let n of e.split(`
@@ -2023,7 +2023,7 @@ native-divergence-injected
2023
2023
  `);return o=a?`${o.replace(/\n+$/,``)}\n`:o.replace(/\n+$/,``),i&&(o=o.replace(/\n/g,`\r
2024
2024
  `)),`${n}${o}`}function UNe(e,t){let{bom:n,body:r}=K7(e),i=[],a=_P(r,i,{allowTrailingComma:!0,disallowComments:!1});if(!a||i.length>0||a.type!==`object`)return{kind:`declined`,reason:`unparseable`};if(HNe(a,t.topLevelKey)>1)return{kind:`declined`,reason:`duplicate-container`};let o=[t.topLevelKey,`open-knowledge`],s=vP(a,o);if(!s)return{kind:`no-entry`,raw:e,shell:e};let c=yP(s);if(!W7(c))return{kind:`declined`,reason:`foreign-entry`};let l=pi(c);if(l.kind===`declined`)return{kind:`declined`,reason:`foreign-entry`};let u=r,d=t.managedKeys.map(e=>({key:e,node:vP(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(J7(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 J7(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 WNe(e,t,n){if(!n)return{kind:`declined`,reason:`no-native-writer`};let{bom:r,body:i}=K7(e),a;try{a=n.parseToObject(i)}catch{return{kind:`declined`,reason:`unparseable`}}let o=a[t.topLevelKey],s=W7(o)?o[`open-knowledge`]:void 0;if(s===void 0)return{kind:`no-entry`,raw:e,shell:e};if(!W7(s))return{kind:`declined`,reason:`foreign-entry`};let c=pi(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,J7(t,e)])))}catch{return{kind:`declined`,reason:`unparseable`}}let u=q7(e,l.text);return{kind:`managed`,raw:`${r}${i}`,shell:u,entry:s,descriptor:c.descriptor}}function Y7(e,t,n){return e===null?{kind:`absent`}:Buffer.byteLength(e,`utf8`)>10485760?{kind:`declined`,reason:`oversize`}:t.format===`json`?UNe(e,t):WNe(e,t,n)}function GNe(e,t,n){let{bom:r,body:i}=K7(e),a=i;for(let e of t.managedKeys){let r=_P(a,[],{allowTrailingComma:!0,disallowComments:!1}),o=r?vP(r,[t.topLevelKey,`open-knowledge`,e]):void 0;o&&JSON.stringify(yP(o))===JSON.stringify(n[e])||(a=xP(a,bP(a,[t.topLevelKey,`open-knowledge`,e],n[e],{formattingOptions:VNe(i)})))}return`${r}${a}`}function X7(e,t,n,r){if(t.format===`json`)return GNe(e,t,n);if(!r)return null;let{body:i}=K7(e),a=Object.fromEntries(t.managedKeys.map(e=>[e,n[e]]));try{return q7(e,r.upsertEntry(i,`open-knowledge`,a).text)}catch{return null}}function KNe(e){let t=G7(e.target);return t?X7(e.raw,t,e.entry,e.tomlEditor):null}function Z7(e){let t=G7(e.target);if(!t)return null;let n=Y7(e.raw,t,e.tomlEditor);return n.kind===`managed`||n.kind===`no-entry`?n.shell:null}function qNe(e,t,n){return t.shell===n.shell?t.shell:t.shell===e.shell?n.shell:n.shell===e.shell?t.shell:null}function Q7(e){let t=G7(e.target);if(!t)return{kind:`declined`,reason:`unsupported-target`};let n={base:Y7(e.layers.base,t,e.tomlEditor),head:Y7(e.layers.head,t,e.tomlEditor),index:Y7(e.layers.index,t,e.tomlEditor),worktree:Y7(e.layers.worktree,t,e.tomlEditor),incoming:Y7(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=qNe(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=pi(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=X7(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}}function $7(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 JNe(e,t){return t===`anonymous`?Math.max(180,e):e}const $=N(`sync-engine`),e9=new Set(BNe),t9=/^[0-9a-f]{40}$/i,YNe=ed($l);var n9=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 XNe(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 ZNe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function r9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}const i9={syncScope:{pathBase:`content`}},a9={syncScope:{pathBase:`project`}};function o9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function s9(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 QNe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const c9=12e4;var $Ne=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;rootOkOutsideContentWalk;pullIntervalSeconds;pushIntervalSeconds;mode;credentialConfig;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;mcpTomlEditor;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.rootOkOutsideContentWalk=MM(I(this.contentDir,F(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.ghTokenSource=ONe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??FNe,this.statePath=L(RD(this.projectDir),`sync-state.json`),this.conflictStore=new zZ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return jF(this.projectDir)}gitHandle(e){return dc(this.projectDir,{credentialConfig:this.credentialConfig,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){$.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?F(t,`MERGE_HEAD`):null,r=n!==null&&z(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=$7(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=$7(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),$.info({branch:this.currentBranch,pullDelayMs:o,pushDelayMs:s},`[sync] started`)}stop(){this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.stateSaveTimer!==null&&(clearTimeout(this.stateSaveTimer),this.stateSaveTimer=null),this.state!==`dormant`&&this.transitionTo(`dormant`)}async destroy(){this.stop(),this.saveStateNow()}async setMode(e,t=`config`){if(this.mode===e)return;let n=this.mode;if(this.mode=e,$.info({from:n,to:e,source:t},`[sync] mode changed`),e===`off`){this.cancelScheduledCycles(),await this.drainInFlightCycles(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.transitionTo(this.hasRemote?`disabled`:`dormant`),this.saveStateNow();return}if(this.hasRemote=await this.probeRemote(),this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}e===`follow`&&(await this.drainInFlightCycles(),this.cancelScheduledCycles(),await this.convertStrandedCommitsToOverlay()),this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),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||s9(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||s9(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 lc(()=>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.state!==`auth-error`&&this.pausedReason!==`auth-error`))){if(this.pausedReason=void 0,this.clearPushError(),this.clearPullError(),this.consecutiveFailures=0,this.hasRemote=await this.probeRemote(),!this.hasRemote){this.transitionTo(`dormant`),this.saveStateNow();return}this.transitionTo(`idle`),this.schedulePull(0),this.schedulePush(),this.saveStateNow(),this.probePushPermissionInternal(`refresh`)}}async trigger(e=`sync`){if(this.consecutiveFailures=0,(this.pausedReason===`dirty-tree`||this.pausedReason===`external-changes-pending`||this.pausedReason===`non-content-merge-failure`)&&(this.pausedReason=void 0,this.clearPullError()),this.probePushPermissionInternal(`refresh`),e===`pull`){await this.pullOnce();return}this.state===`dormant`||this.state===`disabled`||this.state===`conflict`||this.state===`auth-error`?$.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`),e===`push`?await this.runPushCycle():(await this.runPushCycle(),await this.runPullCycle())}async pullOnce(){let e=this.mode,t=await this.runOneShotPull();return $.info({mode:e,outcome:t},`[sync] one-shot pull complete`),t}async runOneShotPull(){if(this.pullInFlight||this.pushInFlight||this.state===`conflict`||!this.hasRemote||s9(this.projectDir))return this.recordPullOutcome(`refused`);let e=this.mode,t=this.state,n=this.pausedReason;this.pullInFlight=!0;try{return this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,e===`off`?(this.pausedReason=n,this.transitionTo(t)):this.schedulePull()}}recordPullOutcome(e){return this.lastPullUtc=new Date().toISOString(),this.lastPullOutcome=e,this.cc1Broadcaster?.signal(`sync-status`),e}getStatus(){return{state:this.state,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,lastPullUtc:this.lastPullUtc,lastPullOutcome:this.lastPullOutcome,ahead:this.ahead,behind:this.behind,consecutiveFailures:this.consecutiveFailures,conflictCount:this.conflictCount,hasRemote:this.hasRemote,syncEnabled:this.mode!==`off`,syncMode:this.mode,identityUnresolved:this.identityUnresolved,remote:this.hasRemote?Vme(this.projectDir):null,...this.pushError===void 0?{}:{pushError:this.pushError},...this.pushErrorCode===void 0?{}:{pushErrorCode:this.pushErrorCode},...this.pullError===void 0?{}:{pullError:this.pullError},...this.pullErrorCode===void 0?{}:{pullErrorCode:this.pullErrorCode},pausedReason:this.pausedReason,...this.pushPermission===null?{}:{pushPermission:this.pushPermission}}}async refreshPushPermission(){return this.probePushPermissionInternal(`refresh`)}async refreshIdentity(){let e=await fB(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async applyCommitIdentity(e){let t=await fB(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`;gc(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=AF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,r9(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 n;try{n=await this.checkPushPermissionFn({owner:t.owner,repo:t.repo,host:t.host,transport:t.transport,detectGh:this.detectGh,tokenStore:this.tokenStore})}catch(t){$.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=ZNe(n),i=this.pushPermission;this.pushPermission=r;let a=!1;return r.checkStatus===`denied`&&this.mode===`full`?(this.pausedReason!==`no-push-permission`||this.state!==`disabled`)&&(this.pausedReason=`no-push-permission`,this.transitionTo(`disabled`),a=!0,$.info({reason:r.deniedReason,caller:e},`[sync] paused — no push permission on origin`)):r.checkStatus===`allowed`&&this.pausedReason===`no-push-permission`&&(this.pausedReason=void 0,this.state===`disabled`&&this.mode===`full`&&this.transitionTo(`idle`),a=!0,$.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!r9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}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(!z(F(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?F(n,`MERGE_HEAD`):null;if(r!==null&&z(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.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState())}async resolveConflict(e,t,n){let r=this.conflictStore.list().find(t=>t.file===e)?.variant===`working-tree`;this.setBatchInProgress?.(!0);try{try{await this.conflictStore.resolveConflict(e,t,n)}catch(e){throw this.conflictCount=this.conflictStore.count(),this.scheduleSaveState(),e}r&&($.info({choice:t},`[sync] pull-only: conflict resolved by choice`),await this.notifyContentConflictsResolved([e])),this.conflictCount=this.conflictStore.count(),this.conflictCount===0&&this.state===`conflict`?(this.transitionTo(`idle`),this.pausedReason=void 0,this.schedulePull(),this.schedulePush()):this.cc1Broadcaster?.signal(`sync-status`),this.scheduleSaveState()}finally{this.setBatchInProgress?.(!1)}}updateCurrentBranch(e){e===null?this.state!==`dormant`&&this.state!==`disabled`&&(this.transitionTo(`disabled`),this.pausedReason=`detached-head`,this.scheduleSaveState()):this.currentBranch!==e&&(this.currentBranch=e,this.conflictStore.setBranch(e),this.state===`disabled`&&this.pausedReason===`detached-head`&&(this.pausedReason=void 0,this.transitionTo(`idle`),this.schedulePull(),this.schedulePush()))}schedulePull(e){this.pullTimer!==null&&clearTimeout(this.pullTimer);let t=e??this.effectivePullDelayMs();this.pullTimer=setTimeout(()=>{this.pullTimer=null,this.runPullCycle().catch(e=>{$.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??o9(this.pushIntervalSeconds);this.pushTimer=setTimeout(()=>{this.pushTimer=null,this.runPushCycle().catch(e=>{$.error({err:e},`[sync] push cycle uncaught error`)})},t)}async resolveAuthTier(){let e=this.syncGhTokenHost();if(this.ghTokenSource.get(e)!==null)return`authenticated`;if(this.tokenStore)try{if((await this.tokenStore.get(e))?.token)return`authenticated`}catch(e){$.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`?JNe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=QNe(this.consecutiveFailures);return o9(e>0?e/1e3:this.currentPullIntervalSeconds())}async runPullCycle(){if(!this.pullInFlight&&!(this.state===`dormant`||this.state===`disabled`||this.state===`auth-error`)){if(this.state===`conflict`){this.schedulePull();return}if(s9(this.projectDir)){this.schedulePull();return}this.mode===`follow`&&await this.refreshAuthTier(),this.pullInFlight=!0;try{this.recordPullOutcome(await this.doPullCycle())}finally{this.pullInFlight=!1,this.schedulePull()}}}async doPullCycle(){let e=this.gitHandle(),t;try{let n=(await e.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();if(!n||n===`HEAD`)return this.transitionTo(`disabled`),this.pausedReason=`detached-head`,$.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(z7(e instanceof Error?e:Error(String(e))),`pull`),`error`}this.transitionTo(`fetching`);try{await e.git.fetch(`origin`),this.lastFetchUtc=new Date().toISOString(),this.consecutiveFailures=0,this.clearPullError()}catch(e){let t=z7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;let r=!0,i=!0;try{await this.applyCommitIdentity(e),await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}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`);return await this.persistReconciledMcpEntries(n.reconciled),this.scheduleSaveState(),`succeeded`}catch(e){let t=z7(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(z7(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(z7(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(z7(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(z7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?($.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(z7(Error(`git merge --ff-only timed out after ${c9}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(z7(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(z7(Error(`failed to persist conflict state after fast-forward`)),`pull`),`error`;this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.clearPullError(),this.pausedReason=void 0,this.transitionTo(`idle`),a.newConflicts.length>0&&await this.notifyContentConflictsDetected(a.newConflicts),a.dissolved.length>0&&await this.notifyContentConflictsResolved(a.dissolved),(a.newConflicts.length>0||a.dissolved.length>0)&&this.cc1Broadcaster?.signal(`sync-status`);let o=await this.countStandingOverlay(e);return $.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 YNe(`git`,[`-c`,`core.autocrlf=false`,`merge`,`--ff-only`,`origin/${t}`],{cwd:this.projectDir,env:e.env,windowsHide:!0,timeout:c9}),{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:XNe({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(!z(F(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=B(F(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&&e9.has(p)){let t=await this.readMcpGitBlob(e,n,p),r=Q7({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=jt(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){for(let{path:t,bytes:n}of e){let e=F(this.projectDir,t);fL(e,this.projectDir),Js(e,n)}for(let e of t){let t=F(this.projectDir,e);fL(t,this.projectDir);try{Ps(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=F(this.projectDir,e),n=MM(I(this.contentDir,t));return!n.startsWith(`..`)&&Tx(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(s9(this.projectDir)){this.schedulePush();return}this.pushInFlight=!0;try{await this.doPushCycle(1)}finally{this.pushInFlight=!1,this.schedulePush()}}}async doPushCycle(e=0){let t=F(Iu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),n=null;this.transitionTo(`pushing`);try{let e=this.gatherContentFilesSync();await lc(async()=>{let r=this.gitHandle(t);if(s9(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(z7(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.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)??MM(I(this.contentDir,F(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||!t9.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.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=t instanceof Error?t:Error(String(t));n instanceof n9&&$.warn({err:n},`[sync] push cycle: staging error detail`);let r=z7(n);if(r.class===`semantic`&&r.subclass===`non-fast-forward`){if(e>0){$.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}let n=!0,r=!0;try{await this.applyCommitIdentity(e),await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&(n=await this.popPreMergeStash(e)),r=this.restoreReconciledMcpOverlays(t.reconciled)}if(!n)throw Error(`failed to replay pre-merge working-tree state`);if(!r)throw Error(`failed to restore reconciled MCP overlays`);await this.persistReconciledMcpEntries(t.reconciled)}catch(e){let t=z7(e instanceof Error?e:Error(String(e)));if(t.class===`semantic`&&t.subclass===`merge-conflict`)await this.handleMergeConflict();else if(e instanceof n9)throw e;else this.handleError(t,`pull`);this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}$.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(r,`push`)}finally{try{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=F(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||!t9.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=B(F(this.projectDir,n),`utf8`)}catch{}return Q7({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=e9,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.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:a},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1,reconciled:[]}}if(n.length>0)try{await e.git.raw([`restore`,`--source=HEAD`,`--staged`,`--worktree`,`--`,...n.map(e=>e.path)])}catch(e){return $.warn({err:e},`[sync] could not isolate reconciled MCP paths from pre-merge stash`),this.pullError=`Sync paused — OpenKnowledge could not safely isolate local MCP launcher changes before merging.`,this.pausedReason=`external-changes-pending`,this.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=F(this.projectDir,n.path);fL(e,this.projectDir);let t=null;try{t=B(e,`utf8`)}catch(e){$.warn({err:e,path:n.path},`[sync] could not read MCP config before restoring reconciled overlay`)}t!==n.raw&&Js(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=>z(F(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 lc(async()=>{let t=F(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=KNe({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=Z7({target:o.path,raw:l,tomlEditor:this.mcpTomlEditor}),m=Z7({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(!t9.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=F(this.projectDir,e.path);fL(t,this.projectDir),B(t,`utf8`)!==e.raw&&Js(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 n9(MM(I(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=F(r,c.name);if(c.isDirectory()){let e=MM(I(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=MM(I(i,s));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t,a)){let t=MM(I(this.contentDir,s)),n=MM(I(this.projectDir,s));e.push({contentRelPath:t,projectRelPath:n})}}}};if(z(this.contentDir)&&n(this.contentDir,this.contentDir,i9),this.rootOkOutsideContentWalk){let e=F(this.projectDir,`.ok`);z(e)&&!this.contentFilter.isDirExcluded(`.ok`,a9)&&n(e,this.projectDir,a9,t)}return e}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){let t=F(this.projectDir,e),r=MM(I(this.contentDir,t)),i=!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r,i9),a=this.rootOkOutsideContentWalk&&e.startsWith(`.ok/`)&&!this.contentFilter.isExcluded(e,a9);(i||a)&&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=MM(I(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.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),$.warn({files:t},`[sync] non-content auto-resolve failed — merge aborted, sync paused`);return}if(n.length>0){for(let e of n)this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count(),await this.notifyContentConflictsDetected(n),this.pullTimer!==null&&(clearTimeout(this.pullTimer),this.pullTimer=null),this.pushTimer!==null&&(clearTimeout(this.pushTimer),this.pushTimer=null),this.transitionTo(`conflict`),$.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await this.applyCommitIdentity(e),await e.git.raw([`commit`,`--no-edit`]);let n=fd(this.projectDir);t=n===null||!z(F(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.transitionTo(`auth-error`),this.pausedReason=`auth-error`):e.class===`semantic`&&e.subclass===`protected-branch`?(this.mode=`off`,this.transitionTo(`disabled`),this.pausedReason=`protected-branch`,this.onAutoDisable?.(`protected-branch`)):e.class===`local`&&e.subclass===`dirty-tree`?(this.consecutiveFailures++,this.transitionTo(`idle`),this.pausedReason=`dirty-tree`,this.schedulePush(0)):e.retryable?(this.consecutiveFailures++,this.transitionTo(`offline`)):(this.consecutiveFailures++,this.transitionTo(`idle`))}transitionTo(e){if(this.state===e)return;let t=this.state;this.state=e,$.info({from:t,to:e},`[sync] state: ${t} → ${e}`),this.onStateChange?.(e),this.cc1Broadcaster?.signal(`sync-status`)}scheduleSaveState(){this.stateSaveTimer===null&&(this.stateSaveTimer=setTimeout(()=>{this.stateSaveTimer=null,this.saveStateNow()},5e3))}saveStateNow(){try{let e=this.pausedReason===`no-push-permission`||this.pausedReason===`auth-error`?void 0:this.pausedReason,t={version:1,lastSyncUtc:this.lastSyncUtc,lastFetchUtc:this.lastFetchUtc,lastPushedSha:this.lastPushedSha,consecutiveFailures:this.consecutiveFailures,pausedReason:e,pausedSinceUtc:e?new Date().toISOString():void 0,inflightConflicts:this.conflictStore.list().map(e=>e.file)};ju(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){$.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(z(this.statePath))try{let e=B(this.statePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;this.lastSyncUtc=t.lastSyncUtc??null,this.lastFetchUtc=t.lastFetchUtc??null,this.lastPushedSha=t.lastPushedSha??null,this.consecutiveFailures=t.consecutiveFailures??0,this.pausedReason=t.pausedReason===`no-push-permission`||t.pausedReason===`auth-error`?void 0:t.pausedReason;let n=t.inflightConflicts??[];if(n.length>0){for(let e of n)this.conflictStore.list().some(t=>t.file===e)||this.conflictStore.addConflict({file:e,detectedAt:new Date().toISOString()});this.conflictCount=this.conflictStore.count()}}catch(e){$.warn({err:e},`[sync] failed to load sync state`)}}};hs();const ePe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function tPe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Lx(e)||Rx(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&ePe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{xs(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),gs.with(ps.extract(gs.active(),r),e)}else e()}catch(e){N(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let l9=!1;function u9(){if(l9)return;let e=mne;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){l9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),l9=!0}catch(e){N(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const nPe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})(),rPe=(()=>{let e=Object.freeze({origin:`generated-index`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function iPe(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`],RM({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return N(`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 N(`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(`
2025
2025
  `)){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=L(e,r);if(!FM(a,t))continue;let s=Sz(a,t);i.has(s)||z(a)&&i.set(s,o)}return i}function d9(e){u9();let t=e.ingressPolicy??TB({}),{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=N(`server`),x=new K5,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),T=e=>x.deleteReconciledBase(e),E=e=>x.switchReconciledBaseScope(e),ee=e=>x.setBatchInProgress(e),te=()=>x.isBatchInProgress();function ne(e){let t=Ss({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!t.valid){let n=Se(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 re(){let e=Ss({absPath:Rs(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=_e(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=Ss({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:ve(n.value.autoSync?.default)??`off`,source:`committed-default`}}function ie(){let e=Ss({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules,t=e?Mn(e):Fr;return EMe(r,t.plugins.okf),t}function D(){return Ss({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 O(){return Pj(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function k(){let e=Ss({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 ae(){return ws({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function oe(){for(let e of ae().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 se(e){return`${pj(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}let ce;function le(e,t){let i;if(e===`__config__/project`||e===`__local__/project`){let t=re();i=t.mode,$t?.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 a=O();if(Ie.applyConfig({enabled:a.enabled,providerFingerprint:se(a)}),e===`__config__/project`){try{let e=ne({requireValid:!0});ge?.setAttachmentFolderPath(e),ce!==void 0&&e!==ce&&b.warn({previous:ce,next:e},`[content-filter] attachment folder changed — files under the previous folder no longer sync`),ce=e}catch(e){b.warn({err:e},`[content-filter] project config invalid — keeping previous attachment admission`)}ke?.signal(`lint-config`),(t??ie().plugins.okf?.generate?.index===!0)||N5({projectDir:r,contentDir:n,generatedDocNames:St(),enabled:!1}).then(e=>{e.ok||b.warn({state:e.status.state},`[index] could not remove Open Knowledge generated-index Git attributes`)}),_t()}b.info({docName:e,autoSyncMode:i,semanticEnabled:a.enabled},`[config] applied persisted config to in-process consumers`)}Xs();let ue=qu(),de=RD(r),fe=new Vd({localDir:de,log:N(`acp-registry`)}),A=new Fd(de,N(`acp-permissions`));if(Cc(de,{port:0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{I7({lockDir:de,shadowRepoDir:pd(r)})}catch(e){throw wc(de),e}let pe=Co(),me=(e,t)=>pe.resolveEmbed(e,t),he=(e,t)=>{let r=pe.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=L(n,r);if(!NM(i,L(n)))return null;try{let e=ku(i);return e.isFile()?e.size:null}catch{return null}},ge,ye,be,j,M,xe,Ce,we,Te,De,Oe,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=null,Fe=O(),Ie=new Gj({loadEmbedder:e.embedderLoader??(()=>{let t=O();return yj({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:F(RD(r),`embeddings`),enabled:Fe.enabled,providerFingerprint:se(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 Y5(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,ft()},500),Ye.unref?.())}function dt(){if($e){ct({status:`cancelled`,indexCount:0});return}nt=!0,rt=!0,Xe=setImmediate(()=>{Xe=void 0,ft()})}function ft(){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 Et(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 pt(){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 mt(e){$e||mMe(e)||(tt.add(B5(e)),ut())}function ht(e){if(!$e){for(let t of pMe(e))tt.add(t);ut()}}function gt(e){let t=Zt?.getFileIndex();if(!t){mt(e);return}let n=B5(e);if(U5(t.keys()).has(n)){mt(e);return}ht(B5(n))}function _t(){$e||(nt=!0,ut())}function vt(e){let t=Zt?.getFileIndex().get(e);if(t)return{title:t.title,description:t.description,type:t.type}}let yt=!1,bt={origin:rPe,writer:fce,isConflict:e=>$t?.getConflicts().some(t=>y5(t,e,r,n))===!0,getDocument:e=>Ce.documents.get(e),writeDisk:async(e,t)=>{zs(P(e),{recursive:!0}),await Ts(e,t,{fs:ks})},registerWrite:(e,t)=>lz(e,dz(t)),noteFileIndex:e=>Zt?.mutateFileIndex({kind:e.kind,path:e.absPath,docName:e.docName,content:e.markdown}),signalFiles:()=>Je(`files`),attribute:async(e,t)=>{EA(e,t.id,t.name,t.id),yt=!0}};function xt(e){return e===``?R5:`${e}/${R5}`}function St(){return[...Zt?U5(Zt.getFileIndex().keys()):new Set([``])].map(xt)}function Ct(e){let t=ie().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 wt(){return Ct(j5({projectDir:r,contentDir:n,generatedDocNames:St()}))}async function Tt(e){let t=await N5({projectDir:r,contentDir:n,generatedDocNames:St(),enabled:e});if(!t.ok)return{...wt(),applied:!1,reason:t.status.state===`conflict`?`git-conflict`:`git-unavailable`};let i=await ys({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{...wt(),applied:!1,reason:`config-write`}}try{let e=B(i.path,`utf-8`);v5(Ce.documents.get(`__config__/project`)??null,ho,e,M.configPersistenceCtx)}catch(e){b.warn({err:e},`[index] generated-index settings reflection deferred to config watcher`)}return le(ho,e),{...wt(),applied:!0}}async function Et(t,i){let a=0,o=t.fullSweep?performance.now():void 0,s=()=>ie().plugins.okf?.generate?.index!==!0;try{if(i.aborted)return{status:`cancelled`,indexCount:0};if(s())return{status:`disabled`,indexCount:0};let c=Zt?.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=hMe({docs:c,docExtension:Mx,currentMarkdownFor:()=>null}),l=j5({projectDir:r,contentDir:n,generatedDocNames:o.map(({directory:e})=>xt(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=xt(r),l=L(n,`${o}.md`),u;try{u=B(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&b.warn({err:e,path:Vs(l)},`[index] could not read the existing generated index; treating it as absent`),u=null}a+=1;let d=await Xje({docName:o,absPath:l,markdown:c,currentMarkdown:u},bt);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&&ht(B5(r))}}finally{yt&&=(await M.waitForPendingCommits(),await M.flushContributors(),!1),o!==void 0&&(SL(`generatedIndexSweepMs`,Math.round((performance.now()-o)*100)/100),CL(`generatedIndexCount`,a))}return{status:`completed`,indexCount:a}}catch(e){return b.warn({err:e},`[index] index regeneration failed`),{status:`failed`,indexCount:a}}}let Dt=null,Ot=!1,kt=()=>{try{D7(r,At.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},At=new iNe(void 0,{onEviction:()=>Gse(),onSizeChange:e=>Kse(e),onMutate:()=>{!Ot||Dt!==null||(Dt=setTimeout(()=>{Dt=null,kt()},2e3))}});for(let[e,t]of lNe(r))Ux(e)||SZ(e)&&([`.md`,`.mdx`].some(t=>{let r=L(n,`${e}${t}`);return NM(r,L(n))&&z(r)})||At.restore(e,t));Ot=!0;let jt={current:null},Mt=(e,t)=>{Ux(e)||At.setRenamed(e,t)},Nt=e=>{if(!Ux(e)){if(At.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}At.setDeleted(e),jt.current?.deleted(e)}},Pt=e=>{Ux(e)||At.delete(e)};try{let m=`./`;try{m=ne()}catch(e){b.warn({err:e},`[content-filter] invalid attachment folder at boot — using sibling admission`)}ce=m,ge=WN({projectDir:r,contentDir:n,singleDocRelPath:v,attachmentFolderPath:m,inPlaceSkillDirs:dL(n),rescanInPlaceSkillDirs:()=>dL(n),skillRootPaths:Hhe(n),onAfterRebuild:()=>{ye.refreshContentScope().catch(e=>{N(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),Jz(Zt).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?N(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):N(`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=>{N(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),ye=new zR({projectDir:r,contentDir:n,contentFilter:ge,getGlobalSkillRoots:()=>GK(M.managedArtifactCtx),signalChannel:Je,getLocalTargetInventory:()=>zK(Zt,n),onRecoveredFileTarget:(e,t)=>{Zt&&oNe({watcher:Zt,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:Ne})}}),be={current:f},j=s?GMe({getShadow:()=>be.current??null,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:fd(r)??void 0,isWriterLive:e=>{if(!Me&&!we)return N(`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 we?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,M=b7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:be,ephemeral:y,contentRoot:p,derivedDocumentIndex:ye,configHomedirOverride:u,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,getPrincipal:()=>Le,onAgentCommit:()=>ke?.signal(`session-activity`),onFlushCommit:()=>j?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ke?.emitDiskAck(e,t),!Ux(e)&&(gMe(r,n,e)&&mt(e),WB(r,n)&&(Ne?.(),Je(`files`)))},onConfigRejected:(e,t)=>ke?.emitConfigValidationRejected(e,t),onConfigPersisted:le,isRecentlyRemoved:e=>At.has(e),mdManager:e.mdManager,getLossRing:()=>xe,durabilityState:x}),Ce=new Pje({quiet:i,debounce:a,maxDebounce:o,extensions:[M.extension]});let _=Ce;Be.push(gle(()=>_.documents.size),_le(()=>M.getQueueDepths()),_C(()=>{let e=0;for(let t of _.documents.values())e+=t.directConnectionsCount;return{websocket:_.getConnectionsCount()-e,direct:e}})),yC(),y||(Pe=nNe({getLoadedDocuments:()=>_.documents,forceStore:(e,t)=>M.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let t=PM(e,n),r,i;try{r=V(t),i=ku(r).size}catch(t){let n=Ec(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new S7(`symlink cycle at content path: ${e}`):t}if(!FM(r,n))throw new S7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new S7(`document exceeds the open byte limit: ${e}`);try{return B(r,`utf-8`)}catch(e){if(Ec(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let S=Ce.shouldUnloadDocument.bind(Ce);Ce.shouldUnloadDocument=e=>{if(Re.has(e)||ze&&S(e))return!0;let t=e.name;return Ux(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:S(e)},Ve=async e=>{Re.add(e);try{await Ce.unloadDocument(e)}finally{Re.delete(e)}},ke=new qx(Ce),je=new uE(Ce),Me=new dE(Ce),we=new rw(Ce,e.agentSessionOptions);let w=we;Be.push(vC(()=>({active:w.liveSessionCount,limit:w.sessionLimit})));let T=Q5({derivedDocumentIndex:ye,onDocumentSettled:e=>jt.current?.changed(e)});Ce.configuration.extensions.push(T);function E(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Ce.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=MZ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==ue)throw E(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:ue}),new jZ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${ue}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await qe();if(t!==null&&i!==t)throw E(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new jZ(`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`}}),Ce.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!Rx(e.documentName)&&!zx(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!EB(r,t))throw E(`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(!OB(a,t))throw E(`config-doc-admission-denied`,e.documentName,{check:`host`}),Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${e.documentName})`)}});let ee=L(n);function te(e){if(!SZ(e))return null;let t=L(ee,Px(e));return NM(t,ee)?t:null}Ce.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await sNe(e.documentName,{recentlyRemovedDocs:At,resolveFilePath:te,fileExists:z})}}),Ce.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=MZ(e.token);_Me(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ce.documents.get(e)})}}),Ce.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new R8(e.update);if(t.readVarString(),t.readVarUint()===Y8.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Ni} rejected — server-only channel`)}});let re=CZ({hocuspocus:Ce,durabilityState:x,ingressPolicy:t,sessionManager:we,commentDocHooksRef:jt,contentDir:n,getGeneratedIndexSettingsStatus:wt,setGeneratedIndexEnabled:Tt,contentFilter:ge,serverInstanceId:ue,getFileIndex:()=>Zt?Zt.getFileIndex():new Map,getAttachmentFolderPath:ne,getAllFilesIndex:()=>Zt?Zt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>Zt?.getFileIndexGeneration()??0,mutateFileIndex:e=>{let t=e.kind===`update`?vt(e.docName):void 0;switch(Zt?.mutateFileIndex(e),e.kind){case`update`:G5(t,e.content,e.docName)&&mt(e.docName);break;case`create`:case`conflict`:mt(e.docName);break;case`delete`:gt(e.docName);break;case`rename`:gt(e.oldDocName),mt(e.newDocName);break;case`folder-create`:case`folder-delete`:ht(e.relativePath);break;case`asset-create`:case`asset-delete`:case`file-create`:case`file-update`:case`file-delete`:break;default:iz(e)}},getFolderIndex:()=>Zt?Zt.getFolderIndex():new Map,getAliasMap:()=>Zt?Zt.getAliasMap():new Map,getFolderAliasIndex:()=>Zt?Zt.getFolderAliasIndex():new Map,rescanFiles:()=>Zt?.rescanFromDisk(),enableTestRoutes:d,shadowRef:be,flushGitCommit:()=>M.flushPendingGitCommit(),flushContributors:()=>M.flushContributors(),getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ke?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,derivedDocumentIndex:ye,signalChannel:Je,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>$t,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:me,getBridgeLossReporter:()=>Oe,getPrincipal:()=>Le,acpRegistry:fe,loadAcpCustomAgents:()=>Hd(de,N(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Ve,ready:We,recentlyRemovedDocs:At,serializeDoc:zt,evictManagedArtifactLkg:e=>{M.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Ie,getSemanticSimilarityFloor:()=>O().similarityFloor,getLinterBaseConfig:()=>ie(),getLinksValidationSetting:()=>D(),getLinkPreviewsEnabled:k,getConfigDiagnostics:ae,embeddingsSecretsFile:Ej(u),readSemanticProviderConfig:O,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Ne=e}});Ce.configuration.extensions.push(re),Te=re.nativeApi,De=re.localApi;let oe=Ss({absPath:Rs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),se=oe.value.bridge.deferGuard.enabled,A=oe.value.bridge.fixedPoint.enabled,pe=oe.value.bridge.preDrain.enabled;xe=oe.value.lossCapture.enabled?new Poe({projectDir:r,maxBytes:oe.value.lossCapture.maxBytes}):void 0,oe.value.bridge.lossDetector.enabled&&(Oe=Ece({shadow:()=>be.current,ring:xe,getBranch:()=>Qt?.getLastKnownBranch()??`main`,contentRoot:p??``}),we.attachBridgeLossReporter(Oe)),Ce.configuration.extensions.push(k7({mdManager:vs,schema:_s,shadowRef:be,contentRoot:p,getCurrentBranch:()=>Qt?.getLastKnownBranch()??null,resolveEmbed:me,resolveSize:he,deferGuardEnabled:se,lossDetectorEnabled:oe.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:A,preDrainEnabled:pe,lossRing:xe})),Ce.configuration.extensions.push(tPe()),Ce.configuration.extensions.push(Yje({getSyncEngine:()=>$t,projectDir:r,contentDir:n}))}catch(e){for(let e of Be.splice(0))e();throw Pe?.dispose(),Pe=null,wc(de),e}let Ft=null,It=new Map,Lt=[];function Rt(e,t){let n=L(e,`rescue`),r=L(n,Px(t));return NM(r,n)?r:null}function zt(e){let t=Ce.documents.get(e);return t?QR(t):null}let Bt=(e,t)=>YR(x,Ce,e,t,me,he,Oe);function Vt(e){if(!nS(e)||$t?.getConflicts().some(t=>y5(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let Ht=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ce.documents){if(Ux(n))continue;let r=Ce.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{VR(r,i,me,n)},BR)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},Ut=null,Wt=e=>{e&&(Ut===null&&(Ut=new Set,setImmediate(()=>{let e=Ut;if(Ut=null,e)try{for(let t of e)Ht(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),Ut.add(e))};function Kt(e){switch(e.kind){case`rename`:return e.newDocName;case`asset-create`:case`asset-delete`:case`folder-create`:case`folder-delete`:case`file-create`:case`file-update`:case`file-delete`:return e.relativePath;case`create`:case`update`:case`delete`:case`conflict`:return e.docName;default:return iz(e)}}async function qt(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await ye.recordDiskUpsert(e.docName,e.content),Je(`files`),mt(e.docName),Pt(e.docName);break;case`update`:{let{docName:t,content:n}=e;G5(e.previousIndexedFields,n,t)&&mt(t);let r=Ce.documents.get(t);if(!r){await ye.recordDiskUpsert(t,n);return}let i=C(t)??``,a=zt(t)??i,o=GR({docName:t,base:i,ours:a,theirs:n}),s=dz(i).slice(0,6),c=dz(a).slice(0,6),l=dz(n).slice(0,6);switch(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`:Vt(r),await ye.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{Bt(t,o.newContent),w(t,o.newContent),jb(),Vt(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),Vt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{Bt(t,o.newContent),w(t,n),jb(),Vt(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),Vt(r)}e&&await ye.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{Bt(t,o.newContent),w(t,o.newContent),jb(),Mb(),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 ye.recordDiskUpsert(t,n);break}case`refused`:{Mb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n){await ye.recordDiskDelete(t),Je(`files`),Nt(t),gt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=zt(t)??``,a=i!==r;if(a&&be.current){let e=be.current,n=Qt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{vx(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Pb(),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 ye.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ce.closeConnections(t),await Ve(n),Je(`files`),Nt(t),gt(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));break}case`rename`:{let{oldDocName:t,newDocName:n,content:r}=e,i=Ce.documents.get(t);if(T(t),w(n,r),await ye.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`),Mt(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`})),gt(t),mt(n);break}case`conflict`:{let{docName:t}=e,n=Ce.documents.get(t);if(!n)return;let r=zt(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`:pe.add(e.relativePath),Je(`files`),Wt(ru(e.relativePath));break;case`asset-delete`:pe.remove(e.relativePath),Je(`files`),Wt(ru(e.relativePath));break;case`folder-create`:case`folder-delete`:Je(`files`),ht(e.relativePath);break;case`file-create`:case`file-update`:await ye.recordFileTargetUpsert(e.relativePath),Ne?.(),Je(`files`);break;case`file-delete`:await ye.recordFileTargetDelete(e.relativePath),Ne?.(),Je(`files`);break;default:iz(e)}}catch(t){let n=Kt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let Jt=[];async function Yt(e){if(te()){Jt.push(e);return}await qt(e)}async function Xt(){let e=Jt.splice(0,Jt.length);for(let t of e)await qt(t)}let Zt=null,Qt=null,$t=null,en=null;async function tn(e){if(Ce.documents.size===0)return;let t=!1,n=new Promise(e=>{Ce.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ce.documents.keys());Ce.closeConnections(),Ce.flushPendingStores();for(let e of Ce.documents.values())e.getConnectionsCount()===0&&Ce.unloadDocument(e).catch(t=>{console.warn(JSON.stringify({event:`ok-shutdown-unload-document-failed`,docName:e.name,reason:t instanceof Error?t.message:String(t)}))});let i,a=new Promise((n,a)=>{i=setTimeout(()=>{t=!0;let n=Array.from(Ce.documents.keys()),i=[],o=[];if(be.current){for(let e of n)if(!Ux(e))try{let t=zt(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=Rt(be.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:be.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}yu(P(n),{recursive:!0}),ju(n,t,`utf-8`),Pb(),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 nn(){return en||(en=(async()=>{let e=Date.now(),t=[];ze=!0;try{await pt()}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{Sc(de)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}if(Dt!==null&&(clearTimeout(Dt),Dt=null),Ot)try{D7(r,At.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=Ce.documents.size;j?.destroy();try{try{try{Ae&&=(clearTimeout(Ae),null),Qt&&=(await Qt.unsubscribe(),null),Zt&&=(await Zt.unsubscribe(),null);for(let{docName:e,cleanup:t}of Lt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}Lt.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(),Ft&&=(await Ft.disconnect(),null);for(let[e,t]of It)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}It.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 we.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 Hce()}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 tn(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`)}ye.close();let e;try{await Promise.race([(async()=>{await M.flushPendingGitCommit(),await M.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{$t&&=(await $t.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(be.current){let e;try{await Promise.race([Qb(be.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 hc({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&ju(L(be.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{oce(be.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{wc(de,{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 Ys()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),en)}let rn=[];async function an(){try{Le=await C7(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(!be.current)try{be.current=await ix(r),b.info({gitDir:be.current.gitDir},`[server] history repo initialized at ${be.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),rn.push(`shadow-repo`)}if(be.current){let e=null;try{e=Vq(be.current.gitDir),cge(be.current.gitDir,e),Kq(be.current.gitDir,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(e){let t=1e4;try{await Promise.race([cJ(be.current,e,{rebuild:!0}),new Promise((e,n)=>setTimeout(()=>n(Error(`boot-time GC exceeded ${t}ms`)),t))])}catch(e){b.warn({err:e},`[rename-log] boot-time GC/rebuild failed; index loaded without GC`)}}try{await j?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(be.current)try{await nx(be.current).raw(`rev-parse`,`--git-dir`)}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes(`not a git repository`)||t.includes(`invalid object`)){b.warn({},`[server] history repo appears corrupted — reinitializing`);try{be.current=await ix(r)}catch(e){b.error({err:e},`[server] history repo reinit failed`),be.current=void 0,rn.includes(`shadow-repo`)||rn.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(be.current)try{let e=L(be.current.gitDir,`last-known-head`),t=null;try{t=B(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await hc({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await hc({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 hx(be.current,p??``,t,n,e),Nb()}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=xq(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`),rn.push(`managed-rename-recovery`)}try{let e=Yhe(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`),rn.push(`upload-tempfile-sweep`)}try{Ft=await Ce.openDirectConnection(Ni),ke?.emitServerInfo(ue,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),rn.push(`cc1-push`)}let t=y?[]:Gt;for(let e of t)try{let t=await Ce.openDirectConnection(e);It.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),rn.push(`config-doc:${e}`)}let i=new Map([[ho,Rs(`project`,r)],[fn,Rs(`project-local`,r)],[Hr,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 c5(t,t=>{let n=Ce.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=v5(n??null,e,t,M.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),le(e)});Lt.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}`),rn.push(`config-file-watcher:${e}`)}}if(!y){let e=(e,t)=>{let n=XK(e,M.managedArtifactCtx);if(!n)return;let r=tq(Ce.documents.get(n)??null,n,t,M.managedArtifactCtx);b.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Je(`files`),sa(n)&&ye.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=XK(e,M.managedArtifactCtx);Je(`files`),t&&sa(t)&&ye.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=GK(M.managedArtifactCtx),r=await KMe(n,e,t);Lt.push({docName:`__skill-files__`,cleanup:r}),b.info({roots:n},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),rn.push(`managed-artifact-watcher:skills`)}try{let e=L(HK(M.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await c5(e,()=>{Je(`files`)});Lt.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`),rn.push(`skill-state-watcher`)}}try{let e=L(n,`.okignore`),t=L(r,`.gitignore`),i=null;try{let e=tu(`git`,[`rev-parse`,`--git-common-dir`],RM({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=F(L(r,e.stdout.trim()),`info`,`exclude`);z(P(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 Bje(a,(t,n)=>{(async()=>{if(t===e)try{let e=v5(Ce.documents.get(`__config__/okignore`)??null,vn,n,M.configPersistenceCtx);o.info({docName:vn,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:I(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:I(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ke?.signal(`files`);else{let e=I(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:I(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(Lt.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`),rn.push(`ignore-files-watcher`)}let a=Y5(r).branch??`main`;E(a),Ge();let o=ye.beginStartup(a),s=!1,c=performance.now();try{await Ds(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&rn.push(`backlink-index`);let i=0;for(let t of e)Ux(t)||At.peek(t)?.kind!==`renamed`&&(At.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=ge?dL(n):new Set,d=e=>{e.some(e=>c.test(I(n,e).split(R).join(`/`)))&&(Ae&&clearTimeout(Ae),Ae=setTimeout(()=>{Ae=null;try{aX(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=dL(n);if(!(e.size!==l.size||[...e].some(e=>!l.has(e))))return;l=e,ge.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))};Zt=await Ds(`ok.boot.seed-walk`,void 0,async()=>qz(n,Yt,ge,{onRawBatch:d})),aX(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();aX(e,e,lL(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`))}SL(`seedWalkMs`,Math.round(performance.now()-a));{let e=L(n),t=0;for(let[n]of At.entries()){if(!SZ(n))continue;let r=L(e,`${n}${Mx(n)}`);NM(r,e)&&z(r)&&(At.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 ye.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&rn.push(`tag-index`);let p=0;try{v===void 0?await EZ({contentDir:n,contentFilter:ge,basenameIndex:pe,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):mye({contentDir:n,basenameIndex:pe,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`),rn.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),rn.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),rn.push(`file-watcher`),!s){let e=await ye.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&rn.push(`tag-index`)}}finally{SL(`indexesMs`,Math.round(performance.now()-c)),Zt&&CL(`fileCount`,Zt.getFileIndex().size)}try{Qt=await SMe(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),Hoe(),Ce.flushPendingStores(),await M.flushPendingGitCommit(),ee(!0),be.current){let e=S(),t=Y5(r).branch??e,n=[];for(let[e,t]of Ce.documents){if(Ux(e))continue;let r=null;if(t.transact(()=>{r=zt(e)},nPe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await _ce(be.current,e,px.id,n,t);r&&(Goe(),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=Jt.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(ee(!1),await Xt(),e.headMoved&&e.newHead){let t=iPe(r,L(n),e.oldHead,e.newHead);if(t.size>0){DA(t.keys());for(let[e,n]of t)EA(e,yne(n.email),n.name,n.email,Td(e));await M.flushContributors()}}if(await M.flushDeferredStores(`within-branch`),$t!==null)try{await $t.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Woe(),Jt.splice(0,Jt.length);let t=!1,r;try{E(i),r=await ye.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;pe.clear(),await EZ({contentDir:n,contentFilter:ge,basenameIndex:pe,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`),rn.includes(`basename-index-partial`)||rn.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Ce.documents)if(!Ux(e))try{let r=PM(e,n);if(!z(r)){let n=C(e)??``,r=zt(e)??``;if(r!==n&&be.current){let t=be.current;queueMicrotask(()=>{vx(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Pb(),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=B(r,`utf-8`);Bt(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:Ce.documents.size},`[branch-switch] loaded branch ${i} (${Ce.documents.size} docs)`);try{await ye.settleBranchFromDisk(r)}catch(e){ye.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(be.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ce.documents)if(!Ux(t))try{let n=await yce(be.current,i,px.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=GR({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:Bt(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:Bt(t,a.newContent),w(t,a.newContent),Mb(),e++;{let e=Ce.documents.get(t);if(e){let t=e.getMap(`lifecycle`);t.set(`status`,`conflict`),t.set(`reason`,`merged-with-markers`)}}break;case`noop`:case`refused`:break}}catch(e){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-`)&&be.current)try{let t=nx(be.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await Qb(be.current).withMutator(async()=>{for(let e of n.split(`
2026
- `))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`)}ee(!1),await M.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(ee(!1),await M.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await hx(be.current,t,e.oldHead,e.newHead,i);Nb(),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`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Dx(e),a=Ce.documents.get(i);if(!a)continue;let o=zt(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=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Dx(e));i&&Vt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=MF(r);b.debug({resetAmbientCredentials:f,originKind:AF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=mc(h,{resetAmbient:f}),g=re();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{$t=new $Ne({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||M.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=be.current;n&&await _x(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await _x(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 ys({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:Ee(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 $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Je(`files`),ye.announceReadyViews();let _=xL();_!==void 0&&SL(`readyMs`,_),oe()}return an().then(()=>{Qe=!0,He(),dt()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:j,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:nn,ready:We,generatedIndexSweepReady:st,degraded:rn,lockDir:de,get syncEngine(){return $t},getLinkPreviewsEnabled:k,resolveEmbed:me,acpRegistry:fe,acpPermissions:A}}function f9(e){return e/1048576}function aPe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;Es(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function oPe(){if(p9)return;let e=Zs().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}=aPe();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`})}),p9=e}function sPe(){if(!m9){let e=Zs().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(!_9){_9=ene({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=Zs().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=v9;if(v9={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`}))}),h9=e}}const y9=N(`skill-migrate`);function b9(e){return[{host:`agents`,root:Si},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=RE.indexOf(e.host),r=RE.indexOf(t.host);return(n===-1?RE.length:n)-(r===-1?RE.length:r)||e.host.localeCompare(t.host)})}const cPe=b9(kn),lPe=b9(Fn);function uPe(e,t){return z(L(e,st(t)))}function dPe(e,t){zs(P(t),{recursive:!0});try{Ms(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Hs(e,t,{recursive:!0}),Us(e,{recursive:!0,force:!0})}}function fPe(e,t,n){let r=AI(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 x9(e,t){let n;try{n=V(L(e,`.ok`,`skills`))}catch{n=L(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!V(L(e,t.dir)).startsWith(n+R)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??cPe,a={migrated:[],skipped:[]};if(!z(n))return a;let o;try{o=wu(n)}catch{return a}let s=I(t,n).split(R).join(`/`),c=new Set;for(let[e,n]of Object.entries(nX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!no.test(e)||GF.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=L(n,e);if(!z(F(o,`SKILL.md`)))continue;let s=ME(o)?.contentHash;if(s===void 0)continue;let l=V(o),u=i.map(({host:n,root:r})=>{let i=L(t,r);return{host:n,root:r,path:F(i,e),escapes:RI(t,i),state:fPe(F(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=>uPe(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`?Us(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Us(d.path,{recursive:!0,force:!0}),dPe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Us(e.path,{recursive:!0,force:!0}),Hs(d.path,e.path,{recursive:!0}));await pN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=N(`skill-reconcile`),pPe=GF;function w9(){let e=[];for(let t of Rt){let n=kn[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Si,editor:null}),e}function mPe(e,t){let n=I(e,L(t));return ou(n)?L(t):n}function T9(e){let{frontmatter:t,body:n}=Za(e),r={};if(t!==``)try{let e=(0,oD.parse)(xo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function hPe(e,t){let n=T9(e),r=T9(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 E9(e,t){let n=D9(e),r=D9(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=F(e,o),c=F(t,o);if(i+=ku(s).size+ku(c).size,i>1048576)return!1;let l=B(s),u=B(c);if(!l.equals(u)&&(o!==`SKILL.md`||!hPe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of wu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(F(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){Us(t,{recursive:!0,force:!0}),zs(e,{recursive:!0}),Fs(mPe(e,n),t,`dir`)}function k9(e,t){try{let n=Tu(e);return L(ou(n)?n:L(P(e),n))===L(t)}catch{return!1}}function gPe(e,t){try{let n=Tu(e),r=ou(n)?L(n):L(P(e),n);if(!z(r))return!1;let i=I(L(t),r);return i!==``&&(i.startsWith(`..`)||ou(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const _Pe=[...Rt,`agents`];function vPe(e){for(let t of _Pe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function yPe(e){let{projectDir:t,skillsRoot:n}=e;if(!z(n))return;let r;try{r=wu(n)}catch{return}let i=w9();for(let e of r){let r=vPe(e);if(r===null)continue;let a=L(n,e),o=L(n,r);if(z(o))try{let n=vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!z(F(a,`SKILL.md`))||!z(F(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=L(t,n);if(RI(t,r))continue;let i=F(r,e);k9(i,a)&&O9(r,i,o)}Us(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function bPe(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 w9()){let o=L(t,e);if(!z(o)||RI(t,o))continue;let s;try{s=wu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(pPe.has(e))continue;let t=F(o,e),s=L(n,e),c=z(s);try{let l=vu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(gPe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Us(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!no.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=uN(t);for(let[r,a]of i){let i=L(n,r);if(!z(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await fN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??NI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{yPe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=RD(e);A9=new ic({currentPath:L(t,`tolerance-telemetry.jsonl`),previousPath:L(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),zt(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,N(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){zt(null),await A9?.drain(),A9=null,j9=!1}hs();const xPe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],SPe=[`cache`,`tmp`];function CPe(e){let t=L(e,ye);if(!(()=>{if(!z(t))return!0;try{return wu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of xPe)z(L(e,t))&&n.push(t);for(let t of SPe){let r=L(e,t);try{z(r)&&ku(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function wPe(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 F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function TPe(e){Xhe();let t=e.projectDir??e.contentDir,n=kye({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}`)}ec.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Xs({localSink:n?.telemetry}),N9(t),oPe(),sPe();let{kind:r,gitdir:i}=wPe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Vs(i));let o=Dye(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ds(`ok.boot`,{attributes:a},async()=>EPe(e)),l=()=>{if(s)try{let e=ps.extract(gs.active(),{traceparent:s});return gs.with(e,c)}catch(e){N(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function EPe(e){let t=e.skipAutoInit??!1,n=e.log??N(`boot`),r=e.serverRuntime??{...ea(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((za(r)||!co(i))&&!r.allowExternal)throw new SB(`refusing to start: the server would bind a non-loopback address (${(co(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=TB({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-DEUsqKAE.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=L(p,`.ok`);if(!z(L(m,`config.yml`)))throw new s8(z(m)?`config`:`okdir`,p);let h=L(m,`.gitignore`);z(h)||N(`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??tK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof QG||e instanceof $G){let t=e instanceof $G?e.detected:``,r=e instanceof $G?`too_old`:`not_available`;bK(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 Ys(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=CPe(m);_.length>0&&N(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ye}/.`);let v=d9({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,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=()=>`http://${te}:${re}`,D=e.ephemeral?void 0:e8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ie(),localApi:v.localApi,log:n}),O=c();O.headersTimeout=3e4,O.requestTimeout=6e4;let k=e.serveContentAssets===!1?void 0:wZ({contentFilter:v.contentFilter,contentSirv:LZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:be,assetExtensions:ne,blocklistExtensions:Ne,ingressPolicy:a}),ae=e.reactShellDistDir?LZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new JT({contentDir:e.contentDir,localDir:C,globalDir:L(Nu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ie(),getMcpStdioCommand:()=>qT(e.localOpCliArgs,re),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=a8({httpServer:O,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:D,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:k,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=HZ({httpServer:O,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],A=async()=>{await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(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 pe(O,e.port??0,fe??`127.0.0.1`)}catch(e){throw await A(),e}let me=O.address(),he=typeof me==`object`&&me?me.port:e.port??0,ge=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=O.headersTimeout,t.requestTimeout=O.requestTimeout;for(let e of O.listeners(`request`))t.on(`request`,e);for(let e of O.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:ge.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ge,O])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await A(),t}ge.push(t)}let _e=xL();_e!==void 0&&SL(`httpListenMs`,_e);let ve=O.address(),j=typeof ve==`object`&&ve?ve.port:e.port??0;re=j,d(C,j,ie());let M=!1,xe=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(M)return;M=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await xe(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of ge)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>ce.shutdown()),D!==void 0&&await t(`mcpHttpHandler.close`,()=>D.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),await t(`shutdownTelemetry`,()=>Ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>ec.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,cL(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 S9({projectDir:e,skillsRoot:L(e,`.ok`,`skills`),hostRoots:lPe,inPlaceNames:x9(e,lL(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 bPe({projectDir:p,skillsRoot:L(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:O,destroy:le,lockDir:C,contentDir:e.contentDir,port:j,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:LAe(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new zZ(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?F(e,`MERGE_HEAD`):null;if(!t||!z(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=uc({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=Dx(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 DPe=Ie;function OPe(e={}){let t=e.home??Nu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(F(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(F(r.APPDATA??F(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(rc(),1);const R9=F(Nu(),`.ok`,`logs`),kPe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function APe(){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 jPe(e){yu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function MPe(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 NPe(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(F(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(F(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(F(e,t.name)),a-=t.size}catch{}}}catch{}}function PPe(e){jPe(R9);let t=z9(),n=e.filePath??F(R9,`${e.name}.${t}.log`);MPe(n),(e._setTimeout??setTimeout)(()=>NPe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:APe(),name:e.name,redact:{paths:kPe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function FPe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.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 IPe(e){return F(R9,`${e}.${z9()}.log`)}function LPe(){return R9}function RPe(e){let t=L(e),n=0;for(;n<30;){let e=!1;try{e=z(L(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=P(t);if(r===t)return null;t=r,n+=1}return null}const B9=ed($l),V9=N(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function zPe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],RM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function BPe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],RM({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function VPe(e){let t=L(e,`packed-refs`);if(z(t))try{if(B(t,`utf-8`).split(`
2026
+ `))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`)}ee(!1),await M.flushDeferredStores(`discard-stale`),t=!0,ke?.emitBranchSwitched(i)}finally{ye.abortBranchSwitch(r),t||(ee(!1),await M.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&be.current&&t>0){let t=p??`.`;try{let n=await hx(be.current,t,e.oldHead,e.newHead,i);Nb(),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`),rn.push(`head-watcher`)}function l(e){for(let t of e)try{let e=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Dx(e),a=Ce.documents.get(i);if(!a)continue;let o=zt(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=MM(I(n,F(r,t)));if(e.startsWith(`..`))continue;let i=Ce.documents.get(Dx(e));i&&Vt(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=MF(r);b.debug({resetAmbientCredentials:f,originKind:AF(r).kind},`[sync] ambient credential-chain reset decision at boot`);let m=mc(h,{resetAmbient:f}),g=re();g.mode!==`off`&&b.info({mode:g.mode,source:g.source},`[sync] mode active at boot`);try{$t=new $Ne({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mcpTomlEditor:e.mcpTomlEditor,mode:g.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialConfig:m,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||M.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=be.current;n&&await _x(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=be.current;n&&await _x(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 ys({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:Ee(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 $t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),$t=null}Je(`files`),ye.announceReadyViews();let _=xL();_!==void 0&&SL(`readyMs`,_),oe()}return an().then(()=>{Qe=!0,He(),dt()},e=>{$e=!0,et.abort(),ct({status:`failed`,indexCount:0}),ye.close(),Ge(),Ue(e)}),{hocuspocus:Ce,durabilityState:x,sessionManager:we,nativeApi:Te,localApi:De,cc1Broadcaster:ke,agentFocusBroadcaster:je,agentPresenceBroadcaster:Me,maintenanceCoordinator:j,contentFilter:ge,basenameIndex:pe,serverInstanceId:ue,destroy:nn,ready:We,generatedIndexSweepReady:st,degraded:rn,lockDir:de,get syncEngine(){return $t},getLinkPreviewsEnabled:k,resolveEmbed:me,acpRegistry:fe,acpPermissions:A}}function f9(e){return e/1048576}function aPe(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:f9(e.rss),heapTotalMb:f9(e.heapTotal),heapUsedMb:f9(e.heapUsed),externalMb:f9(e.external),arrayBuffersMb:f9(e.arrayBuffers)}}}let p9=null,m9=null,h9=null;const g9=1e6;let _9=null,v9=null;Es(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function oPe(){if(p9)return;let e=Zs().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}=aPe();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`})}),p9=e}function sPe(){if(!m9){let e=Zs().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(!_9){_9=ene({resolution:20}),_9.enable();return}e.observe(_9.percentile(50)/g9,{stat:`p50`}),e.observe(_9.percentile(99)/g9,{stat:`p99`}),_9.reset()}),m9=e}if(!h9){let e=Zs().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=v9;if(v9={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`}))}),h9=e}}const y9=N(`skill-migrate`);function b9(e){return[{host:`agents`,root:Si},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=RE.indexOf(e.host),r=RE.indexOf(t.host);return(n===-1?RE.length:n)-(r===-1?RE.length:r)||e.host.localeCompare(t.host)})}const cPe=b9(kn),lPe=b9(Fn);function uPe(e,t){return z(L(e,st(t)))}function dPe(e,t){zs(P(t),{recursive:!0});try{Ms(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;Hs(e,t,{recursive:!0}),Us(e,{recursive:!0,force:!0})}}function fPe(e,t,n){let r=AI(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 x9(e,t){let n;try{n=V(L(e,`.ok`,`skills`))}catch{n=L(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!V(L(e,t.dir)).startsWith(n+R)}catch{return!0}}).map(e=>e.name))}async function S9(e){let{projectDir:t,skillsRoot:n}=e,r=e.inPlaceNames??new Set,i=e.hostRoots??cPe,a={migrated:[],skipped:[]};if(!z(n))return a;let o;try{o=wu(n)}catch{return a}let s=I(t,n).split(R).join(`/`),c=new Set;for(let[e,n]of Object.entries(nX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!no.test(e)||GF.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=L(n,e);if(!z(F(o,`SKILL.md`)))continue;let s=ME(o)?.contentHash;if(s===void 0)continue;let l=V(o),u=i.map(({host:n,root:r})=>{let i=L(t,r);return{host:n,root:r,path:F(i,e),escapes:RI(t,i),state:fPe(F(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=>uPe(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`?Us(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&Us(d.path,{recursive:!0,force:!0}),dPe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(Us(e.path,{recursive:!0,force:!0}),Hs(d.path,e.path,{recursive:!0}));await pN(t,e),a.migrated.push({name:e,to:`${d.root}/${e}`}),y9.info({skill:e,to:`${d.root}/${e}`},`migrated store skill in place`)}catch(t){a.skipped.push({name:e,reason:`error`}),y9.warn({err:t,skill:e},`store-skill migration skipped one entry after error`)}return a}const C9=N(`skill-reconcile`),pPe=GF;function w9(){let e=[];for(let t of Rt){let n=kn[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:Si,editor:null}),e}function mPe(e,t){let n=I(e,L(t));return ou(n)?L(t):n}function T9(e){let{frontmatter:t,body:n}=Za(e),r={};if(t!==``)try{let e=(0,oD.parse)(xo(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function hPe(e,t){let n=T9(e),r=T9(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 E9(e,t){let n=D9(e),r=D9(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=F(e,o),c=F(t,o);if(i+=ku(s).size+ku(c).size,i>1048576)return!1;let l=B(s),u=B(c);if(!l.equals(u)&&(o!==`SKILL.md`||!hPe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of wu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(F(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){Us(t,{recursive:!0,force:!0}),zs(e,{recursive:!0}),Fs(mPe(e,n),t,`dir`)}function k9(e,t){try{let n=Tu(e);return L(ou(n)?n:L(P(e),n))===L(t)}catch{return!1}}function gPe(e,t){try{let n=Tu(e),r=ou(n)?L(n):L(P(e),n);if(!z(r))return!1;let i=I(L(t),r);return i!==``&&(i.startsWith(`..`)||ou(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const _Pe=[...Rt,`agents`];function vPe(e){for(let t of _Pe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function yPe(e){let{projectDir:t,skillsRoot:n}=e;if(!z(n))return;let r;try{r=wu(n)}catch{return}let i=w9();for(let e of r){let r=vPe(e);if(r===null)continue;let a=L(n,e),o=L(n,r);if(z(o))try{let n=vu(a);if(n.isSymbolicLink()||!n.isDirectory()||!z(F(a,`SKILL.md`))||!z(F(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=L(t,n);if(RI(t,r))continue;let i=F(r,e);k9(i,a)&&O9(r,i,o)}Us(a,{recursive:!0,force:!0}),C9.info({base:r,suffixed:e},`collapsed accreted suffix-duplicate skill into its base`)}catch(t){C9.warn({err:t,base:r,suffixed:e},`suffix-dupe collapse skipped one entry after error`)}}}async function bPe(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 w9()){let o=L(t,e);if(!z(o)||RI(t,o))continue;let s;try{s=wu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(pPe.has(e))continue;let t=F(o,e),s=L(n,e),c=z(s);try{let l=vu(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(gPe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(Us(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!no.test(e)){C9.warn({skill:e,editor:i},`reconcile: skipping host-dir entry with a non-skill name`);continue}if(c&&E9(t,s)){O9(o,t,s),r.replaced.push({name:e,editor:i}),a(e,i);continue}r.skipped.push({name:e,editor:i})}catch(t){C9.warn({err:t,skill:e,editor:i},`reconcile skipped one skill entry after error`)}}}if(i.size>0){let e=uN(t);for(let[r,a]of i){let i=L(n,r);if(!z(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await fN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??NI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{yPe({projectDir:t,skillsRoot:n})}catch(e){C9.warn({err:e},`suffix-dupe collapse pass failed (non-fatal)`)}return r}let A9=null,j9=!1;function M9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function N9(e){if(!M9())return;let t=RD(e);A9=new ic({currentPath:L(t,`tolerance-telemetry.jsonl`),previousPath:L(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),zt(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};A9?.append(`${JSON.stringify(t)}\n`).catch(e=>{j9||(j9=!0,N(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){zt(null),await A9?.drain(),A9=null,j9=!1}hs();const xPe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],SPe=[`cache`,`tmp`];function CPe(e){let t=L(e,ye);if(!(()=>{if(!z(t))return!0;try{return wu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of xPe)z(L(e,t))&&n.push(t);for(let t of SPe){let r=L(e,t);try{z(r)&&ku(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function wPe(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 F9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function TPe(e){Xhe();let t=e.projectDir??e.contentDir,n=kye({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}`)}ec.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}Xs({localSink:n?.telemetry}),N9(t),oPe(),sPe();let{kind:r,gitdir:i}=wPe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Vs(i));let o=Dye(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Ds(`ok.boot`,{attributes:a},async()=>EPe(e)),l=()=>{if(s)try{let e=ps.extract(gs.active(),{traceparent:s});return gs.with(e,c)}catch(e){N(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function EPe(e){let t=e.skipAutoInit??!1,n=e.log??N(`boot`),r=e.serverRuntime??{...ea(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((za(r)||!co(i))&&!r.allowExternal)throw new SB(`refusing to start: the server would bind a non-loopback address (${(co(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=TB({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-BZi8m82Z.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=L(p,`.ok`);if(!z(L(m,`config.yml`)))throw new s8(z(m)?`config`:`okdir`,p);let h=L(m,`.gitignore`);z(h)||N(`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??tK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof QG||e instanceof $G){let t=e instanceof $G?e.detected:``,r=e instanceof $G?`too_old`:`not_available`;bK(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 Ys(),await Promise.race([P9(),new Promise(e=>setTimeout(e,F9))]),e}let _=CPe(m);_.length>0&&N(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ye}/.`);let v=d9({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,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee}=v,te=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),re=e.port??0,ie=()=>`http://${te}:${re}`,D=e.ephemeral?void 0:e8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>ie(),localApi:v.localApi,log:n}),O=c();O.headersTimeout=3e4,O.requestTimeout=6e4;let k=e.serveContentAssets===!1?void 0:wZ({contentFilter:v.contentFilter,contentSirv:LZ(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:be,assetExtensions:ne,blocklistExtensions:Ne,ingressPolicy:a}),ae=e.reactShellDistDir?LZ(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new JT({contentDir:e.contentDir,localDir:C,globalDir:L(Nu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:E,resolveEmbed:v.resolveEmbed,isExcludedPath:e=>v.contentFilter.isExcluded(e),isIgnoredPath:e=>v.contentFilter.isPathIgnored(e),getLoadedDocText:e=>y.documents.get(e)?.getText(`source`).toString()??null,getServerUrl:()=>ie(),getMcpStdioCommand:()=>qT(e.localOpCliArgs,re),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let ce=a8({httpServer:O,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:D,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:w,agentFocusBroadcaster:T,agentPresenceBroadcaster:E,maintenanceCoordinator:ee,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:k,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),le=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},ue=null;e.idleShutdownMs!==null&&(ue=HZ({httpServer:O,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await le()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let de=[...new Set(i)],fe=de[0],A=async()=>{await b().catch(e=>{n.warn({err:e},`destroyHocuspocus failed during listen-error cleanup`)}),u(C)},pe=(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 pe(O,e.port??0,fe??`127.0.0.1`)}catch(e){throw await A(),e}let me=O.address(),he=typeof me==`object`&&me?me.port:e.port??0,ge=[];for(let e of de.slice(1)){let t=c();t.headersTimeout=O.headersTimeout,t.requestTimeout=O.requestTimeout;for(let e of O.listeners(`request`))t.on(`request`,e);for(let e of O.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:ge.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...ge,O])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await A(),t}ge.push(t)}let _e=xL();_e!==void 0&&SL(`httpListenMs`,_e);let ve=O.address(),j=typeof ve==`object`&&ve?ve.port:e.port??0;re=j,d(C,j,ie());let M=!1,xe=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${F9}ms`))},F9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};le=async()=>{if(M)return;M=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await xe(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C)}catch(e){n.warn({err:e,step:`markServerLockDraining`},`bootServer destroy step failed`)}try{ue?.detach()}catch(t){e.push(t),n.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(oe!==null&&await t(`acpThreads.destroy`,()=>oe.destroy()),await t(`secondaryListeners.close`,async()=>{for(let e of ge)e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] secondary listener close failed during teardown`),t()})})}),await t(`mount.shutdown`,()=>ce.shutdown()),D!==void 0&&await t(`mcpHttpHandler.close`,()=>D.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{ce.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{O.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{O.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),await t(`shutdownTelemetry`,()=>Ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>ec.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:L(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,cL(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 S9({projectDir:e,skillsRoot:L(e,`.ok`,`skills`),hostRoots:lPe,inPlaceNames:x9(e,lL(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 bPe({projectDir:p,skillsRoot:L(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:O,destroy:le,lockDir:C,contentDir:e.contentDir,port:j,ready:x,generatedIndexSweepReady:v.generatedIndexSweepReady,degraded:S,didAutoInit:f,serverInstance:v,runtime:LAe(v,{contentDir:e.contentDir,projectDir:p}),acpThreadManager:oe}}async function I9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new zZ(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?F(e,`MERGE_HEAD`):null;if(!t||!z(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=uc({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=Dx(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 DPe=Ie;function OPe(e={}){let t=e.home??Nu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?z(F(t,`Library`,`Application Support`,`Claude`)):n===`win32`?z(F(r.APPDATA??F(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(rc(),1);const R9=F(Nu(),`.ok`,`logs`),kPe=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function APe(){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 jPe(e){yu(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function MPe(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 NPe(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(F(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(F(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(F(e,t.name)),a-=t.size}catch{}}}catch{}}function PPe(e){jPe(R9);let t=z9(),n=e.filePath??F(R9,`${e.name}.${t}.log`);MPe(n),(e._setTimeout??setTimeout)(()=>NPe(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:APe(),name:e.name,redact:{paths:kPe,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:L9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function FPe(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[L9.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 IPe(e){return F(R9,`${e}.${z9()}.log`)}function LPe(){return R9}function RPe(e){let t=L(e),n=0;for(;n<30;){let e=!1;try{e=z(L(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=P(t);if(r===t)return null;t=r,n+=1}return null}const B9=ed($l),V9=N(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function zPe(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],RM({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function BPe(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],RM({cwd:t,encoding:`utf-8`}));return n.trim().length>0}catch(e){return V9.warn({path:t,stderr:U9(e)},`could not list refs — assuming history exists and skipping the initial commit`),!0}}function VPe(e){let t=L(e,`packed-refs`);if(z(t))try{if(B(t,`utf-8`).split(`
2027
2027
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return wu(L(e,`refs/heads`)).length>0}catch{return!1}}function U9(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 W9(e,t){if(await BPe(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await zPe(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,RM({cwd:t,encoding:`utf-8`})),r||V9.info({path:t},`created initial commit with fallback identity (git identity unset)`)}catch(e){V9.warn({path:t,stderr:U9(e)},`could not create initial commit`)}}async function HPe(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],RM({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function UPe(e){let t=L(e);_W(t);let n=L(t,`.git`),r=L(n,`HEAD`),i=!1,a=!1;if(z(n)){if(!ku(n).isDirectory())return{didInit:!1};if(z(r)){if(VPe(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=tK()}catch(e){throw e instanceof QG||e instanceof $G?(bK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof $G?`too_old`:`not_available`,detectedVersion:e instanceof $G?e.detected:``},e instanceof $G?`git binary too old`:`git binary not found`)):V9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let s=o.resolvedPath;if(a)return await W9(s,t),{didInit:!1};if(!i&&await HPe(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],RM({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new H9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!z(r))throw new H9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,c);return await W9(s,t),i?(V9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(V9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=N(`project-skill-git`),K9=/^[0-9a-f]{40}$/,WPe=sn.map(e=>e.replace(/\/$/,``));async function GPe(e){let t=fd(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(YPe(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=dc(e,{credentialConfig:[]});if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await lc(async()=>{let t=await KPe(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await qPe(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=dc(e,{gitIndexFile:F(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 JPe(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await fB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;gc(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 \`${Tn}\` skill is regenerated per machine and version-stamped per app build, so tracking it causes recurring sync conflicts. It is now git-ignored.`,f=(await a.git.raw([`commit-tree`,o,`-p`,r,`-m`,d])).trim();if(!K9.test(f))return G9.warn({raw:f},`commit-tree returned invalid SHA — aborting untrack`),{kind:`failed`,error:`commit-tree returned invalid SHA`};try{await n.git.raw([`update-ref`,`refs/heads/${t}`,f,r])}catch(e){return G9.info({branch:t,err:J9(e)},`update-ref CAS failed — ref moved, retry next open`),{kind:`skipped`,reason:`ref-race`}}try{await n.git.raw([`reset`,`-q`,f,`--`,...i])}catch(e){G9.info({err:J9(e)},`real-index reset after untrack failed (cosmetic)`)}return G9.info({dirs:i,commitSha:f},`untracked project-skill projection`),{kind:`untracked`,dirs:i,commitSha:f}})}catch(e){return{kind:`failed`,error:J9(e)}}}async function q9(e){let t=[];for(let n of WPe){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function KPe(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 qPe(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function JPe(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function YPe(e){return z(F(e,`MERGE_HEAD`))||z(F(e,`rebase-merge`))||z(F(e,`rebase-apply`))||z(F(e,`CHERRY_PICK_HEAD`))||z(F(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function XPe(e,t){let n;try{n=Ql(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=P(n),r=0;r<32;r+=1){let n=F(t,`package.json`);if(z(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=P(t);if(r===t)return;t=r}}const ZPe=[{regex:/\/Users\/[^/]+\//g,replacement:`~/`},{regex:/\/home\/[^/]+\//g,replacement:`~/`},{regex:/C:\\\\Users\\\\[^\\\\]+\\\\/g,replacement:`~\\`},{regex:/C:\\Users\\[^\\]+\\/g,replacement:`~\\`}];function Y9(e){if(e===void 0)return;let t=e;for(let{regex:e,replacement:n}of ZPe)t=t.replace(e,n);return t}function X9(e,t=0,n=new WeakSet){if(t>=5)return{name:`SerializedError.CauseDepthExceeded`,message:`cause chain depth > 5; truncated`};if(typeof e==`object`&&e){if(n.has(e))return{name:`SerializedError.CauseCycle`,message:`cyclic cause; truncated`};n.add(e)}if(e instanceof Error)return{name:e.name,message:Y9(e.message)??``,stack:Y9(e.stack),code:e.code,cause:e.cause===void 0?void 0:X9(e.cause,t+1,n)};if(e==null)return{name:`UnknownError`,message:String(e)};if(typeof e==`string`)return{name:`StringError`,message:Y9(e)??e};if(typeof e==`object`){let r=e;return{name:String(r.name??`ObjectError`),message:Y9(String(r.message??``))??``,stack:Y9(r.stack),code:r.code,cause:r.cause===void 0?void 0:X9(r.cause,t+1,n)}}return{name:`UnknownError`,message:String(e)}}var Z9=class extends Error{constructor(e){super(`File not found: ${e}`),this.filePath=e,this.name=`SingleFileNotFoundError`}},Q9=class extends Error{constructor(e){super(`Not a file: ${e}. \`ok <file>\` opens a single markdown file.`),this.filePath=e,this.name=`SingleFileNotAFileError`}},$9=class extends Error{constructor(e){super(`OpenKnowledge edits markdown files (.md / .mdx): ${e}`),this.filePath=e,this.name=`SingleFileNotMarkdownError`}};function QPe(e){if(!Tx(e))throw new $9(e);let t;try{t=V(L(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ku(t).isFile())throw new Q9(e);let n=P(t),r=Xz(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Dx(I($Pe(e),t).split(R).join(`/`)),canonicalFilePath:t}}let i=ru(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Dx(i)}}function $Pe(e){return L(e,Ss({absPath:Rs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function eFe(e){let t=bu(L(Iu(),`ok-ephemeral-`)),n=L(t,`.ok`);return yu(n,{recursive:!0}),ju(L(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),ju(L(n,`.gitignore`),`local/
2028
2028
  `,`utf-8`),t}export{c2 as $,fx as $i,WR as $n,HM as $r,yK as $t,F7 as A,qT as Ai,EB as An,WP as Ar,eye as At,Y5 as B,CC as Bi,jz as Bn,yP as Br,IJ as Bt,d9 as C,Hd as Ca,zD as Ci,gW as Cn,qF as Cr,hye as Ct,I7 as D,Md as Da,lE as Di,bB as Dn,YF as Dr,WX as Dt,N7 as E,hd as Ea,uE as Ei,NB as En,Qme as Er,wZ as Et,VMe as F,rw as Fi,Yz as Fn,Npe as Fr,VJ as Ft,i8 as G,qx as Gi,qz as Gn,mpe as Gr,PJ as Gt,o8 as H,tS as Hi,Sz as Hn,gP as Hr,jJ as Ht,o7 as I,Ele as Ii,iz as In,SP as Ir,zJ as It,Z6 as J,zx as Ji,YR as Jn,XM as Jr,MJ as Jt,n8 as K,Rx as Ki,Oz as Kn,qM as Kr,NJ as Kt,a7 as L,Dle as Li,Az as Ln,wP as Lr,EJ as Lt,C7 as M,ow as Mi,hB as Mn,AP as Mr,xZ as Mt,b7 as N,KC as Ni,mB as Nn,jP as Nr,qX as Nt,j7 as O,pd as Oa,JT as Oi,OB as On,$me as Or,UX as Ot,i7 as P,tw as Pi,Xz as Pn,OP as Pr,Nge as Pt,r2 as Q,dx as Qi,GR as Qn,zM as Qr,SK as Qt,kMe as R,QC as Ri,dz as Rn,CP as Rr,Ege as Rt,P9 as S,Id as Sa,LD as Si,hW as Sn,eI as Sr,kZ as St,A7 as T,gd as Ta,dE as Ti,TB as Tn,WF as Tr,EZ as Tt,s8 as U,G as Ui,lz as Un,_P as Ur,Tge as Ut,K5 as V,WC as Vi,Dz as Vn,bP as Vr,AJ as Vt,a8 as W,eS as Wi,kz as Wn,WN as Wr,LJ as Wt,t2 as X,Lx as Xi,HR as Xn,YM as Xr,SJ as Xt,V6 as Y,Ux as Yi,XR as Yn,JM as Yr,xJ as Yt,n2 as Z,bx as Zi,UR as Zn,WM as Zr,wK as Zt,DPe as _,Xie as _a,AA as _i,OW as _n,iI as _r,NZ as _t,QPe as a,xx as aa,kj as ai,vK as an,OI as ar,tCe as at,N9 as b,nh as ba,OA as bi,mW as bn,tI as br,DZ as bt,GPe as c,_x as ca,Aj as ci,rK as cn,TI as cr,P0 as ct,RPe as d,nx as da,aj as di,UG as dn,xI as dr,M$ as dt,px as ea,RM as ei,bK as en,BR as er,pCe as et,PPe as f,Yb as fa,oj as fi,vW as fn,SI as fr,u$ as ft,OPe as g,$se as ga,jA as gi,jW as gn,yI as gr,HZ as gt,LPe as h,Rb as ha,PA as hi,SW as hn,phe as hr,O$ as ht,eFe as i,ux as ia,Pj as ii,tK as in,kI as ir,eCe as it,k7 as j,iw as ji,gB as jn,kP as jr,CZ as jt,P7 as k,ad as ka,zT as ki,kB as kn,jF as kr,$ve as kt,H9 as l,vx as la,Mj as li,qG as ln,CI as lr,I0 as lt,IPe as m,Gb as ma,NA as mi,DW as mn,_I as mr,T$ as mt,Z9 as n,hx as na,bM as ni,$G as nn,gR as nr,J0 as nt,X9 as o,ix as oa,Tj as oi,eK as on,Dhe as or,nCe as ot,FPe as p,qb as pa,vj as pi,EW as pn,vI as pr,ybe as pt,e8 as q,Wx as qi,sz as qn,KM as qr,FJ as qt,$9 as r,ox as ra,yM as ri,XG as rn,sR as rr,U0 as rt,XPe as s,yx as sa,Nj as si,sK as sn,xhe as sr,L0 as st,Q9 as t,cx as ta,PM as ti,QG as tn,jR as tr,Y0 as tt,UPe as u,Sx as ua,jj as ui,KG as un,bI as ur,n0 as ut,TPe as v,th as va,EA as vi,bW as vn,nI as vr,OZ as vt,u9 as w,Fd as wa,rD as wi,SB as wn,JF as wr,MZ as wt,M9 as x,Vd as xa,RD as xi,_W as xn,QF as xr,AZ as xt,I9 as y,rh as ya,kA as yi,kW as yn,rI as yr,jZ as yt,Q5 as z,SC as zi,uz as zn,xP as zr,wge as zt};
2029
- //# sourceMappingURL=src-3c-GN0Vv.mjs.map
2029
+ //# sourceMappingURL=src-CKvbaaFV.mjs.map