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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/dist/{acp-harness-probe-DvXLWBwm.mjs → acp-harness-probe-s3CqzCCO.mjs} +2 -2
  2. package/dist/cli.mjs +6 -6
  3. package/dist/config-schema.json +12 -3
  4. package/dist/config.project-local.schema.json +1 -1
  5. package/dist/config.project.schema.json +11 -2
  6. package/dist/constants-LXoEgYJe.mjs +2 -0
  7. package/dist/{fs-traced-DV9uD41t.mjs → fs-traced-CBFyXjv8.mjs} +2 -2
  8. package/dist/fs-traced-CChInc-O.mjs +1 -0
  9. package/dist/{git-handle-VuHcNtS4.mjs → git-handle-CjkVOyU7.mjs} +2 -2
  10. package/dist/git-handle-OIwLbjAT.mjs +1 -0
  11. package/dist/index.d.mts +1 -0
  12. package/dist/index.mjs +91 -91
  13. package/dist/{init-ja0T-etx.mjs → init-BSKAqmkk.mjs} +3 -3
  14. package/dist/init-D6zgpP-Z.mjs +1 -0
  15. package/dist/{launch-json-removal-DaMY_ELf.mjs → launch-json-removal-DS4Iihpf.mjs} +2 -2
  16. package/dist/{loader-CZJtDyW1.mjs → loader-BTTXRFLw.mjs} +2 -2
  17. package/dist/loader-CVvRSwYS.mjs +1 -0
  18. package/dist/md-manager-C2pyfP1M.mjs +2 -0
  19. package/dist/{open-browser-BfbWvPXH.mjs → open-browser-RpCPdtF_.mjs} +2 -2
  20. package/dist/parse-worker.mjs +1 -1
  21. package/dist/preview-CCsYKQw8.mjs +1 -0
  22. package/dist/{preview-DZFeEN5M.mjs → preview-DwoADdoO.mjs} +2 -2
  23. package/dist/public/assets/{ActivityModeContent-BMqdsZEQ.js → ActivityModeContent-BVNDha83.js} +1 -1
  24. package/dist/public/assets/{AgentDiffPane-D_ubtipg.js → AgentDiffPane-tc3vpwY_.js} +1 -1
  25. package/dist/public/assets/{AgentThreadClientBinder-B7pwGsKU.js → AgentThreadClientBinder-CSCbo226.js} +1 -1
  26. package/dist/public/assets/{ChangedOutsideBadge-4TgQdQOf.js → ChangedOutsideBadge-DrITuwxs.js} +1 -1
  27. package/dist/public/assets/{CodeMirrorPropInput-CjgqNZXo.js → CodeMirrorPropInput-CCoKlaSP.js} +1 -1
  28. package/dist/public/assets/{DocumentContext-tOm4SkOp.js → DocumentContext-BrnqRC7f.js} +1 -1
  29. package/dist/public/assets/{EditorModeToggle-CFFhQhHA.js → EditorModeToggle-tYJlAm15.js} +1 -1
  30. package/dist/public/assets/{EnableSyncConfirmDialog-BiThAkoH.js → EnableSyncConfirmDialog-BpR4lOGV.js} +1 -1
  31. package/dist/public/assets/FeedbackForm-B26S-tMj.js +1 -0
  32. package/dist/public/assets/{GraphPanel-CsRKre3D.js → GraphPanel-BBDNp1Lu.js} +1 -1
  33. package/dist/public/assets/{ImportSkillDialog-DcZoBHf-.js → ImportSkillDialog-BHURtwXV.js} +1 -1
  34. package/dist/public/assets/{LintConfigEditor--yFdaWpg.js → LintConfigEditor-B1_9NfyV.js} +1 -1
  35. package/dist/public/assets/ManagedArtifactProperties-BxCiEKqW.js +1 -0
  36. package/dist/public/assets/{ManagedArtifactProperties-CIVfnd15.js → ManagedArtifactProperties-XetEd70v.js} +1 -1
  37. package/dist/public/assets/{McpConsentDialogBody-DEhSeOSg.js → McpConsentDialogBody-BMcFiOpb.js} +1 -1
  38. package/dist/public/assets/{MermaidDocEditor-civq6mkL.js → MermaidDocEditor-2uKE8dRs.js} +1 -1
  39. package/dist/public/assets/{ReportBugDialogBody-DO7eotFd.js → ReportBugDialogBody-CokSHlbL.js} +1 -1
  40. package/dist/public/assets/{SchemaConfigEditor-NxaI-Jdd.js → SchemaConfigEditor-m3x_uxwj.js} +1 -1
  41. package/dist/public/assets/{SessionsHost-PjSsebux.js → SessionsHost-BwjsJ4kM.js} +2 -2
  42. package/dist/public/assets/{SettingsDialogBody-BNYz-D4X.js → SettingsDialogBody-NnXMegDb.js} +1 -1
  43. package/dist/public/assets/{ShareBranchSwitchDialog-B7Bl6qR0.js → ShareBranchSwitchDialog-DGpxR8rv.js} +1 -1
  44. package/dist/public/assets/{ShareReceiveDialog-BmMkjWTr.js → ShareReceiveDialog-DmLaRlCo.js} +1 -1
  45. package/dist/public/assets/{ShareReceiveMissDialog-R20sy2ia.js → ShareReceiveMissDialog-eWc73H2u.js} +1 -1
  46. package/dist/public/assets/{SkillEditBanner-B2U7UdOB.js → SkillEditBanner-Bcj_SsXK.js} +1 -1
  47. package/dist/public/assets/{SkillOriginInline-B3wOLT3t.js → SkillOriginInline-D59WrmB9.js} +1 -1
  48. package/dist/public/assets/{SkillToolbarControls-B_RJpm5V.js → SkillToolbarControls-CF4GI3N4.js} +1 -1
  49. package/dist/public/assets/{SlidesToolbarControls-56-P71vE.js → SlidesToolbarControls-pic8RAQO.js} +1 -1
  50. package/dist/public/assets/{SourceEditor-BW7yuIvG.js → SourceEditor-D4_TDrJh.js} +1 -1
  51. package/dist/public/assets/{TerminalPanel-Clr6j-jo.js → TerminalPanel-XbiaeXBm.js} +1 -1
  52. package/dist/public/assets/{TerminalWindowApp-DRbYHuvS.js → TerminalWindowApp-ptqnI_mm.js} +1 -1
  53. package/dist/public/assets/{TextDocEditor-Bwwrrcn5.js → TextDocEditor-BjbQZtTc.js} +1 -1
  54. package/dist/public/assets/{ThreadView-BA7gxPI6.js → ThreadView-CdeJaSQw.js} +1 -1
  55. package/dist/public/assets/{TimelineDiffPane-CTJnk9me.js → TimelineDiffPane-BbiOEtH2.js} +1 -1
  56. package/dist/public/assets/{agent-diff-store-BvxTke2d.js → agent-diff-store-BDOTYRUw.js} +1 -1
  57. package/dist/public/assets/{auth-state-cache-DrAhOPTB.js → auth-state-cache-BvGXSOYb.js} +1 -1
  58. package/dist/public/assets/client-version-vFgto74n.js +1 -0
  59. package/dist/public/assets/{comment-chips-W2ozPSpm.js → comment-chips-DBaYF7lS.js} +1 -1
  60. package/dist/public/assets/{config-provider-DamFbxl8.js → config-provider-C5Tk3I1Q.js} +1 -1
  61. package/dist/public/assets/{dist-ILlrHFKs.js → dist-C27Q9mDy.js} +82 -82
  62. package/dist/public/assets/{doc-paths-DAh95jxf.js → doc-paths-BVBn68AJ.js} +1 -1
  63. package/dist/public/assets/{documents-events-CCW6R-r2.js → documents-events-BsVKB80J.js} +1 -1
  64. package/dist/public/assets/{file-tree-adapter-Bf1ZqkPA.js → file-tree-adapter-BnVxsS3Y.js} +1 -1
  65. package/dist/public/assets/{file-tree-utils-CgJ4lrP9.js → file-tree-utils-Bo6aWobj.js} +1 -1
  66. package/dist/public/assets/{folder-config-api-CKV5STj1.js → folder-config-api-BKVZKM0Y.js} +1 -1
  67. package/dist/public/assets/{follow-file-D0HdtSlc.js → follow-file-DqzQHgKU.js} +1 -1
  68. package/dist/public/assets/i18n-DdNV3ihn.js +1 -0
  69. package/dist/public/assets/{index-qtxLhYJO.js → index-MDvvCb3N.js} +7 -7
  70. package/dist/public/assets/{lint-config-client-xawAT1mQ.js → lint-config-client-kEetoezQ.js} +1 -1
  71. package/dist/public/assets/{markdownlint-rule-browser-B3UPVPG_.js → markdownlint-rule-browser-Chpu90_w.js} +1 -1
  72. package/dist/public/assets/{navigation-targets-C1boWExT.js → navigation-targets-BZG2mu1V.js} +1 -1
  73. package/dist/public/assets/{open-managed-artifact-tab-G7xdjHph.js → open-managed-artifact-tab-b7h2CbkR.js} +1 -1
  74. package/dist/public/assets/{pending-receive-nav-store-CpVItLnx.js → pending-receive-nav-store-Clqxh2Fp.js} +1 -1
  75. package/dist/public/assets/{prop-types-BIrEWnOv.js → prop-types-CxA_rPl_.js} +1 -1
  76. package/dist/public/assets/{receive-store-BrOspwat.js → receive-store-DjapXAoN.js} +1 -1
  77. package/dist/public/assets/{selection-context-nm7zlSXJ.js → selection-context-C32Stxol.js} +1 -1
  78. package/dist/public/assets/{skill-actions-e3PRoOA3.js → skill-actions-5PfZ_o96.js} +1 -1
  79. package/dist/public/assets/{skill-scope-8PP6d5Gw.js → skill-scope-D6RlM0oa.js} +1 -1
  80. package/dist/public/assets/{skills-api-DQ0PK-8O.js → skills-api-Cdab4eC0.js} +1 -1
  81. package/dist/public/assets/{src-BKQkpwCc.js → src-Bfy3jrQ_.js} +1 -1
  82. package/dist/public/assets/{tag-pill-input-BHj2SAnj.js → tag-pill-input-Bcisv-E4.js} +1 -1
  83. package/dist/public/assets/{target-navigation-intent-DpIU3fe6.js → target-navigation-intent-AcMTl0tC.js} +1 -1
  84. package/dist/public/assets/{telemetry-impl-Byic_ID0.js → telemetry-impl-CQnpJy_e.js} +1 -1
  85. package/dist/public/assets/{telemetry-startup-D_ttbNLC.js → telemetry-startup-D9BKJrQj.js} +1 -1
  86. package/dist/public/assets/{terminal-cli-display-CgJpdKCI.js → terminal-cli-display-Co0kpfr2.js} +1 -1
  87. package/dist/public/assets/{terminal-launch-events-DQ0KtteM.js → terminal-launch-events-BYyc92EH.js} +1 -1
  88. package/dist/public/assets/{terminal-telemetry-CE1yzjKD.js → terminal-telemetry-C-cKlmwu.js} +1 -1
  89. package/dist/public/assets/{typing-burst-detector-B6UhFT8T.js → typing-burst-detector-B5Vy4mIn.js} +1 -1
  90. package/dist/public/assets/{uninstall-BE8yLKij.js → uninstall-GQMfCPpu.js} +1 -1
  91. package/dist/public/assets/{use-activity-panel-CF6Guvjl.js → use-activity-panel-jeOH8Waq.js} +1 -1
  92. package/dist/public/assets/{use-apply-config-color-theme-BatIDUX7.js → use-apply-config-color-theme-BApSgC_I.js} +1 -1
  93. package/dist/public/assets/{use-collab-url-7XE2_0_k.js → use-collab-url-bZfgDsoc.js} +1 -1
  94. package/dist/public/assets/{use-live-xterm-theme-DS89T4Os.js → use-live-xterm-theme-BplIi05T.js} +1 -1
  95. package/dist/public/assets/{use-open-skill-CtzMj-sg.js → use-open-skill-DXlvLAoL.js} +1 -1
  96. package/dist/public/assets/{use-popular-skills-BY0ulPzk.js → use-popular-skills-CfUTYkxE.js} +1 -1
  97. package/dist/public/assets/{use-settings-route-DN0TWdfX.js → use-settings-route-Di4sAvRi.js} +1 -1
  98. package/dist/public/assets/{use-skill-origin-COh1_mOK.js → use-skill-origin-B_Rm_rN6.js} +1 -1
  99. package/dist/public/assets/{use-skills-C_HuRxth.js → use-skills-D1P4d0d_.js} +1 -1
  100. package/dist/public/assets/{use-terminal-enabled-CIQB6jgW.js → use-terminal-enabled-D26F4OF8.js} +1 -1
  101. package/dist/public/assets/{use-timeline-entry-diff-CDFU16yg.js → use-timeline-entry-diff-DjaTQJZU.js} +1 -1
  102. package/dist/public/assets/{use-workspace-CNCW4CS8.js → use-workspace-CyUAn3C0.js} +1 -1
  103. package/dist/public/index.html +44 -44
  104. package/dist/public/uninstall.html +3 -3
  105. package/dist/{repair-launch-json-D0g7JIQF.mjs → repair-launch-json-6ZgSt8VQ.mjs} +2 -2
  106. package/dist/{repair-mcp-configs-hbX7fywV.mjs → repair-mcp-configs-BX-Egvbf.mjs} +2 -2
  107. package/dist/repair-skills-BVA056EW.mjs +1 -0
  108. package/dist/{repair-skills-BVCJQr-D.mjs → repair-skills-CnWUwwGE.mjs} +2 -2
  109. package/dist/schemas/v0/config.project-local.schema.json +1 -1
  110. package/dist/schemas/v0/config.project.schema.json +11 -2
  111. package/dist/{server-lock-CeKMy65H.mjs → server-lock-B8gC6O_D.mjs} +2 -2
  112. package/dist/server-lock-BgDwOXHz.mjs +1 -0
  113. package/dist/{skill-teardown-CybJJo-5.mjs → skill-teardown-Bz8I6Qtp.mjs} +2 -2
  114. package/dist/{sleep-A0G7hOuG.mjs → sleep-C7muMiHm.mjs} +2 -2
  115. package/dist/{src-DNgZpbWL.mjs → src-1_fSbfZs.mjs} +2 -2
  116. package/dist/{src-3gxGmFyn.mjs → src-B6lC36UX.mjs} +1 -1
  117. package/dist/{src-Dj6UxpKM.mjs → src-BqZfalMj.mjs} +21 -21
  118. package/dist/src-C5VWLO7S.mjs +1 -0
  119. package/dist/{src--OhnhRml.mjs → src-CPA_Jv5y.mjs} +10 -10
  120. package/dist/start-BBU8Sqd0.mjs +1 -0
  121. package/dist/start-CTIu5W77.mjs +12 -0
  122. package/dist/{ui-DXs7IMUP.mjs → ui-CaE3cWnk.mjs} +3 -3
  123. package/dist/{write-project-skill-B4M4CzQe.mjs → write-project-skill-lYT2q0EM.mjs} +2 -2
  124. package/package.json +5 -5
  125. package/dist/constants-GVvlP0F1.mjs +0 -2
  126. package/dist/fs-traced-DtlsFK7O.mjs +0 -1
  127. package/dist/git-handle-CEoe8TIl.mjs +0 -1
  128. package/dist/init-CXnCnSQu.mjs +0 -1
  129. package/dist/loader-zzsiCoMM.mjs +0 -1
  130. package/dist/md-manager-45eVlaBq.mjs +0 -2
  131. package/dist/preview-BqJFFDSI.mjs +0 -1
  132. package/dist/public/assets/FeedbackForm-tTwFtkKO.js +0 -1
  133. package/dist/public/assets/ManagedArtifactProperties-Bb9ghWb1.js +0 -1
  134. package/dist/public/assets/client-version-DFQNNQh_.js +0 -1
  135. package/dist/public/assets/i18n-CUKvPzxt.js +0 -1
  136. package/dist/repair-skills-BmAntgZP.mjs +0 -1
  137. package/dist/server-lock-CDm0H6LS.mjs +0 -1
  138. package/dist/src-BqNFscyh.mjs +0 -1
  139. package/dist/start-DYelgMjm.mjs +0 -1
  140. package/dist/start-xJV4Y-0A.mjs +0 -12
@@ -1,7 +1,7 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt as a,C as o,Ct as s,Et as c,F as l,Ft as u,Gt as d,I as f,It as p,Jt as m,Kt as h,L as g,Lt as _,Mt as v,N as y,Nt as b,Ot as x,P as S,Pt as C,Q as w,Qt as T,R as E,Rt as ee,S as te,St as D,T as O,Tt as k,U as A,V as ne,Vt as re,Wt as ie,Xt as ae,Yt as oe,Zt as se,_t as j,a as ce,at as le,dt as ue,en as de,f as fe,ft as pe,h as me,ht as he,i as ge,it as _e,j as M,jt as N,kt as ve,lt as ye,m as be,mt as xe,o as Se,ot as Ce,qt as we,s as Te,st as Ee,t as De,tn as Oe,tt as ke,ut as Ae,vt as je,w as Me,wt as Ne,x as Pe,xt as P,yt as Fe,z as Ie,zt as Le}from"./sleep-A0G7hOuG.mjs";import{$ as Re,$a as ze,$i as Be,$n as Ve,$o as He,$r as Ue,$t as We,A as Ge,Aa as Ke,Ai as qe,An as Je,Ao as Ye,Ar as Xe,As as Ze,At as Qe,B as $e,Ba as et,Bi as tt,Bn as nt,Br as rt,Bs as it,C as at,Ca as ot,Ci as st,Cn as ct,Co as lt,Cr as ut,Cs as dt,Ct as ft,D as pt,Da as mt,Di as ht,Dn as gt,Do as _t,Dr as vt,Dt as yt,E as bt,Ea as xt,Ei as St,En as Ct,Eo as wt,Er as Tt,Es as Et,Et as Dt,F as Ot,Fa as kt,Fi as At,Fn as eee,Fo as jt,Fr as tee,Fs as Mt,Ft as Nt,G as Pt,Ga as Ft,Gi as It,Gn as Lt,Go as Rt,Gr as zt,Gt as Bt,H as Vt,Ha as Ht,Hi as Ut,Hn as nee,Ho as Wt,Hr as ree,Hs as Gt,Ht as Kt,I as qt,Ia as Jt,Ii as Yt,In as iee,Io as Xt,Ir as Zt,Is as aee,It as Qt,J as $t,Ja as en,Ji as tn,Jn as nn,Jo as rn,Jr as an,Jt as on,K as sn,Ki as cn,Kn as oee,Ko as ln,Kr as see,Kt as un,L as dn,La as fn,Li as pn,Ln as cee,Lr as mn,Ls as hn,Lt as lee,M as gn,Ma as uee,Mi as dee,Mn as fee,Mr as _n,Ms as vn,Mt as yn,N as bn,Na as xn,Ni as Sn,Nn as Cn,No as wn,Nr as pee,Ns as Tn,Nt as En,O as Dn,Oa as On,Oi as kn,On as mee,Oo as An,Or as hee,Os as jn,Ot as Mn,P as gee,Pa as Nn,Pi as Pn,Pn as _ee,Po as Fn,Pr as vee,Ps as In,Pt as Ln,Q as Rn,Qa as zn,Qi as Bn,Qn as Vn,Qo as Hn,Qr as Un,Qt as Wn,R as Gn,Ra as Kn,Ri as qn,Rn as Jn,Ro as Yn,Rr as Xn,Rs as Zn,Rt as Qn,S as $n,Sa as er,Si as tr,Sn as yee,So as bee,Sr as xee,Ss as nr,St as rr,T as ir,Ta as See,Ti as ar,Tn as or,Tr as Cee,Ts as sr,Tt as cr,Ua as lr,Ui as ur,Un as dr,Ur as wee,Us as fr,Ut as pr,V as mr,Va as hr,Vi as gr,Vn as _r,Vo as vr,Vr as Tee,W as yr,Wa as br,Wi as Eee,Wn as Dee,Wo as xr,Wr as Oee,Ws as Sr,Wt as Cr,X as wr,Xa as Tr,Xi as Er,Xn as Dr,Xo as Or,Xr as kr,Xs as Ar,Xt as jr,Y as Mr,Ya as Nr,Yi as Pr,Yn as Fr,Yr as Ir,Ys as Lr,Yt as Rr,Z as zr,Za as Br,Zi as Vr,Zn as Hr,Zo as Ur,Zr as Wr,Zs as Gr,Zt as Kr,_ as qr,_a as kee,_i as Jr,_n as Aee,_o as Yr,_r as Xr,_s as Zr,_t as Qr,a as $r,aa as ei,ai as ti,an as ni,ao as ri,ar as jee,as as ii,at as ai,b as oi,ba as Mee,bi as si,bn as Nee,bo as ci,br as Pee,bs as li,bt as ui,c as di,ca as Fee,ci as Iee,cn as Lee,co as Ree,cr as fi,ct as pi,d as mi,da as hi,di as gi,dn as zee,do as Bee,dr as Vee,ds as _i,dt as vi,ea as yi,ec as bi,ei as xi,en as Si,eo as Ci,er as wi,es as Ti,et as Ei,f as Di,fa as Oi,fi as ki,fn as Ai,fo as ji,fr as Mi,fs as Ni,ft as Pi,g as Fi,ga as Ii,gi as Li,gn as Ri,go as zi,gr as Bi,gs as Vi,gt as Hi,h as Ui,ha as Wi,hi as Gi,hn as Ki,ho as qi,hr as Ji,hs as Yi,ht as Xi,i as Zi,ia as Qi,ii as $i,in as ea,io as ta,ir as na,it as ra,j as ia,ja as aa,ji as oa,jn as sa,jr as ca,js as la,jt as ua,k as da,ka as fa,ki as pa,kn as ma,kr as ha,ks as ga,kt as _a,l as va,la as Hee,li as Uee,ln as Wee,lo as Gee,lr as Kee,ls as ya,lt as ba,m as xa,ma as qee,mi as Jee,mn as Yee,mo as Xee,mr as Zee,ms as Sa,mt as Ca,n as wa,na as Ta,ni as Qee,nn as Ea,no as $ee,nr as ete,ns as Da,o as Oa,oa as ka,oi as Aa,on as tte,oo as nte,or as rte,os as ja,ot as Ma,p as Na,pa as ite,pi as ate,pn as ote,po as ste,pr as cte,ps as Pa,pt as Fa,q as Ia,qa as La,qi as Ra,qn as lte,qo as za,qr as Ba,qt as Va,r as Ha,ra as Ua,ri as ute,rn as Wa,ro as dte,rr as fte,rs as Ga,rt as Ka,s as qa,sa as Ja,si as pte,sn as mte,so as Ya,sr as Xa,ss as Za,st as Qa,t as $a,ta as eo,ti as hte,tn as gte,tr as _te,u as to,ua as vte,ui as no,un as yte,uo as ro,ur as bte,us as io,ut as ao,v as oo,va as so,vi as co,vn as lo,vo as xte,vr as Ste,vs as uo,vt as fo,w as po,wa as Cte,wi as wte,wn as mo,wo as ho,wr as Tte,ws as go,wt as _o,x as vo,xa as Ete,xi as Dte,xn as Ote,xo as kte,xr as Ate,xs as yo,xt as bo,y as xo,ya as So,yi as Co,yn as wo,yo as To,yr as Eo,yt as Do,z as Oo,za as ko,zi as Ao,zn as jo,zo as Mo,zr as No,zs as Po,zt as Fo}from"./src-Dj6UxpKM.mjs";import{c as Io,i as Lo,l as Ro,n as zo,s as Bo}from"./esm-DxvI2ZVA.mjs";import{n as Vo,t as Ho}from"./md-manager-45eVlaBq.mjs";import{A as Uo,C as Wo,E as Go,I as Ko,M as qo,O as Jo,P as Yo,S as Xo,T as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-DV9uD41t.mjs";import{D as Ss,E as Cs,S as ws,T as Ts,a as Es,b as Ds,l as Os,p as ks,r as F,s as As,x as js,y as Ms}from"./logger-DFxEUjvj.mjs";import{a as Ns,i as Ps,o as Fs,r as Is,s as Ls,t as Rs}from"./git-handle-VuHcNtS4.mjs";import{C as zs,S as Bs,_ as Vs,a as Hs,b as Us,c as Ws,f as Gs,g as Ks,h as qs,i as Js,l as Ys,n as Xs,p as Zs,r as Qs,u as $s,x as ec}from"./server-lock-CeKMy65H.mjs";import{t as tc}from"./libesm-DzwC_yFw.mjs";import{t as nc}from"./yazl-DZr4PyKA.mjs";import{n as rc,t as ic}from"./build-CJW5ggp6.mjs";import{t as ac}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as oc,c as sc,d as cc,f as lc,h as uc,i as dc,l as fc,m as pc,n as mc,o as hc,p as gc,r as _c,s as vc,t as yc,u as bc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as xc,B as Sc,C as Cc,D as wc,E as Tc,F as Ec,H as Dc,I as Oc,L as kc,M as Ac,N as jc,O as Mc,P as Nc,S as Pc,T as Fc,V as Ic,_ as Lc,a as Rc,b as zc,c as Bc,d as Vc,f as Hc,g as Uc,h as Wc,i as Gc,j as Kc,k as qc,l as Jc,m as Yc,n as Xc,o as Zc,p as Qc,r as $c,s as el,t as tl,u as nl,v as rl,w as il,x as al,y as ol,z as sl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as cl,c as ll,d as ul,i as dl,l as fl,n as jte,o as Mte,r as Nte,s as pl,t as Pte,u as ml}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as hl,r as gl,t as _l}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as vl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as yl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as bl,t as xl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Fte,t as Sl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cl,r as wl,t as Tl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ite,t as El}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Dl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Ol}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Lte}from"./wrapper-BcpqREsI.mjs";import{createRequire as kl}from"node:module";import{execFile as Al,execFileSync as Rte,spawn as jl,spawnSync as Ml}from"node:child_process";import*as Nl from"node:path";import{basename as Pl,delimiter as Fl,dirname as I,extname as Il,isAbsolute as Ll,join as L,normalize as Rl,parse as zl,posix as Bl,relative as R,resolve as z,sep as Vl,win32 as zte}from"node:path";import{URLSearchParams as Bte,fileURLToPath as Hl,pathToFileURL as Vte}from"node:url";import*as Ul from"node:fs";import{appendFileSync as Hte,chmodSync as Wl,closeSync as Gl,constants as Kl,createReadStream as ql,createWriteStream as Jl,existsSync as B,fstatSync as Ute,lstatSync as Yl,mkdirSync as Xl,mkdtempSync as Zl,openSync as Ql,opendirSync as $l,readFile as Wte,readFileSync as V,readSync as eu,readdirSync as tu,readlinkSync as nu,realpathSync as H,renameSync as ru,rmSync as iu,rmdirSync as au,statSync as ou,unlinkSync as su,writeFileSync as cu,writeSync as Gte}from"node:fs";import{arch as lu,availableParallelism as Kte,homedir as uu,hostname as du,platform as fu,tmpdir as pu}from"node:os";import{access as mu,chmod as qte,constants as hu,lstat as gu,readFile as _u,readdir as vu,realpath as yu,stat as bu,writeFile as Jte}from"node:fs/promises";import{Readable as xu,Transform as Yte,Writable as Xte}from"node:stream";import Su,{createHash as Cu,randomUUID as wu,webcrypto as Tu}from"node:crypto";import Zte from"crypto";import{Readable as Eu}from"stream";import{EventEmitter as Qte}from"node:events";import{Worker as $te}from"node:worker_threads";import{monitorEventLoopDelay as ene,performance as Du}from"node:perf_hooks";import{createInterface as tne}from"node:readline";import{pipeline as Ou}from"node:stream/promises";import{setImmediate as nne,setTimeout as ku}from"node:timers/promises";import{promisify as Au}from"node:util";import{request as rne}from"node:http";import{Http2ServerRequest as ju,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{Http2ServerRequest as Mu,constants as une}from"http2";import{AsyncLocalStorage as dne}from"node:async_hooks";import{lookup as fne}from"node:dns";import pne from"node:tls";function mne(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),hne(n)}function hne(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Nu=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=V(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Ll(t)?t:z(this.gitDir,t))}catch(e){if(!zu(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=V(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return zu(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]}:Hu(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=V(L(t.path,`config`),`utf-8`)}catch(e){return zu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=gne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Bu(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=z(t.path,e),r=R(t.path,n);if(r.startsWith(`..`)||Ll(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Vu(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!zu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return zu(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 Hu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Pu(e){return Iu(z(e),``)}function Fu(e){let t=z(e),n=z(uu());if(t===n)return{kind:`absent`};let r=Iu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=I(i);if(e===i||e===n)return{kind:`absent`};let r=Iu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Iu(e,t){let n=L(e,`.git`),r;try{r=ou(n)}catch(e){return zu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Nu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=V(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=Ll(o)?o:z(e,o);try{if(!ou(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 Nu(`linked`,e,t,n,s)}}function gne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Lu(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=Ru(i[1]);if(a.length>0)return a}return null}function Lu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Ru(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function zu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Bu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Vu(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Bu(t[1])?{kind:`symbolic`,target:t[1]}:null:Hu(e)?{kind:`oid`,oid:e}:null}function Hu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Uu(e){return`git-author-${_a(e.trim().toLowerCase())}`}const Wu=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Gu(e){let t=Fu(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 Ku(e){let t=Gu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function qu(e){let t=Gu(e);switch(t.kind){case`directory`:return z(t.path,Ju(t.projectSubPath));case`linked`:if(!B(t.path))throw new Yu(t.gitPath,t.path);return z(t.path,Ju(t.projectSubPath));case`malformed-pointer`:throw new Yu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Xu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Ju(e){return e===``?`ok`:`ok-${_ne(e)}`}function _ne(e){let t=e.split(Vl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=vne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function vne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Yu=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}},Xu=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 yne(e){let t;try{t=qu(e)}catch(e){if(e instanceof Yu||e instanceof Xu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Zu(e){return`refs/wip/${e}/`}function bne(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,At as i,Bt as a,C as o,Ct as s,Et as c,F as l,Ft as u,Gt as d,I as f,It as p,Jt as m,Kt as h,L as g,Lt as _,Mt as v,N as y,Nt as b,Ot as x,P as S,Pt as C,Q as w,Qt as T,R as E,Rt as ee,S as te,St as D,T as O,Tt as k,U as A,V as ne,Vt as re,Wt as ie,Xt as ae,Yt as oe,Zt as se,_t as j,a as ce,at as le,dt as ue,en as de,f as fe,ft as pe,h as me,ht as he,i as ge,it as _e,j as M,jt as N,kt as ve,lt as ye,m as be,mt as xe,o as Se,ot as Ce,qt as we,s as Te,st as Ee,t as De,tn as Oe,tt as ke,ut as Ae,vt as je,w as Me,wt as Ne,x as Pe,xt as P,yt as Fe,z as Ie,zt as Le}from"./sleep-C7muMiHm.mjs";import{$ as Re,$a as ze,$i as Be,$n as Ve,$o as He,$r as Ue,$t as We,A as Ge,Aa as Ke,Ai as qe,An as Je,Ao as Ye,Ar as Xe,As as Ze,At as Qe,B as $e,Ba as et,Bi as tt,Bn as nt,Br as rt,Bs as it,C as at,Ca as ot,Ci as st,Cn as ct,Co as lt,Cr as ut,Cs as dt,Ct as ft,D as pt,Da as mt,Di as ht,Dn as gt,Do as _t,Dr as vt,Dt as yt,E as bt,Ea as xt,Ei as St,En as Ct,Eo as wt,Er as Tt,Es as Et,Et as Dt,F as Ot,Fa as kt,Fi as At,Fn as eee,Fo as jt,Fr as tee,Fs as Mt,Ft as Nt,G as Pt,Ga as Ft,Gi as It,Gn as Lt,Go as Rt,Gr as zt,Gt as Bt,H as Vt,Ha as Ht,Hi as Ut,Hn as nee,Ho as Wt,Hr as ree,Hs as Gt,Ht as Kt,I as qt,Ia as Jt,Ii as Yt,In as iee,Io as Xt,Ir as Zt,Is as aee,It as Qt,J as $t,Ja as en,Ji as tn,Jn as nn,Jo as rn,Jr as an,Jt as on,K as sn,Ki as cn,Kn as oee,Ko as ln,Kr as see,Kt as un,L as dn,La as fn,Li as pn,Ln as cee,Lr as mn,Ls as hn,Lt as lee,M as gn,Ma as uee,Mi as dee,Mn as fee,Mr as _n,Ms as vn,Mt as yn,N as bn,Na as xn,Ni as Sn,Nn as Cn,No as wn,Nr as pee,Ns as Tn,Nt as En,O as Dn,Oa as On,Oi as kn,On as mee,Oo as An,Or as hee,Os as jn,Ot as Mn,P as gee,Pa as Nn,Pi as Pn,Pn as _ee,Po as Fn,Pr as vee,Ps as In,Pt as Ln,Q as Rn,Qa as zn,Qi as Bn,Qn as Vn,Qo as Hn,Qr as Un,Qt as Wn,R as Gn,Ra as Kn,Ri as qn,Rn as Jn,Ro as Yn,Rr as Xn,Rs as Zn,Rt as Qn,S as $n,Sa as er,Si as tr,Sn as yee,So as bee,Sr as xee,Ss as nr,St as rr,T as ir,Ta as See,Ti as ar,Tn as or,Tr as Cee,Ts as sr,Tt as cr,Ua as lr,Ui as ur,Un as dr,Ur as wee,Us as fr,Ut as pr,V as mr,Va as hr,Vi as gr,Vn as _r,Vo as vr,Vr as Tee,W as yr,Wa as br,Wi as Eee,Wn as Dee,Wo as xr,Wr as Oee,Ws as Sr,Wt as Cr,X as wr,Xa as Tr,Xi as Er,Xn as Dr,Xo as Or,Xr as kr,Xs as Ar,Xt as jr,Y as Mr,Ya as Nr,Yi as Pr,Yn as Fr,Yr as Ir,Ys as Lr,Yt as Rr,Z as zr,Za as Br,Zi as Vr,Zn as Hr,Zo as Ur,Zr as Wr,Zs as Gr,Zt as Kr,_ as qr,_a as kee,_i as Jr,_n as Aee,_o as Yr,_r as Xr,_s as Zr,_t as Qr,a as $r,aa as ei,ai as ti,an as ni,ao as ri,ar as jee,as as ii,at as ai,b as oi,ba as Mee,bi as si,bn as Nee,bo as ci,br as Pee,bs as li,bt as ui,c as di,ca as Fee,ci as Iee,cn as Lee,co as Ree,cr as fi,ct as pi,d as mi,da as hi,di as gi,dn as zee,do as Bee,dr as Vee,ds as _i,dt as vi,ea as yi,ec as bi,ei as xi,en as Si,eo as Ci,er as wi,es as Ti,et as Ei,f as Di,fa as Oi,fi as ki,fn as Ai,fo as ji,fr as Mi,fs as Ni,ft as Pi,g as Fi,ga as Ii,gi as Li,gn as Ri,go as zi,gr as Bi,gs as Vi,gt as Hi,h as Ui,ha as Wi,hi as Gi,hn as Ki,ho as qi,hr as Ji,hs as Yi,ht as Xi,i as Zi,ia as Qi,ii as $i,in as ea,io as ta,ir as na,it as ra,j as ia,ja as aa,ji as oa,jn as sa,jr as ca,js as la,jt as ua,k as da,ka as fa,ki as pa,kn as ma,kr as ha,ks as ga,kt as _a,l as va,la as Hee,li as Uee,ln as Wee,lo as Gee,lr as Kee,ls as ya,lt as ba,m as xa,ma as qee,mi as Jee,mn as Yee,mo as Xee,mr as Zee,ms as Sa,mt as Ca,n as wa,na as Ta,ni as Qee,nn as Ea,no as $ee,nr as ete,ns as Da,o as Oa,oa as ka,oi as Aa,on as tte,oo as nte,or as rte,os as ja,ot as Ma,p as Na,pa as ite,pi as ate,pn as ote,po as ste,pr as cte,ps as Pa,pt as Fa,q as Ia,qa as La,qi as Ra,qn as lte,qo as za,qr as Ba,qt as Va,r as Ha,ra as Ua,ri as ute,rn as Wa,ro as dte,rr as fte,rs as Ga,rt as Ka,s as qa,sa as Ja,si as pte,sn as mte,so as Ya,sr as Xa,ss as Za,st as Qa,t as $a,ta as eo,ti as hte,tn as gte,tr as _te,u as to,ua as vte,ui as no,un as yte,uo as ro,ur as bte,us as io,ut as ao,v as oo,va as so,vi as co,vn as lo,vo as xte,vr as Ste,vs as uo,vt as fo,w as po,wa as Cte,wi as wte,wn as mo,wo as ho,wr as Tte,ws as go,wt as _o,x as vo,xa as Ete,xi as Dte,xn as Ote,xo as kte,xr as Ate,xs as yo,xt as bo,y as xo,ya as So,yi as Co,yn as wo,yo as To,yr as Eo,yt as Do,z as Oo,za as ko,zi as Ao,zn as jo,zo as Mo,zr as No,zs as Po,zt as Fo}from"./src-BqZfalMj.mjs";import{c as Io,i as Lo,l as Ro,n as zo,s as Bo}from"./esm-DxvI2ZVA.mjs";import{n as Vo,t as Ho}from"./md-manager-C2pyfP1M.mjs";import{A as Uo,C as Wo,E as Go,I as Ko,M as qo,O as Jo,P as Yo,S as Xo,T as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,t as gs,u as _s,v as vs,w as ys,x as bs,y as xs}from"./fs-traced-CBFyXjv8.mjs";import{D as Ss,E as Cs,S as ws,T as Ts,a as Es,b as Ds,l as Os,p as ks,r as F,s as As,x as js,y as Ms}from"./logger-DFxEUjvj.mjs";import{a as Ns,i as Ps,o as Fs,r as Is,s as Ls,t as Rs}from"./git-handle-CjkVOyU7.mjs";import{C as zs,S as Bs,_ as Vs,a as Hs,b as Us,c as Ws,f as Gs,g as Ks,h as qs,i as Js,l as Ys,n as Xs,p as Zs,r as Qs,u as $s,x as ec}from"./server-lock-B8gC6O_D.mjs";import{t as tc}from"./libesm-DzwC_yFw.mjs";import{t as nc}from"./yazl-DZr4PyKA.mjs";import{n as rc,t as ic}from"./build-CJW5ggp6.mjs";import{t as ac}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as oc,c as sc,d as cc,f as lc,h as uc,i as dc,l as fc,m as pc,n as mc,o as hc,p as gc,r as _c,s as vc,t as yc,u as bc}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as xc,B as Sc,C as Cc,D as wc,E as Tc,F as Ec,H as Dc,I as Oc,L as kc,M as Ac,N as jc,O as Mc,P as Nc,S as Pc,T as Fc,V as Ic,_ as Lc,a as Rc,b as zc,c as Bc,d as Vc,f as Hc,g as Uc,h as Wc,i as Gc,j as Kc,k as qc,l as Jc,m as Yc,n as Xc,o as Zc,p as Qc,r as $c,s as el,t as tl,u as nl,v as rl,w as il,x as al,y as ol,z as sl}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as cl,c as ll,d as ul,i as dl,l as fl,n as jte,o as Mte,r as Nte,s as pl,t as Pte,u as ml}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as hl,r as gl,t as _l}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as vl}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as yl}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as bl,t as xl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as Fte,t as Sl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as Cl,r as wl,t as Tl}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as Ite,t as El}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as Dl}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as Ol}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as Lte}from"./wrapper-BcpqREsI.mjs";import{createRequire as kl}from"node:module";import{execFile as Al,execFileSync as Rte,spawn as jl,spawnSync as Ml}from"node:child_process";import*as Nl from"node:path";import{basename as Pl,delimiter as Fl,dirname as I,extname as Il,isAbsolute as Ll,join as L,normalize as Rl,parse as zl,posix as Bl,relative as R,resolve as z,sep as Vl,win32 as zte}from"node:path";import{URLSearchParams as Bte,fileURLToPath as Hl,pathToFileURL as Vte}from"node:url";import*as Ul from"node:fs";import{appendFileSync as Hte,chmodSync as Wl,closeSync as Gl,constants as Kl,createReadStream as ql,createWriteStream as Jl,existsSync as B,fstatSync as Ute,lstatSync as Yl,mkdirSync as Xl,mkdtempSync as Zl,openSync as Ql,opendirSync as $l,readFile as Wte,readFileSync as V,readSync as eu,readdirSync as tu,readlinkSync as nu,realpathSync as H,renameSync as ru,rmSync as iu,rmdirSync as au,statSync as ou,unlinkSync as su,writeFileSync as cu,writeSync as Gte}from"node:fs";import{arch as lu,availableParallelism as Kte,homedir as uu,hostname as du,platform as fu,tmpdir as pu}from"node:os";import{access as mu,chmod as qte,constants as hu,lstat as gu,readFile as _u,readdir as vu,realpath as yu,stat as bu,writeFile as Jte}from"node:fs/promises";import{Readable as xu,Transform as Yte,Writable as Xte}from"node:stream";import Su,{createHash as Cu,randomUUID as wu,webcrypto as Tu}from"node:crypto";import Zte from"crypto";import{Readable as Eu}from"stream";import{EventEmitter as Qte}from"node:events";import{Worker as $te}from"node:worker_threads";import{monitorEventLoopDelay as ene,performance as Du}from"node:perf_hooks";import{createInterface as tne}from"node:readline";import{pipeline as Ou}from"node:stream/promises";import{setImmediate as nne,setTimeout as ku}from"node:timers/promises";import{promisify as Au}from"node:util";import{request as rne}from"node:http";import{Http2ServerRequest as ju,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{Http2ServerRequest as Mu,constants as une}from"http2";import{AsyncLocalStorage as dne}from"node:async_hooks";import{lookup as fne}from"node:dns";import pne from"node:tls";function mne(e){let t=new TextEncoder().encode(e),n=new Uint8Array(1+t.length);return n[0]=1,n.set(t,1),hne(n)}function hne(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}var Nu=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=V(L(this.gitDir,`commondir`),`utf-8`).trim();t.length>0&&(e=Ll(t)?t:z(this.gitDir,t))}catch(e){if(!zu(e))return{kind:`unreadable`,cause:e}}return this.cachedCommonDir=e,{kind:`resolved`,path:e}}readHead(){let e;try{e=V(L(this.gitDir,`HEAD`),`utf-8`).trim()}catch(e){return zu(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]}:Hu(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=V(L(t.path,`config`),`utf-8`)}catch(e){return zu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=gne(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Bu(e))return{kind:`invalid`};let t=this.readCommonDir();if(t.kind===`unreadable`)return t;let n=z(t.path,e),r=R(t.path,n);if(r.startsWith(`..`)||Ll(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Vu(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!zu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return zu(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 Hu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function Pu(e){return Iu(z(e),``)}function Fu(e){let t=z(e),n=z(uu());if(t===n)return{kind:`absent`};let r=Iu(t,``);if(r.kind!==`absent`)return r;let i=t;for(let e=0;e<64;e++){if(i===n)return{kind:`absent`};let e=I(i);if(e===i||e===n)return{kind:`absent`};let r=Iu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Iu(e,t){let n=L(e,`.git`),r;try{r=ou(n)}catch(e){return zu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new Nu(`directory`,e,t,n,n)};if(!r.isFile())return{kind:`absent`};let i;try{i=V(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=Ll(o)?o:z(e,o);try{if(!ou(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 Nu(`linked`,e,t,n,s)}}function gne(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Lu(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=Ru(i[1]);if(a.length>0)return a}return null}function Lu(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Ru(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function zu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Bu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Vu(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Bu(t[1])?{kind:`symbolic`,target:t[1]}:null:Hu(e)?{kind:`oid`,oid:e}:null}function Hu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Uu(e){return`git-author-${_a(e.trim().toLowerCase())}`}const Wu=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Gu(e){let t=Fu(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 Ku(e){let t=Gu(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function qu(e){let t=Gu(e);switch(t.kind){case`directory`:return z(t.path,Ju(t.projectSubPath));case`linked`:if(!B(t.path))throw new Yu(t.gitPath,t.path);return z(t.path,Ju(t.projectSubPath));case`malformed-pointer`:throw new Yu(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Xu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Ju(e){return e===``?`ok`:`ok-${_ne(e)}`}function _ne(e){let t=e.split(Vl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=vne(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function vne(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var Yu=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}},Xu=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 yne(e){let t;try{t=qu(e)}catch(e){if(e instanceof Yu||e instanceof Xu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Zu(e){return`refs/wip/${e}/`}function bne(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 Qu=`ok-actor: `;function $u(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),`${Qu}${JSON.stringify(i)}`}function ed(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=td(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 td(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 nd(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(Qu))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:ed(n)}return null}function rd(e){if(!e)return[];let t=[];for(let n of e.split(`
4
- `)){let e=n.trim();if(!e.startsWith(Qu))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=ed(r);i&&t.push(i)}return t}function id(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 ad(e){let t=rd(e);return t.length>0?t.map(id):bne(e)}function od(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function sd(e){return`reconcile: ${e}`}function cd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function ld(e,t){return`park: ${e} -> ${t}`}function ud(e,t){return`rename: ${e} -> ${t}`}function dd(e){return`checkpoint: ${e}`}function xne(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Sne=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function fd(e){return e.replace(Sne,` `)}function Cne(e,t){let n=fd(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=fd(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function pd(e){return Wu.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function md(e){let t=Gu(e);if(t.kind!==`linked`)return z(e);try{let n=V(L(t.path,`commondir`),`utf-8`).trim();return n===``?z(e):z(I(z(t.path,n)),t.projectSubPath)}catch{return z(e)}}function hd(e){return e.kind??`other`}function wne(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var gd=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=hd(t),i=wne(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=hd(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-DtlsFK7O.mjs`);await e(L(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(V(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 _d=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Tne={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},vd=`acp-agents.json`,yd=`acp-registry-cache.json`;function bd(){let e=fu(),t=lu(),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 xd=new Set([`goose`,`fast-agent`,`crow-cli`]);function Sd(e,t){let n=t.trim();return n.length===0?e:xd.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Cd(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 wd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Cd).map(e=>({...e,name:Sd(e.id,e.name)})):null}var Td=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=wd(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-DtlsFK7O.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,yd),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=wd(await _u(L(this.localDir,yd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Ed(e,t){let n;try{n=await _u(L(e,vd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${vd} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${vd} entry`)}return i}const U={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`},Dd={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`},Od={cancel_request:`$/cancel_request`},kd=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function Ad(e,t){let n=e.catch(t);return _().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Oe):n.parse(e))}function jd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Md(e,t,n){return e.superRefine((e,r)=>{let i=jd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Nd(e,t,n){return _().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Oe}let o=a.data,s=jd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Pd(e){return P(e.catch(kd)).transform(e=>e.filter(e=>e!==kd))}const Fd=p([i(),u()]).nullable(),Id=u(),Ld=N({sessionId:Id,path:u(),content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rd=N({sessionId:Id,path:u(),line:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zd=u(),Bd=p([x(`read`),x(`edit`),x(`delete`),x(`move`),x(`search`),x(`execute`),x(`think`),x(`fetch`),x(`switch_mode`),x(`other`)]),Vd=p([x(`pending`),x(`in_progress`),x(`completed`),x(`failed`)]),Hd=N({audience:W(Pd(p([x(`assistant`),x(`user`)])).nullish(),()=>void 0),lastModified:W(u().nullish(),()=>void 0),priority:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ene=N({annotations:W(Hd.nullish(),()=>void 0),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dne=N({annotations:W(Hd.nullish(),()=>void 0),data:u(),mimeType:u(),uri:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),One=N({annotations:W(Hd.nullish(),()=>void 0),data:u(),mimeType:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kne=N({annotations:W(Hd.nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),mimeType:W(u().nullish(),()=>void 0),name:u(),size:W(i().nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ane=p([N({mimeType:W(u().nullish(),()=>void 0),text:u(),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),N({blob:u(),mimeType:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})]),jne=N({annotations:W(Hd.nullish(),()=>void 0),resource:Ane,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ud=p([Ene.and(N({type:x(`text`)})),Dne.and(N({type:x(`image`)})),One.and(N({type:x(`audio`)})),kne.and(N({type:x(`resource_link`)})),jne.and(N({type:x(`resource`)}))]),Mne=N({content:Ud,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nne=N({path:u(),oldText:W(u().nullish(),()=>void 0),newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wd=u(),Pne=N({terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gd=p([Mne.and(N({type:x(`content`)})),Nne.and(N({type:x(`diff`)})),Pne.and(N({type:x(`terminal`)}))]),Kd=N({path:u(),line:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qd=N({toolCallId:zd,kind:W(Bd.nullish(),()=>void 0),status:W(Vd.nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),content:W(Pd(Gd).nullish(),()=>void 0),locations:W(Pd(Kd).nullish(),()=>void 0),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jd=u(),Fne=p([x(`allow_once`),x(`allow_always`),x(`reject_once`),x(`reject_always`)]),Yd=N({sessionId:Id,toolCall:qd,options:P(N({optionId:Jd,name:u(),kind:Fne,_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xd=N({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zd=N({sessionId:Id,command:u(),args:W(Pd(u()).optional(),()=>[]),env:W(Pd(Xd).optional(),()=>[]),cwd:W(u().nullish(),()=>void 0),outputByteLimit:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qd=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),$d=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ef=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tf=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),nf=N({sessionId:Id,toolCallId:W(zd.nullish(),()=>void 0)}),rf=N({requestId:Fd}),Ine=x(`object`),Lne=p([x(`email`),x(`uri`),x(`date`),x(`date-time`)]),af=N({const:u(),title:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),of=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minLength:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:u().nullish(),format:Lne.nullish(),default:W(u().nullish(),()=>void 0),enum:P(u()).nullish(),oneOf:P(af).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),default:W(D().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),uf=N({enum:P(u()),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rne=N({anyOf:P(af),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zne=Nd(p([uf.and(N({type:x(`string`)})),Md(N({type:u()}),`type`,[`string`]),Rne]),`type`,[`string`]),df=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minItems:i().nullish(),maxItems:i().nullish(),items:zne,default:W(Pd(u()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bne=Nd(p([of.and(N({type:x(`string`)})),sf.and(N({type:x(`number`)})),cf.and(N({type:x(`integer`)})),lf.and(N({type:x(`boolean`)})),df.and(N({type:x(`array`)})),Md(N({type:u()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Vne=N({type:W(Ine.optional().default(`object`),()=>`object`),title:W(u().nullish(),()=>void 0),properties:C(u(),Bne).optional().default({}),required:P(u()).nullish(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ff=c(p([nf,rf]),N({requestedSchema:Vne})),pf=u(),mf=c(p([nf,rf]),N({elicitationId:pf,url:ee()})),hf=Nd(c(p([ff.and(N({mode:x(`form`)})),mf.and(N({mode:x(`url`)})),Md(c(p([nf,rf]),N({mode:u()})),`mode`,[`form`,`url`])]),N({message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),gf=u(),_f=N({serverId:gf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),vf=u(),yf=N({connectionId:vf,method:u(),params:C(u(),_()).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bf=N({connectionId:vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),xf=_();N({id:Fd,method:u(),params:p([Ld,Rd,Yd,Zd,Qd,$d,ef,tf,hf,_f,yf,bf,xf]).nullish()});const Sf=k().gte(0).lte(65535),Cf=N({image:W(D().optional().default(!1),()=>!1),audio:W(D().optional().default(!1),()=>!1),embeddedContext:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wf=N({http:W(D().optional().default(!1),()=>!1),sse:W(D().optional().default(!1),()=>!1),acp:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ef=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Df=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Of=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),kf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Af=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),jf=N({list:W(Tf.nullish(),()=>void 0),delete:W(Ef.nullish(),()=>void 0),additionalDirectories:W(Df.nullish(),()=>void 0),fork:W(Of.nullish(),()=>void 0),resume:W(kf.nullish(),()=>void 0),close:W(Af.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mf=N({logout:W(N({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ff=N({syncKind:p([x(`full`),x(`incremental`)]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),If=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),zf=N({document:W(N({didOpen:W(Pf.nullish(),()=>void 0),didChange:W(Ff.nullish(),()=>void 0),didClose:W(If.nullish(),()=>void 0),didSave:W(Lf.nullish(),()=>void 0),didFocus:W(Rf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Uf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kf=N({recentFiles:W(Bf.nullish(),()=>void 0),relatedSnippets:W(Vf.nullish(),()=>void 0),editHistory:W(Hf.nullish(),()=>void 0),userActions:W(Uf.nullish(),()=>void 0),openFiles:W(Wf.nullish(),()=>void 0),diagnostics:W(Gf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qf=N({events:W(zf.nullish(),()=>void 0),context:W(Kf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jf=p([x(`utf-16`),x(`utf-32`),x(`utf-8`)]),Yf=N({loadSession:W(D().optional().default(!1),()=>!1),promptCapabilities:W(Cf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(wf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(jf.optional().default({}),()=>({})),auth:W(Mf.optional().default({}),()=>({})),providers:W(Nf.nullish(),()=>void 0),nes:W(qf.nullish(),()=>void 0),positionEncoding:W(Jf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xf=u(),Zf=N({name:u(),label:W(u().nullish(),()=>void 0),secret:W(D().optional().default(!0),()=>!0),optional:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qf=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),vars:Ad(Pd(Zf),()=>[]),link:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$f=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),args:W(Pd(u()).optional(),()=>[]),env:W(C(u(),u()).optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ep=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),tp=p([Qf.and(N({type:x(`env_var`)})),$f.and(N({type:x(`terminal`)})),ep]),np=N({name:u(),title:W(u().nullish(),()=>void 0),version:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rp=N({protocolVersion:Sf,agentCapabilities:W(Yf.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:W(Pd(tp).optional().default([]),()=>[]),agentInfo:W(np.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ip=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ap=u(),op=p([x(`anthropic`),x(`openai`),x(`azure`),x(`vertex`),x(`bedrock`),u()]),sp=N({apiType:op,baseUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cp=N({providers:P(N({providerId:ap,supported:Ad(Pd(op),()=>[]),required:D(),current:sp.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),up=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),dp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fp=u(),pp=N({currentModeId:fp,availableModes:Ad(Pd(N({id:fp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mp=u(),hp=p([x(`mode`),x(`model`),x(`model_config`),x(`thought_level`),u()]),gp=u(),_p=N({value:gp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vp=N({group:u(),name:u(),options:Ad(Pd(_p),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp=N({currentValue:gp,options:p([P(_p),P(vp)])}),bp=N({currentValue:D()}),xp=c(p([yp.and(N({type:x(`select`)})),bp.and(N({type:x(`boolean`)}))]),N({id:mp,name:u(),description:W(u().nullish(),()=>void 0),category:W(hp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),Sp=N({sessionId:Id,modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cp=N({modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wp=N({sessions:Ad(Pd(N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ep=N({sessionId:Id,modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dp=N({modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Op=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),kp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ap=N({configOptions:Ad(Pd(xp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jp=N({stopReason:p([x(`end_turn`),x(`max_tokens`),x(`max_turn_requests`),x(`refusal`),x(`cancelled`)]),usage:W(N({totalTokens:i(),inputTokens:i(),outputTokens:i(),thoughtTokens:W(i().nullish(),()=>void 0),cachedReadTokens:W(i().nullish(),()=>void 0),cachedWriteTokens:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mp=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Np=u(),Pp=N({line:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fp=N({start:Pp,end:Pp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ip=N({range:Fp,newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lp=N({id:Np,uri:u(),edits:P(Ip),cursorPosition:W(Pp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rp=N({id:Np,uri:u(),position:Pp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),zp=N({id:Np,uri:u(),position:Pp,newName:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bp=N({id:Np,uri:u(),search:u(),replace:u(),isRegex:D().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vp=N({suggestions:P(p([Lp.and(N({kind:x(`edit`)})),Rp.and(N({kind:x(`jump`)})),zp.and(N({kind:x(`rename`)})),Bp.and(N({kind:x(`searchAndReplace`)}))])),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Up=_(),Wp=_(),Gp=N({code:p([x(-32700),x(-32600),x(-32601),x(-32602),x(-32603),x(-32800),x(-32e3),x(-32002),k().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:u(),data:W(_().optional(),()=>void 0)});p([N({id:Fd,result:p([rp,ip,cp,lp,up,dp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Vp,Hp,Up,Wp])}),N({id:Fd,error:Gp})]);const Kp=N({content:Ud,messageId:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hne=N({toolCallId:zd,title:u(),kind:W(Bd.optional(),()=>void 0),status:W(Vd.optional(),()=>void 0),content:W(Pd(Gd).optional(),()=>[]),locations:W(Pd(Kd).optional(),()=>[]),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Une=p([x(`high`),x(`medium`),x(`low`)]),Wne=p([x(`pending`),x(`in_progress`),x(`completed`)]),qp=N({content:u(),priority:Une,status:Wne,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gne=N({entries:Ad(Pd(qp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jp=u(),Kne=N({planId:Jp,entries:Ad(Pd(qp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qne=N({planId:Jp,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jne=N({planId:Jp,content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yne=N({plan:p([Kne.and(N({type:x(`items`)})),qne.and(N({type:x(`file`)})),Jne.and(N({type:x(`markdown`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xne=N({planId:Jp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zne=N({hint:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qne=N({availableCommands:Ad(Pd(N({name:u(),description:u(),input:W(Zne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$ne=N({currentModeId:fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ere=N({configOptions:Ad(Pd(xp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),tre=N({title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),nre=N({amount:i(),currency:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rre=N({used:i(),size:i(),cost:W(nre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yp=N({sessionId:Id,update:p([Kp.and(N({sessionUpdate:x(`user_message_chunk`)})),Kp.and(N({sessionUpdate:x(`agent_message_chunk`)})),Kp.and(N({sessionUpdate:x(`agent_thought_chunk`)})),Hne.and(N({sessionUpdate:x(`tool_call`)})),qd.and(N({sessionUpdate:x(`tool_call_update`)})),Gne.and(N({sessionUpdate:x(`plan`)})),Yne.and(N({sessionUpdate:x(`plan_update`)})),Xne.and(N({sessionUpdate:x(`plan_removed`)})),Qne.and(N({sessionUpdate:x(`available_commands_update`)})),$ne.and(N({sessionUpdate:x(`current_mode_update`)})),ere.and(N({sessionUpdate:x(`config_option_update`)})),tre.and(N({sessionUpdate:x(`session_info_update`)})),rre.and(N({sessionUpdate:x(`usage_update`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xp=N({elicitationId:pf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zp=N({connectionId:vf,method:u(),params:W(C(u(),_()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qp=_();N({method:u(),params:p([Yp,Xp,Zp,Qp]).nullish()});const ire=N({readTextFile:W(D().optional().default(!1),()=>!1),writeTextFile:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),are=N({configOptions:W(N({boolean:W(N({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ore=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),sre=N({terminal:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),lre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ure=N({form:W(cre.nullish(),()=>void 0),url:W(lre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),dre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),pre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),mre=N({jump:W(dre.nullish(),()=>void 0),rename:W(fre.nullish(),()=>void 0),searchAndReplace:W(pre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$p=N({protocolVersion:Sf,clientCapabilities:W(N({fs:W(ire.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(D().optional().default(!1),()=>!1),session:W(are.nullish(),()=>void 0),plan:W(ore.nullish(),()=>void 0),auth:W(sre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(ure.nullish(),()=>void 0),nes:W(mre.nullish(),()=>void 0),positionEncodings:W(Pd(Jf).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:W(np.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),em=N({methodId:Xf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tm=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),nm=N({providerId:ap,apiType:op,baseUrl:u(),headers:C(u(),u()).optional(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rm=N({providerId:ap,_meta:W(C(u(),_()).nullish(),()=>void 0)}),im=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),am=N({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hre=N({name:u(),url:u(),headers:P(am),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gre=N({name:u(),url:u(),headers:P(am),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_re=N({name:u(),serverId:gf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),vre=N({name:u(),command:u(),args:P(u()),env:P(Xd),_meta:W(C(u(),_()).nullish(),()=>void 0)}),om=p([hre.and(N({type:x(`http`)})),gre.and(N({type:x(`sse`)})),_re.and(N({type:x(`acp`)})),vre]),sm=N({cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:Ad(Pd(om),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cm=N({mcpServers:Ad(Pd(om),()=>[]),cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),lm=N({cwd:u().nullish(),cursor:u().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),um=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),dm=N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:W(Pd(om).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fm=N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:W(Pd(om).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pm=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),mm=N({sessionId:Id,modeId:fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),hm=c(p([N({value:D(),type:x(`boolean`)}),N({value:gp})]),N({sessionId:Id,configId:mp,_meta:W(C(u(),_()).nullish(),()=>void 0)})),gm=N({sessionId:Id,prompt:P(Ud),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yre=N({uri:u(),name:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bre=N({name:u(),owner:u(),remoteUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_m=N({workspaceUri:W(u().nullish(),()=>void 0),workspaceFolders:P(yre).nullish(),repository:W(bre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xre=p([x(`automatic`),x(`diagnostic`),x(`manual`)]),Sre=N({uri:u(),languageId:u(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cre=N({startLine:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wre=N({uri:u(),excerpts:P(Cre),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tre=N({uri:u(),diff:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ere=N({action:u(),uri:u(),position:Pp,timestampMs:i(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dre=N({uri:u(),languageId:u(),visibleRange:W(Fp.nullish(),()=>void 0),lastFocusedMs:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ore=p([x(`error`),x(`warning`),x(`information`),x(`hint`)]),kre=N({uri:u(),range:Fp,severity:Ore,message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Are=N({recentFiles:P(Sre).nullish(),relatedSnippets:P(wre).nullish(),editHistory:P(Tre).nullish(),userActions:P(Ere).nullish(),openFiles:P(Dre).nullish(),diagnostics:P(kre).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vm=N({sessionId:Id,uri:u(),version:i(),position:Pp,selection:Fp.nullish(),triggerKind:xre,context:Are.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ym=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)});N({id:Fd,method:u(),params:p([$p,em,tm,nm,rm,im,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,yf,xf]).nullish()});const jre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mre=N({content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nre=N({optionId:Jd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pre=N({outcome:p([N({outcome:x(`cancelled`)}),Nre.and(N({outcome:x(`selected`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fre=N({terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ire=N({exitCode:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lre=N({output:u(),truncated:D(),exitStatus:W(Ire.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),zre=N({exitCode:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vre=p([u(),i(),i(),D(),P(u())]),bm=N({content:C(u(),Vre).nullish()});p([N({id:Fd,result:p([jre,Mre,Pre,Fre,Lre,Rre,zre,Bre,Nd(c(p([bm.and(N({action:x(`accept`)})),N({action:x(`decline`)}),N({action:x(`cancel`)}),Md(N({action:u()}),`action`,[`accept`,`cancel`,`decline`])]),N({_meta:W(C(u(),_()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),N({connectionId:vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wp,Up])}),N({id:Fd,error:Gp})]);const xm=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sm=N({sessionId:Id,uri:u(),languageId:u(),version:i(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hre=N({range:Fp.nullish(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cm=N({sessionId:Id,uri:u(),version:i(),contentChanges:Ad(Pd(Hre),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wm=N({sessionId:Id,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tm=N({sessionId:Id,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Em=N({sessionId:Id,uri:u(),version:i(),position:Pp,visibleRange:Fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dm=N({sessionId:Id,id:Np,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Om=N({sessionId:Id,id:Np,reason:W(p([x(`rejected`),x(`ignored`),x(`replaced`),x(`cancelled`)]).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)});N({method:u(),params:p([xm,Sm,Cm,wm,Tm,Em,Dm,Om,Zp,Qp]).nullish()}),N({requestId:Fd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ff.and(N({mode:x(`form`)})).and(N({message:u()})),mf.and(N({mode:x(`url`)})).and(N({message:u()})),p([nf,rf]).and(N({message:u()})),of.and(N({type:x(`string`)})),sf.and(N({type:x(`number`)})),cf.and(N({type:x(`integer`)})),lf.and(N({type:x(`boolean`)})),df.and(N({type:x(`array`)})),uf.and(N({type:x(`string`)})),bm.and(N({action:x(`accept`)})),N({action:x(`decline`)}),N({action:x(`cancel`)});const km=`$/cancel_request`;function Am(e){return typeof e==`object`&&!!e}function Ure(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Wre(e){if(!(!Am(e)||!Ure(e.requestId)))return e.requestId}const jm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Mm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Gre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Kre(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 Nm(e){if(e instanceof Im)return e.toResult();if(Kre(e))return Im.invalidParams(e.format()).toResult();let t=Gre(e);try{return Im.internalError(t?JSON.parse(t):{}).toResult()}catch{return Im.internalError({details:t}).toResult()}}function qre(e){return e instanceof Im&&e.code===-32800?e:Im.requestCancelled(e)}function Jre(e,t){let n=Yre(e,t);return n?n.toResult():Nm(e)}function Yre(e,t){if(!(!t.aborted||!Xre(e)))return qre(t.reason)}function Xre(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Zre=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 Im?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Mm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Pm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Qre=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}},Fm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Qre(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 $re}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 Pm(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return Mm(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification(km,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Mm(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return jm.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(!Am(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(Im.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Jre(n,t.responder.signal));else{let t=Nm(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 Zre(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&&Am(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Im(n,r,i))}else t.reject(Im.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==km)return;let t=Wre(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Im.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Mm(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},$re=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)??jm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?jm.no(r):await n(t(r.params),r.responder,i)??jm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?jm.no(r):await n(t(r.params),i)??jm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Fm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Im=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}}},eie=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 tie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new eie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Am(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
4
+ `)){let e=n.trim();if(!e.startsWith(Qu))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=ed(r);i&&t.push(i)}return t}function id(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 ad(e){let t=rd(e);return t.length>0?t.map(id):bne(e)}function od(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function sd(e){return`reconcile: ${e}`}function cd(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function ld(e,t){return`park: ${e} -> ${t}`}function ud(e,t){return`rename: ${e} -> ${t}`}function dd(e){return`checkpoint: ${e}`}function xne(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Sne=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function fd(e){return e.replace(Sne,` `)}function Cne(e,t){let n=fd(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=fd(r),a=`${n} — ${i}`;if(a.length<=72)return a;let o=`${n} — `,s=72-o.length-1;return s<=0?a.slice(0,72):`${o}${i.slice(0,s)}…`}function pd(e){return Wu.test(e)?e.startsWith(`agent-`)?{id:e,classification:`agent`,isAgent:!0}:e.startsWith(`principal-`)?{id:e,classification:`principal`,isAgent:!1}:e.startsWith(`git-author-`)?{id:e,classification:`classified-git-author`,isAgent:null}:e===`file-system`?{id:e,classification:`classified-file-system`,isAgent:null}:e===`git-upstream`?{id:e,classification:`classified-git-upstream`,isAgent:null}:e===`openknowledge-service`?{id:e,classification:`classified-openknowledge-service`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}:{id:e,classification:`unknown`,isAgent:null}}function md(e){let t=Gu(e);if(t.kind!==`linked`)return z(e);try{let n=V(L(t.path,`commondir`),`utf-8`).trim();return n===``?z(e):z(I(z(t.path,n)),t.projectSubPath)}catch{return z(e)}}function hd(e){return e.kind??`other`}function wne(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var gd=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=hd(t),i=wne(n,[`allow_once`,`allow_always`]);return i===void 0?{auto:null}:r===`read`||this.hasAllowAlways(e,r)?{auto:{optionId:i.optionId}}:{auto:null}}hasAllowAlways(e,t){return this.loadGrants().some(n=>n.agentId===e&&n.toolKind===t)}async recordChoice(e,t,n){if(n.kind!==`allow_always`)return;let r=hd(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-CChInc-O.mjs`);await e(L(this.filePath,`..`),{recursive:!0});let n={version:1,grants:i};await t(this.filePath,`${JSON.stringify(n,null,2)}\n`)}catch(e){this.log.warn({err:e},`[acp-permissions] persisting allow_always grant failed`)}}loadGrants(){if(this.grants!==null)return this.grants;try{let e=JSON.parse(V(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 _d=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],Tne={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},vd=`acp-agents.json`,yd=`acp-registry-cache.json`;function bd(){let e=fu(),t=lu(),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 xd=new Set([`goose`,`fast-agent`,`crow-cli`]);function Sd(e,t){let n=t.trim();return n.length===0?e:xd.has(e)||n!==n.toLowerCase()?n:n.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `)}function Cd(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 wd(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(Cd).map(e=>({...e,name:Sd(e.id,e.name)})):null}var Td=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=wd(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-CChInc-O.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,yd),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=wd(await _u(L(this.localDir,yd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function Ed(e,t){let n;try{n=await _u(L(e,vd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${vd} is not valid JSON — ignoring`),[]}if(!Array.isArray(r))return[];let i=[];for(let e of r){let n=e;typeof n?.id==`string`&&/^[a-zA-Z0-9_-]+$/.test(n.id)&&typeof n.name==`string`&&typeof n.command==`string`&&n.command.length>0&&(n.args===void 0||Array.isArray(n.args)&&n.args.every(e=>typeof e==`string`))&&(n.env===void 0||typeof n.env==`object`&&n.env!==null&&!Array.isArray(n.env)&&Object.values(n.env).every(e=>typeof e==`string`))?i.push({id:n.id,name:n.name,command:n.command,args:n.args,env:n.env??void 0}):t.warn({entry:e},`[acp-registry] dropping malformed ${vd} entry`)}return i}const U={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`},Dd={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`},Od={cancel_request:`$/cancel_request`},kd=Symbol(`skippedItem`);function W(e,t){return e.catch(t)}function Ad(e,t){let n=e.catch(t);return _().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Oe):n.parse(e))}function jd(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];return typeof n==`string`?n:void 0}function Md(e,t,n){return e.superRefine((e,r)=>{let i=jd(e,t);i!==void 0&&n.includes(i)&&r.addIssue({code:`custom`,path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function Nd(e,t,n){return _().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Oe}let o=a.data,s=jd(r,t);if(s!==void 0&&!n.includes(s)){let e=r;for(let[t,n]of Object.entries(e))t!==`__proto__`&&(Object.hasOwn(o,t)||(o[t]=n))}return o})}function Pd(e){return P(e.catch(kd)).transform(e=>e.filter(e=>e!==kd))}const Fd=p([i(),u()]).nullable(),Id=u(),Ld=N({sessionId:Id,path:u(),content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rd=N({sessionId:Id,path:u(),line:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zd=u(),Bd=p([x(`read`),x(`edit`),x(`delete`),x(`move`),x(`search`),x(`execute`),x(`think`),x(`fetch`),x(`switch_mode`),x(`other`)]),Vd=p([x(`pending`),x(`in_progress`),x(`completed`),x(`failed`)]),Hd=N({audience:W(Pd(p([x(`assistant`),x(`user`)])).nullish(),()=>void 0),lastModified:W(u().nullish(),()=>void 0),priority:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ene=N({annotations:W(Hd.nullish(),()=>void 0),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dne=N({annotations:W(Hd.nullish(),()=>void 0),data:u(),mimeType:u(),uri:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),One=N({annotations:W(Hd.nullish(),()=>void 0),data:u(),mimeType:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),kne=N({annotations:W(Hd.nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),mimeType:W(u().nullish(),()=>void 0),name:u(),size:W(i().nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ane=p([N({mimeType:W(u().nullish(),()=>void 0),text:u(),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),N({blob:u(),mimeType:W(u().nullish(),()=>void 0),uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})]),jne=N({annotations:W(Hd.nullish(),()=>void 0),resource:Ane,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ud=p([Ene.and(N({type:x(`text`)})),Dne.and(N({type:x(`image`)})),One.and(N({type:x(`audio`)})),kne.and(N({type:x(`resource_link`)})),jne.and(N({type:x(`resource`)}))]),Mne=N({content:Ud,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nne=N({path:u(),oldText:W(u().nullish(),()=>void 0),newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wd=u(),Pne=N({terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gd=p([Mne.and(N({type:x(`content`)})),Nne.and(N({type:x(`diff`)})),Pne.and(N({type:x(`terminal`)}))]),Kd=N({path:u(),line:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qd=N({toolCallId:zd,kind:W(Bd.nullish(),()=>void 0),status:W(Vd.nullish(),()=>void 0),title:W(u().nullish(),()=>void 0),content:W(Pd(Gd).nullish(),()=>void 0),locations:W(Pd(Kd).nullish(),()=>void 0),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jd=u(),Fne=p([x(`allow_once`),x(`allow_always`),x(`reject_once`),x(`reject_always`)]),Yd=N({sessionId:Id,toolCall:qd,options:P(N({optionId:Jd,name:u(),kind:Fne,_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xd=N({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zd=N({sessionId:Id,command:u(),args:W(Pd(u()).optional(),()=>[]),env:W(Pd(Xd).optional(),()=>[]),cwd:W(u().nullish(),()=>void 0),outputByteLimit:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qd=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),$d=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ef=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tf=N({sessionId:Id,terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),nf=N({sessionId:Id,toolCallId:W(zd.nullish(),()=>void 0)}),rf=N({requestId:Fd}),Ine=x(`object`),Lne=p([x(`email`),x(`uri`),x(`date`),x(`date-time`)]),af=N({const:u(),title:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),of=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minLength:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:u().nullish(),format:Lne.nullish(),default:W(u().nullish(),()=>void 0),enum:P(u()).nullish(),oneOf:P(af).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),sf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minimum:i().nullish(),maximum:i().nullish(),default:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lf=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),default:W(D().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),uf=N({enum:P(u()),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rne=N({anyOf:P(af),_meta:W(C(u(),_()).nullish(),()=>void 0)}),zne=Nd(p([uf.and(N({type:x(`string`)})),Md(N({type:u()}),`type`,[`string`]),Rne]),`type`,[`string`]),df=N({title:W(u().nullish(),()=>void 0),description:W(u().nullish(),()=>void 0),minItems:i().nullish(),maxItems:i().nullish(),items:zne,default:W(Pd(u()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bne=Nd(p([of.and(N({type:x(`string`)})),sf.and(N({type:x(`number`)})),cf.and(N({type:x(`integer`)})),lf.and(N({type:x(`boolean`)})),df.and(N({type:x(`array`)})),Md(N({type:u()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),Vne=N({type:W(Ine.optional().default(`object`),()=>`object`),title:W(u().nullish(),()=>void 0),properties:C(u(),Bne).optional().default({}),required:P(u()).nullish(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ff=c(p([nf,rf]),N({requestedSchema:Vne})),pf=u(),mf=c(p([nf,rf]),N({elicitationId:pf,url:ee()})),hf=Nd(c(p([ff.and(N({mode:x(`form`)})),mf.and(N({mode:x(`url`)})),Md(c(p([nf,rf]),N({mode:u()})),`mode`,[`form`,`url`])]),N({message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),gf=u(),_f=N({serverId:gf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),vf=u(),yf=N({connectionId:vf,method:u(),params:C(u(),_()).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bf=N({connectionId:vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),xf=_();N({id:Fd,method:u(),params:p([Ld,Rd,Yd,Zd,Qd,$d,ef,tf,hf,_f,yf,bf,xf]).nullish()});const Sf=k().gte(0).lte(65535),Cf=N({image:W(D().optional().default(!1),()=>!1),audio:W(D().optional().default(!1),()=>!1),embeddedContext:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wf=N({http:W(D().optional().default(!1),()=>!1),sse:W(D().optional().default(!1),()=>!1),acp:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ef=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Df=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Of=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),kf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Af=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),jf=N({list:W(Tf.nullish(),()=>void 0),delete:W(Ef.nullish(),()=>void 0),additionalDirectories:W(Df.nullish(),()=>void 0),fork:W(Of.nullish(),()=>void 0),resume:W(kf.nullish(),()=>void 0),close:W(Af.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mf=N({logout:W(N({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ff=N({syncKind:p([x(`full`),x(`incremental`)]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),If=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),zf=N({document:W(N({didOpen:W(Pf.nullish(),()=>void 0),didChange:W(Ff.nullish(),()=>void 0),didClose:W(If.nullish(),()=>void 0),didSave:W(Lf.nullish(),()=>void 0),didFocus:W(Rf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Uf=N({maxCount:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gf=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Kf=N({recentFiles:W(Bf.nullish(),()=>void 0),relatedSnippets:W(Vf.nullish(),()=>void 0),editHistory:W(Hf.nullish(),()=>void 0),userActions:W(Uf.nullish(),()=>void 0),openFiles:W(Wf.nullish(),()=>void 0),diagnostics:W(Gf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qf=N({events:W(zf.nullish(),()=>void 0),context:W(Kf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jf=p([x(`utf-16`),x(`utf-32`),x(`utf-8`)]),Yf=N({loadSession:W(D().optional().default(!1),()=>!1),promptCapabilities:W(Cf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:W(wf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:W(jf.optional().default({}),()=>({})),auth:W(Mf.optional().default({}),()=>({})),providers:W(Nf.nullish(),()=>void 0),nes:W(qf.nullish(),()=>void 0),positionEncoding:W(Jf.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xf=u(),Zf=N({name:u(),label:W(u().nullish(),()=>void 0),secret:W(D().optional().default(!0),()=>!0),optional:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qf=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),vars:Ad(Pd(Zf),()=>[]),link:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$f=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),args:W(Pd(u()).optional(),()=>[]),env:W(C(u(),u()).optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ep=N({id:Xf,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),tp=p([Qf.and(N({type:x(`env_var`)})),$f.and(N({type:x(`terminal`)})),ep]),np=N({name:u(),title:W(u().nullish(),()=>void 0),version:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rp=N({protocolVersion:Sf,agentCapabilities:W(Yf.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:W(Pd(tp).optional().default([]),()=>[]),agentInfo:W(np.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ip=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ap=u(),op=p([x(`anthropic`),x(`openai`),x(`azure`),x(`vertex`),x(`bedrock`),u()]),sp=N({apiType:op,baseUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cp=N({providers:P(N({providerId:ap,supported:Ad(Pd(op),()=>[]),required:D(),current:sp.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)})),_meta:W(C(u(),_()).nullish(),()=>void 0)}),lp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),up=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),dp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fp=u(),pp=N({currentModeId:fp,availableModes:Ad(Pd(N({id:fp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),mp=u(),hp=p([x(`mode`),x(`model`),x(`model_config`),x(`thought_level`),u()]),gp=u(),_p=N({value:gp,name:u(),description:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vp=N({group:u(),name:u(),options:Ad(Pd(_p),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yp=N({currentValue:gp,options:p([P(_p),P(vp)])}),bp=N({currentValue:D()}),xp=c(p([yp.and(N({type:x(`select`)})),bp.and(N({type:x(`boolean`)}))]),N({id:mp,name:u(),description:W(u().nullish(),()=>void 0),category:W(hp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),Sp=N({sessionId:Id,modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cp=N({modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wp=N({sessions:Ad(Pd(N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),nextCursor:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ep=N({sessionId:Id,modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dp=N({modes:W(pp.nullish(),()=>void 0),configOptions:W(Pd(xp).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Op=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),kp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ap=N({configOptions:Ad(Pd(xp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),jp=N({stopReason:p([x(`end_turn`),x(`max_tokens`),x(`max_turn_requests`),x(`refusal`),x(`cancelled`)]),usage:W(N({totalTokens:i(),inputTokens:i(),outputTokens:i(),thoughtTokens:W(i().nullish(),()=>void 0),cachedReadTokens:W(i().nullish(),()=>void 0),cachedWriteTokens:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mp=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Np=u(),Pp=N({line:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fp=N({start:Pp,end:Pp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ip=N({range:Fp,newText:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lp=N({id:Np,uri:u(),edits:P(Ip),cursorPosition:W(Pp.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rp=N({id:Np,uri:u(),position:Pp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),zp=N({id:Np,uri:u(),position:Pp,newName:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bp=N({id:Np,uri:u(),search:u(),replace:u(),isRegex:D().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vp=N({suggestions:P(p([Lp.and(N({kind:x(`edit`)})),Rp.and(N({kind:x(`jump`)})),zp.and(N({kind:x(`rename`)})),Bp.and(N({kind:x(`searchAndReplace`)}))])),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hp=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Up=_(),Wp=_(),Gp=N({code:p([x(-32700),x(-32600),x(-32601),x(-32602),x(-32603),x(-32800),x(-32e3),x(-32002),k().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:u(),data:W(_().optional(),()=>void 0)});p([N({id:Fd,result:p([rp,ip,cp,lp,up,dp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Vp,Hp,Up,Wp])}),N({id:Fd,error:Gp})]);const Kp=N({content:Ud,messageId:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hne=N({toolCallId:zd,title:u(),kind:W(Bd.optional(),()=>void 0),status:W(Vd.optional(),()=>void 0),content:W(Pd(Gd).optional(),()=>[]),locations:W(Pd(Kd).optional(),()=>[]),rawInput:W(_().optional(),()=>void 0),rawOutput:W(_().optional(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Une=p([x(`high`),x(`medium`),x(`low`)]),Wne=p([x(`pending`),x(`in_progress`),x(`completed`)]),qp=N({content:u(),priority:Une,status:Wne,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Gne=N({entries:Ad(Pd(qp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jp=u(),Kne=N({planId:Jp,entries:Ad(Pd(qp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),qne=N({planId:Jp,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Jne=N({planId:Jp,content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yne=N({plan:p([Kne.and(N({type:x(`items`)})),qne.and(N({type:x(`file`)})),Jne.and(N({type:x(`markdown`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xne=N({planId:Jp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zne=N({hint:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qne=N({availableCommands:Ad(Pd(N({name:u(),description:u(),input:W(Zne.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)})),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$ne=N({currentModeId:fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ere=N({configOptions:Ad(Pd(xp),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),tre=N({title:W(u().nullish(),()=>void 0),updatedAt:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),nre=N({amount:i(),currency:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rre=N({used:i(),size:i(),cost:W(nre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Yp=N({sessionId:Id,update:p([Kp.and(N({sessionUpdate:x(`user_message_chunk`)})),Kp.and(N({sessionUpdate:x(`agent_message_chunk`)})),Kp.and(N({sessionUpdate:x(`agent_thought_chunk`)})),Hne.and(N({sessionUpdate:x(`tool_call`)})),qd.and(N({sessionUpdate:x(`tool_call_update`)})),Gne.and(N({sessionUpdate:x(`plan`)})),Yne.and(N({sessionUpdate:x(`plan_update`)})),Xne.and(N({sessionUpdate:x(`plan_removed`)})),Qne.and(N({sessionUpdate:x(`available_commands_update`)})),$ne.and(N({sessionUpdate:x(`current_mode_update`)})),ere.and(N({sessionUpdate:x(`config_option_update`)})),tre.and(N({sessionUpdate:x(`session_info_update`)})),rre.and(N({sessionUpdate:x(`usage_update`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Xp=N({elicitationId:pf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Zp=N({connectionId:vf,method:u(),params:W(C(u(),_()).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Qp=_();N({method:u(),params:p([Yp,Xp,Zp,Qp]).nullish()});const ire=N({readTextFile:W(D().optional().default(!1),()=>!1),writeTextFile:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),are=N({configOptions:W(N({boolean:W(N({_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ore=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),sre=N({terminal:W(D().optional().default(!1),()=>!1),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),lre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),ure=N({form:W(cre.nullish(),()=>void 0),url:W(lre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),dre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),fre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),pre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),mre=N({jump:W(dre.nullish(),()=>void 0),rename:W(fre.nullish(),()=>void 0),searchAndReplace:W(pre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),$p=N({protocolVersion:Sf,clientCapabilities:W(N({fs:W(ire.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:W(D().optional().default(!1),()=>!1),session:W(are.nullish(),()=>void 0),plan:W(ore.nullish(),()=>void 0),auth:W(sre.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:W(ure.nullish(),()=>void 0),nes:W(mre.nullish(),()=>void 0),positionEncodings:W(Pd(Jf).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:W(np.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),em=N({methodId:Xf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),tm=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),nm=N({providerId:ap,apiType:op,baseUrl:u(),headers:C(u(),u()).optional(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),rm=N({providerId:ap,_meta:W(C(u(),_()).nullish(),()=>void 0)}),im=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),am=N({name:u(),value:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),hre=N({name:u(),url:u(),headers:P(am),_meta:W(C(u(),_()).nullish(),()=>void 0)}),gre=N({name:u(),url:u(),headers:P(am),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_re=N({name:u(),serverId:gf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),vre=N({name:u(),command:u(),args:P(u()),env:P(Xd),_meta:W(C(u(),_()).nullish(),()=>void 0)}),om=p([hre.and(N({type:x(`http`)})),gre.and(N({type:x(`sse`)})),_re.and(N({type:x(`acp`)})),vre]),sm=N({cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:Ad(Pd(om),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),cm=N({mcpServers:Ad(Pd(om),()=>[]),cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),lm=N({cwd:u().nullish(),cursor:u().nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),um=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),dm=N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:W(Pd(om).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),fm=N({sessionId:Id,cwd:u(),additionalDirectories:W(Pd(u()).optional(),()=>[]),mcpServers:W(Pd(om).optional(),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),pm=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),mm=N({sessionId:Id,modeId:fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),hm=c(p([N({value:D(),type:x(`boolean`)}),N({value:gp})]),N({sessionId:Id,configId:mp,_meta:W(C(u(),_()).nullish(),()=>void 0)})),gm=N({sessionId:Id,prompt:P(Ud),_meta:W(C(u(),_()).nullish(),()=>void 0)}),yre=N({uri:u(),name:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),bre=N({name:u(),owner:u(),remoteUrl:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),_m=N({workspaceUri:W(u().nullish(),()=>void 0),workspaceFolders:P(yre).nullish(),repository:W(bre.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),xre=p([x(`automatic`),x(`diagnostic`),x(`manual`)]),Sre=N({uri:u(),languageId:u(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cre=N({startLine:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wre=N({uri:u(),excerpts:P(Cre),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tre=N({uri:u(),diff:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ere=N({action:u(),uri:u(),position:Pp,timestampMs:i(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dre=N({uri:u(),languageId:u(),visibleRange:W(Fp.nullish(),()=>void 0),lastFocusedMs:W(i().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ore=p([x(`error`),x(`warning`),x(`information`),x(`hint`)]),kre=N({uri:u(),range:Fp,severity:Ore,message:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Are=N({recentFiles:P(Sre).nullish(),relatedSnippets:P(wre).nullish(),editHistory:P(Tre).nullish(),userActions:P(Ere).nullish(),openFiles:P(Dre).nullish(),diagnostics:P(kre).nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),vm=N({sessionId:Id,uri:u(),version:i(),position:Pp,selection:Fp.nullish(),triggerKind:xre,context:Are.nullish(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),ym=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)});N({id:Fd,method:u(),params:p([$p,em,tm,nm,rm,im,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,yf,xf]).nullish()});const jre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Mre=N({content:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Nre=N({optionId:Jd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Pre=N({outcome:p([N({outcome:x(`cancelled`)}),Nre.and(N({outcome:x(`selected`)}))]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Fre=N({terminalId:Wd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Ire=N({exitCode:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Lre=N({output:u(),truncated:D(),exitStatus:W(Ire.nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Rre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),zre=N({exitCode:W(k().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:W(u().nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Bre=N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Vre=p([u(),i(),i(),D(),P(u())]),bm=N({content:C(u(),Vre).nullish()});p([N({id:Fd,result:p([jre,Mre,Pre,Fre,Lre,Rre,zre,Bre,Nd(c(p([bm.and(N({action:x(`accept`)})),N({action:x(`decline`)}),N({action:x(`cancel`)}),Md(N({action:u()}),`action`,[`accept`,`cancel`,`decline`])]),N({_meta:W(C(u(),_()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),N({connectionId:vf,_meta:W(C(u(),_()).nullish(),()=>void 0)}),N({_meta:W(C(u(),_()).nullish(),()=>void 0)}),Wp,Up])}),N({id:Fd,error:Gp})]);const xm=N({sessionId:Id,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Sm=N({sessionId:Id,uri:u(),languageId:u(),version:i(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Hre=N({range:Fp.nullish(),text:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Cm=N({sessionId:Id,uri:u(),version:i(),contentChanges:Ad(Pd(Hre),()=>[]),_meta:W(C(u(),_()).nullish(),()=>void 0)}),wm=N({sessionId:Id,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Tm=N({sessionId:Id,uri:u(),_meta:W(C(u(),_()).nullish(),()=>void 0)}),Em=N({sessionId:Id,uri:u(),version:i(),position:Pp,visibleRange:Fp,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Dm=N({sessionId:Id,id:Np,_meta:W(C(u(),_()).nullish(),()=>void 0)}),Om=N({sessionId:Id,id:Np,reason:W(p([x(`rejected`),x(`ignored`),x(`replaced`),x(`cancelled`)]).nullish(),()=>void 0),_meta:W(C(u(),_()).nullish(),()=>void 0)});N({method:u(),params:p([xm,Sm,Cm,wm,Tm,Em,Dm,Om,Zp,Qp]).nullish()}),N({requestId:Fd,_meta:W(C(u(),_()).nullish(),()=>void 0)}),ff.and(N({mode:x(`form`)})).and(N({message:u()})),mf.and(N({mode:x(`url`)})).and(N({message:u()})),p([nf,rf]).and(N({message:u()})),of.and(N({type:x(`string`)})),sf.and(N({type:x(`number`)})),cf.and(N({type:x(`integer`)})),lf.and(N({type:x(`boolean`)})),df.and(N({type:x(`array`)})),uf.and(N({type:x(`string`)})),bm.and(N({action:x(`accept`)})),N({action:x(`decline`)}),N({action:x(`cancel`)});const km=`$/cancel_request`;function Am(e){return typeof e==`object`&&!!e}function Ure(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Wre(e){if(!(!Am(e)||!Ure(e.requestId)))return e.requestId}const jm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Mm(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Gre(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Kre(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 Nm(e){if(e instanceof Im)return e.toResult();if(Kre(e))return Im.invalidParams(e.format()).toResult();let t=Gre(e);try{return Im.internalError(t?JSON.parse(t):{}).toResult()}catch{return Im.internalError({details:t}).toResult()}}function qre(e){return e instanceof Im&&e.code===-32800?e:Im.requestCancelled(e)}function Jre(e,t){let n=Yre(e,t);return n?n.toResult():Nm(e)}function Yre(e,t){if(!(!t.aborted||!Xre(e)))return qre(t.reason)}function Xre(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Zre=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 Im?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Mm(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Pm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Qre=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}},Fm=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Qre(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 $re}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 Pm(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return Mm(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification(km,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Mm(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return jm.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(!Am(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(Im.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Jre(n,t.responder.signal));else{let t=Nm(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 Zre(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&&Am(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new Im(n,r,i))}else t.reject(Im.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==km)return;let t=Wre(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(Im.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Mm(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},$re=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)??jm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?jm.no(r):await n(t(r.params),r.responder,i)??jm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?jm.no(r):await n(t(r.params),i)??jm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Fm(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},Im=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}}},eie=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 tie(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new eie,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Am(t)?e.enqueue(t):console.warn(`Skipping JSON line that is not an object:`,n)}catch(e){console.error(`Failed to parse JSON message:`,n,e)}},s=t.getReader();a=s;try{for(;;){let{value:e,done:t}=await s.read();if(i)return;if(t)break;if(e){for(let t of n.push(e))if(o(t),i)return}}if(i)return;let e=n.flush();e&&o(e)}catch(t){if(i)return;e.error(t);return}finally{a===s&&(a=void 0),s.releaseLock()}i||e.close()},cancel(e){return i=!0,a?.cancel(e)}}),writable:new WritableStream({async write(t){let r=JSON.stringify(t)+`
5
5
  `,i=e.getWriter();try{await i.write(n.encode(r))}finally{i.releaseLock()}}})}}function Lm(e){return e??{}}function nie(e){return typeof e==`object`&&!!e&&`readable`in e&&`writable`in e}function rie(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}const Rm={agent:{initialize:U.initialize,authenticate:U.authenticate,logout:U.logout,providers:{list:U.providers_list,set:U.providers_set,disable:U.providers_disable},session:{new:U.session_new,load:U.session_load,list:U.session_list,delete:U.session_delete,fork:U.session_fork,resume:U.session_resume,close:U.session_close,setMode:U.session_set_mode,setConfigOption:U.session_set_config_option,prompt:U.session_prompt,cancel:U.session_cancel},nes:{start:U.nes_start,suggest:U.nes_suggest,accept:U.nes_accept,reject:U.nes_reject,close:U.nes_close},document:{didOpen:U.document_did_open,didChange:U.document_did_change,didClose:U.document_did_close,didSave:U.document_did_save,didFocus:U.document_did_focus}},client:{session:{requestPermission:Dd.session_request_permission,update:Dd.session_update},fs:{writeTextFile:Dd.fs_write_text_file,readTextFile:Dd.fs_read_text_file},terminal:{create:Dd.terminal_create,output:Dd.terminal_output,release:Dd.terminal_release,waitForExit:Dd.terminal_wait_for_exit,kill:Dd.terminal_kill},elicitation:{create:Dd.elicitation_create,complete:Dd.elicitation_complete}},protocol:{cancelRequest:Od.cancel_request}},zm=Symbol(`startActiveSession`);var Bm=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},iie=class e extends Bm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}request(e,t,n){let r=Ym[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},Vm=class e extends Bm{constructor(e,t){super(e,t)}static create(t,n){return new e(t,n)}[zm](e,t){return this.sendRequest(U.session_new,e,e=>this.attachSession(e),t)}buildSession(e){return typeof e==`string`?Wm.create(this,{cwd:e,mcpServers:[]}):Wm.create(this,e)}attachSession(e){let t=new lie,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error(`ACP connection closed`))};n.aborted?r():n.addEventListener(`abort`,r);let i=Zm(this.connectionContext).attach(e,t),a=new Pm(()=>{n.removeEventListener(`abort`,r)});return uie.create(this,e,t,[i,a])}request(e,t,n){let r=_ie[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}},Hm=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},aie=class extends Hm{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=iie.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Qm(this,this.connectHandlers))}},oie=class extends Hm{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=Vm.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Qm(this,this.connectHandlers))}};function sie(e,t=[]){return new aie(e,t)}function cie(e,t=[]){return new oie(e,t)}var lie=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:`value`,value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:`error`,error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind===`value`)}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind===`error`?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function Um(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}var Wm=class e{cx;request;constructor(e,t){this.cx=e,this.request=Um(t)}static create(t,n){return new e(t,n)}toRequest(){return Um(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[zm](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},uie=class e{cx;sessionResponse;updates;registrations;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r}static create(t,n,r,i){return new e(t,n,r,i)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let n=this.cx.request(U.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return n.then(e=>{this.updates.enqueue({kind:`stop`,response:e,stopReason:e.stopReason})},e=>{this.updates.reject(e)}),n}nextUpdate(){return this.updates.next()}async readText(){let e=``;for(;;){let t=await this.nextUpdate();if(t.kind===`stop`)return e;let{update:n}=t;n.sessionUpdate===`agent_message_chunk`&&n.content.type===`text`&&(e+=n.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error(`Active session disposed`))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e==`string`?[{type:`text`,text:e}]:Array.isArray(e)?e:[e]}};function Gm(e,t){return e?typeof e==`function`?e(t):e.parse(t):t}function Km(e,t,n){return{method:e,params:t,mapResponse:n}}function qm(e,t){return{method:e,params:t}}function die(e,t,n,r){e.onReceiveRequest(t.method,e=>Gm(t.params,e),async(e,i,a)=>{let o=await r(n(e,a,i.signal,i.id));await i.respond(t.mapResponse?t.mapResponse(o):o)})}function fie(e,t,n,r){e.onReceiveNotification(t.method,e=>Gm(t.params,e),(e,t)=>r(n(e,t,t.signal)))}function Jm(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}const pie={initialize:Km(U.initialize,$p),newSession:Km(U.session_new,sm),loadSession:Km(U.session_load,cm,Lm),unstable_forkSession:Km(U.session_fork,dm),listSessions:Km(U.session_list,lm),deleteSession:Km(U.session_delete,um,Lm),resumeSession:Km(U.session_resume,fm),closeSession:Km(U.session_close,pm,Lm),setSessionMode:Km(U.session_set_mode,mm,Lm),setSessionConfigOption:Km(U.session_set_config_option,hm),authenticate:Km(U.authenticate,em,Lm),unstable_listProviders:Km(U.providers_list,tm),unstable_setProvider:Km(U.providers_set,nm,Lm),unstable_disableProvider:Km(U.providers_disable,rm,Lm),logout:Km(U.logout,im,Lm),prompt:Km(U.session_prompt,gm),unstable_startNes:Km(U.nes_start,_m),unstable_suggestNes:Km(U.nes_suggest,vm),unstable_closeNes:Km(U.nes_close,ym,Lm)},mie={cancel:qm(U.session_cancel,xm),unstable_didOpenDocument:qm(U.document_did_open,Sm),unstable_didChangeDocument:qm(U.document_did_change,Cm),unstable_didCloseDocument:qm(U.document_did_close,wm),unstable_didSaveDocument:qm(U.document_did_save,Tm),unstable_didFocusDocument:qm(U.document_did_focus,Em),unstable_acceptNes:qm(U.nes_accept,Dm),unstable_rejectNes:qm(U.nes_reject,Om)},hie={requestPermission:Km(Dd.session_request_permission,Yd),writeTextFile:Km(Dd.fs_write_text_file,Ld,Lm),readTextFile:Km(Dd.fs_read_text_file,Rd),createTerminal:Km(Dd.terminal_create,Zd),terminalOutput:Km(Dd.terminal_output,Qd),releaseTerminal:Km(Dd.terminal_release,$d,Lm),waitForTerminalExit:Km(Dd.terminal_wait_for_exit,ef),killTerminal:Km(Dd.terminal_kill,tf,Lm),unstable_createElicitation:Km(Dd.elicitation_create,hf)},gie={sessionUpdate:qm(Dd.session_update,Yp),unstable_completeElicitation:qm(Dd.elicitation_complete,Xp)},_ie=Jm(pie);Jm(mie);const Ym=Jm(hie),vie=Jm(gie);function yie(e,t,n,r){return{params:e,requestId:r,signal:n,agent:t}}function bie(e,t,n){return{params:e,signal:n,agent:t}}var xie=class{activeSessions=new Map;handleMessage(e){if(e.kind!==`notification`||e.method!==Dd.session_update)return jm.no(e);let t=Yp.parse(e.params),n={kind:`session_update`,notification:t,update:t.update},r=this.activeSessions.get(t.sessionId);if(r&&r.size>0)for(let e of r)e.enqueue(n);return jm.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new Pm(()=>{n.delete(t),n.size===0&&this.activeSessions.delete(e.sessionId)})}};const Xm=new WeakMap;function Zm(e){let t=Xm.get(e);return t||(t=new xie,Xm.set(e,t)),t}function Qm(e,t){for(let n of t){let t;try{t=n(e)}catch(t){throw e.close(t),t}Promise.resolve(t).catch(t=>{e.close(t)})}}const $m=Symbol(`appBuilder`),Sie=Symbol(`runAgentConnectHandlers`),eh=Symbol(`runClientConnectHandlers`);function Cie(e){return new wie(e)}var wie=class{builder=Fm.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(e,t)=>Zm(t).handleMessage(e),describe:()=>`client-session-update-router`})}[$m](){return this.builder}[eh](e){Qm(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(n)return this.request({method:e,params:t},n);let r=Ym[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(r,t)}onNotification(e,t,n){if(n)return this.notification({method:e,params:t},n);let r=vie[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return die(this.builder,e,(e,t,n,r)=>yie(e,Vm.create(t,r),n,r),t),this}notification(e,t){return fie(this.builder,e,(e,t,n)=>bie(e,Vm.create(t),n),t),this}connectConnection(e){if(nie(e)){let t=this.openStreamConnection(e);return this[eh](t.connection),t}let[t,n]=rie(),r=e[$m]().connect(n),i=sie(r),a=this.openStreamConnection(t);a.rawConnection.closed.then(()=>i.close()),r.closed.then(()=>a.connection.close());try{e[Sie](i),this[eh](a.connection)}catch(e){throw i.close(e),a.connection.close(e),e}return a}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:cie(t,this.connectHandlers)}}};new Set([U.initialize,U.authenticate,U.providers_list,U.providers_set,U.providers_disable,U.session_new,U.session_load,U.session_set_mode,U.session_set_config_option,U.session_prompt,U.session_list,U.session_delete,U.session_fork,U.session_resume,U.session_close,U.logout,U.nes_start,U.nes_suggest,U.nes_close]),new Set([U.session_cancel,U.nes_accept,U.nes_reject,U.document_did_open,U.document_did_change,U.document_did_close,U.document_did_save,U.document_did_focus]),new Set([Dd.session_request_permission,Dd.fs_write_text_file,Dd.fs_read_text_file,Dd.terminal_create,Dd.terminal_output,Dd.terminal_release,Dd.terminal_wait_for_exit,Dd.terminal_kill,Dd.elicitation_create]),new Set([Dd.session_update,Dd.elicitation_complete]);function th(e){return e.replace(/[<>\r\n]/g,``).trim().slice(0,128)}const nh=/^[a-zA-Z0-9_-]+$/,Tie=64;function rh(e){return typeof e!=`string`||e.length===0||e.length>64||!nh.test(e)?null:e}function ih(e){return e.startsWith(`agent-`)?e:`agent-${e}`}function ah(e){return!e.startsWith(`principal-`)}function oh(e){if(!e)return`bot`;let t=e.toLowerCase();return t.includes(`claude`)||t.startsWith(`local-agent-mode-`)?`claude`:t.includes(`cursor`)?`cursor`:t.includes(`codex`)?`codex`:t.includes(`cline`)?`cline`:t.includes(`windsurf`)?`windsurf`:`bot`}function sh(e){let t=rh(typeof e.agentId==`string`?e.agentId:null)??void 0;return{rawAgentId:t,writerId:t===void 0?void 0:ih(t),displayName:typeof e.agentName==`string`?th(e.agentName):`Claude`,clientName:typeof e.clientName==`string`?th(e.clientName):void 0,clientVersion:typeof e.clientVersion==`string`?th(e.clientVersion):void 0,label:typeof e.label==`string`?th(e.label):void 0,colorSeed:typeof e.colorSeed==`string`&&e.colorSeed.length>0?e.colorSeed.slice(0,128):void 0}}function ch(e){let t=jt(e);return t.frontmatter===``?t:En(Xt(t.frontmatter)).map===null?{frontmatter:``,body:e}:t}const lh=()=>new Map,uh=e=>{let t=lh();return e.forEach((e,n)=>{t.set(n,e)}),t},dh=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r},fh=(e,t)=>{for(let[n,r]of e)if(t(r,n))return!0;return!1},ph=()=>new Set,mh=e=>e[e.length-1],hh=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},gh=Array.from,_h=(e,t)=>{for(let n=0;n<e.length;n++)if(t(e[n],n,e))return!0;return!1},vh=Array.isArray;var yh=class{constructor(){this._observers=lh()}on(e,t){return dh(this._observers,e,ph).add(t),t}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return gh((this._observers.get(e)||lh()).values()).forEach(e=>e(...t))}destroy(){this._observers=lh()}};const bh=Math.floor,xh=Math.abs,Sh=(e,t)=>e<t?e:t,Ch=(e,t)=>e>t?e:t;Number.isNaN;const wh=e=>e===0?1/e<0:e<0,Th=2**53-1,Eh=Number.isInteger||(e=>typeof e==`number`&&isFinite(e)&&bh(e)===e);Number.isNaN,Number.parseInt;const Dh=String.fromCharCode;String.fromCodePoint,Dh(65535);const Oh=e=>e.toLowerCase(),kh=/^\s*/g,Ah=e=>e.replace(kh,``),jh=/([A-Z])/g,Mh=(e,t)=>Ah(e.replace(jh,e=>`${t}${Oh(e)}`)),Nh=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},Ph=typeof TextEncoder<`u`?new TextEncoder:null,Fh=Ph?e=>Ph.encode(e):Nh;let Ih=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});Ih&&Ih.decode(new Uint8Array).length===1&&(Ih=null);var Lh=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Rh=()=>new Lh,zh=e=>{let t=Rh();return e(t),Vh(t)},Bh=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},Vh=e=>{let t=new Uint8Array(Bh(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Hh=(e,t)=>{let n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(Ch(n,t)*2),e.cpos=0)},Uh=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},Wh=Uh,Gh=(e,t)=>{for(;t>127;)Uh(e,128|127&t),t=bh(t/128);Uh(e,127&t)},Kh=(e,t)=>{let n=wh(t);for(n&&(t=-t),Uh(e,(t>63?128:0)|(n?64:0)|63&t),t=bh(t/64);t>0;)Uh(e,(t>127?128:0)|127&t),t=bh(t/128)},qh=new Uint8Array(3e4),Jh=qh.length/3,Yh=Ph&&Ph.encodeInto?(e,t)=>{if(t.length<Jh){let n=Ph.encodeInto(t,qh).written||0;Gh(e,n);for(let t=0;t<n;t++)Uh(e,qh[t])}else Zh(e,Fh(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;Gh(e,r);for(let t=0;t<r;t++)Uh(e,n.codePointAt(t))},Xh=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=Sh(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Ch(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},Zh=(e,t)=>{Gh(e,t.byteLength),Xh(e,t)},Qh=(e,t)=>{Hh(e,t);let n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},$h=(e,t)=>Qh(e,4).setFloat32(0,t,!1),eg=(e,t)=>Qh(e,8).setFloat64(0,t,!1),tg=(e,t)=>Qh(e,8).setBigInt64(0,t,!1),ng=new DataView(new ArrayBuffer(4)),rg=e=>(ng.setFloat32(0,e),ng.getFloat32(0)===e),ig=(e,t)=>{switch(typeof t){case`string`:Uh(e,119),Yh(e,t);break;case`number`:Eh(t)&&xh(t)<=2147483647?(Uh(e,125),Kh(e,t)):rg(t)?(Uh(e,124),$h(e,t)):(Uh(e,123),eg(e,t));break;case`bigint`:Uh(e,122),tg(e,t);break;case`object`:if(t===null)Uh(e,126);else if(vh(t)){Uh(e,117),Gh(e,t.length);for(let n=0;n<t.length;n++)ig(e,t[n])}else if(t instanceof Uint8Array)Uh(e,116),Zh(e,t);else{Uh(e,118);let n=Object.keys(t);Gh(e,n.length);for(let r=0;r<n.length;r++){let i=n[r];Yh(e,i),ig(e,t[i])}}break;case`boolean`:Uh(e,t?120:121);break;default:Uh(e,127)}};var ag=class extends Lh{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Gh(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}};const og=e=>{e.count>0&&(Kh(e.encoder,e.count===1?e.s:-e.s),e.count>1&&Gh(e.encoder,e.count-2))};var sg=class{constructor(){this.encoder=new Lh,this.s=0,this.count=0}write(e){this.s===e?this.count++:(og(this),this.count=1,this.s=e)}toUint8Array(){return og(this),Vh(this.encoder)}};const cg=e=>{if(e.count>0){let t=e.diff*2+(e.count===1?0:1);Kh(e.encoder,t),e.count>1&&Gh(e.encoder,e.count-2)}};var lg=class{constructor(){this.encoder=new Lh,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(cg(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return cg(this),Vh(this.encoder)}},ug=class{constructor(){this.sarr=[],this.s=``,this.lensE=new sg}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=``),this.lensE.write(e.length)}toUint8Array(){let e=new Lh;return this.sarr.push(this.s),this.s=``,Yh(e,this.sarr.join(``)),Xh(e,this.lensE.toUint8Array()),Vh(e)}};const dg=e=>Error(e),fg=()=>{throw dg(`Method unimplemented`)},pg=()=>{throw dg(`Unexpected case`)},mg=dg(`Unexpected end of array`),hg=dg(`Integer out of Range`);var gg=class{constructor(e){this.arr=e,this.pos=0}};const _g=e=>new gg(e),vg=e=>e.pos!==e.arr.length,yg=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},bg=e=>yg(e,Sg(e)),xg=e=>e.arr[e.pos++],Sg=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>Th)throw hg}throw mg},Cg=e=>{let t=e.arr[e.pos++],n=t&63,r=64,i=(t&64)>0?-1:1;if(!(t&128))return i*n;let a=e.arr.length;for(;e.pos<a;){if(t=e.arr[e.pos++],n+=(t&127)*r,r*=128,t<128)return i*n;if(n>Th)throw hg}throw mg},wg=Ih?e=>Ih.decode(bg(e)):e=>{let t=Sg(e);if(t===0)return``;{let n=String.fromCodePoint(xg(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(xg(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},Tg=(e,t)=>{let n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Eg=[e=>void 0,e=>null,Cg,e=>Tg(e,4).getFloat32(0,!1),e=>Tg(e,8).getFloat64(0,!1),e=>Tg(e,8).getBigInt64(0,!1),e=>!1,e=>!0,wg,e=>{let t=Sg(e),n={};for(let r=0;r<t;r++){let t=wg(e);n[t]=Dg(e)}return n},e=>{let t=Sg(e),n=[];for(let r=0;r<t;r++)n.push(Dg(e));return n},bg],Dg=e=>Eg[127-xg(e)](e);var Og=class extends gg{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return this.count===0&&(this.s=this.reader(this),vg(this)?this.count=Sg(this)+1:this.count=-1),this.count--,this.s}},kg=class extends gg{constructor(e){super(e),this.s=0,this.count=0}read(){if(this.count===0){this.s=Cg(this);let e=wh(this.s);this.count=1,e&&(this.s=-this.s,this.count=Sg(this)+2)}return this.count--,this.s}},Ag=class extends gg{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(this.count===0){let e=Cg(this),t=e&1;this.diff=bh(e/2),this.count=1,t&&(this.count=Sg(this)+2)}return this.s+=this.diff,this.count--,this.s}},jg=class{constructor(e){this.decoder=new kg(e),this.str=wg(this.decoder),this.spos=0}read(){let e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}};Tu.subtle;const Mg=Tu.getRandomValues.bind(Tu),Ng=()=>Mg(new Uint32Array(1))[0],Pg=()=>`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^Ng()&15>>e/4).toString(16)),Fg=Date.now,Ig=e=>new Promise(e);Promise.all.bind(Promise);const Lg=e=>e===void 0?null:e;let Rg=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}};try{typeof localStorage<`u`&&localStorage&&(Rg=localStorage)}catch{}const zg=Rg,Bg=Symbol(`Equality`),Vg=(e,t)=>e===t||!!e?.[Bg]?.(t)||!1,Hg=Object.assign,Ug=Object.keys,Wg=(e,t)=>{for(let n in e)t(e[n],n)},Gg=e=>Ug(e).length,Kg=e=>{for(let t in e)return!1;return!0},qg=(e,t)=>{for(let n in e)if(!t(e[n],n))return!1;return!0},Jg=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Yg=(e,t)=>e===t||Gg(e)===Gg(t)&&qg(e,(e,n)=>(e!==void 0||Jg(t,n))&&Vg(t[n],e)),Xg=Object.freeze,Zg=e=>{for(let t in e){let n=e[t];(typeof n==`object`||typeof n==`function`)&&Zg(e[t])}return Xg(e)},Qg=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Qg(e,t,n+1)}},$g=e=>e,e_=(e,t)=>t.includes(e),t_=typeof process<`u`&&process.release&&/node|io\.js/.test(process.release.name)&&Object.prototype.toString.call(typeof process<`u`?process:0)===`[object process]`,n_=typeof window<`u`&&typeof document<`u`&&!t_;typeof navigator<`u`&&/Mac/.test(navigator.platform);let r_;const i_=[],a_=()=>{if(r_===void 0)if(t_){r_=lh();let e=process.argv,t=null;for(let n=0;n<e.length;n++){let r=e[n];r[0]===`-`?(t!==null&&r_.set(t,``),t=r):t===null?i_.push(r):(r_.set(t,r),t=null)}t!==null&&r_.set(t,``)}else typeof location==`object`?(r_=lh(),(location.search||`?`).slice(1).split(`&`).forEach(e=>{if(e.length!==0){let[t,n]=e.split(`=`);r_.set(`--${Mh(t,`-`)}`,n),r_.set(`-${Mh(t,`-`)}`,n)}})):r_=lh();return r_},o_=e=>a_().has(e),s_=e=>Lg(t_?process.env[e.toUpperCase().replaceAll(`-`,`_`)]:zg.getItem(e)),c_=e=>o_(`--`+e)||s_(e)!==null;c_(`production`);const l_=t_&&e_(process.env.FORCE_COLOR,[`true`,`1`,`2`])||!o_(`--no-colors`)&&!c_(`no-color`)&&(!t_||process.stdout.isTTY)&&(!t_||o_(`--color`)||s_(`COLORTERM`)!==null||(s_(`TERM`)||``).includes(`color`)),u_=e=>new Uint8Array(e),d_=n_?e=>{let t=``;for(let n=0;n<e.byteLength;n++)t+=Dh(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString(`base64`),f_=e=>{let t=u_(e.byteLength);return t.set(e),t},p_=e=>zh(t=>ig(t,e)),m_=Symbol,h_=m_(),g_=m_(),__=m_(),v_=m_(),y_=m_(),b_=m_(),x_=m_(),S_=m_(),C_=m_(),w_=e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r];if(n===void 0)break;if(n.constructor===String||n.constructor===Number)t.push(n);else if(n.constructor===Object)break}for(r>0&&n.push(t.join(``));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n};Fg();const T_={[h_]:`\x1B[1m`,[g_]:`\x1B[2m`,[__]:`\x1B[34m`,[y_]:`\x1B[32m`,[v_]:`\x1B[37m`,[b_]:`\x1B[31m`,[x_]:`\x1B[35m`,[S_]:`\x1B[38;5;208m`,[C_]:`\x1B[0m`},E_=l_?e=>{e.length===1&&e[0]?.constructor===Function&&(e=e[0]());let t=[],n=[],r=0;for(;r<e.length;r++){let n=e[r],i=T_[n];if(i!==void 0)t.push(i);else if(n===void 0)break;else if(n.constructor===String||n.constructor===Number)t.push(n);else break}for(r>0&&(t.push(`\x1B[0m`),n.push(t.join(``)));r<e.length;r++){let t=e[r];t instanceof Symbol||n.push(t)}return n}:w_,D_=(...e)=>{console.log(...E_(e))},O_=(...e)=>{console.warn(...E_(e))},k_=e=>({[Symbol.iterator](){return this},next:e}),A_=(e,t)=>k_(()=>{let n;do n=e.next();while(!n.done&&!t(n.value));return n}),j_=(e,t)=>k_(()=>{let{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});var M_=class{constructor(e,t){this.clock=e,this.len=t}},N_=class{constructor(){this.clients=new Map}};const P_=(e,t,n)=>t.clients.forEach((t,r)=>{let i=e.doc.store.clients.get(r);if(i!=null){let r=i[i.length-1],a=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<a;o=t[++r])Wv(e,i,o.clock,o.len,n)}}),F_=(e,t)=>{let n=0,r=e.length-1;for(;n<=r;){let i=bh((n+r)/2),a=e[i],o=a.clock;if(o<=t){if(t<o+a.len)return i;n=i+1}else r=i-1}return null},I_=(e,t)=>{let n=e.clients.get(t.client);return n!==void 0&&F_(n,t.clock)!==null},L_=e=>{e.clients.forEach(e=>{e.sort((e,t)=>e.clock-t.clock);let t,n;for(t=1,n=1;t<e.length;t++){let r=e[n-1],i=e[t];r.clock+r.len>=i.clock?e[n-1]=new M_(r.clock,Ch(r.len,i.clock+i.len-r.clock)):(n<t&&(e[n]=i),n++)}e.length=n})},R_=e=>{let t=new N_;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,i)=>{if(!t.clients.has(i)){let a=r.slice();for(let t=n+1;t<e.length;t++)hh(a,e[t].clients.get(i)||[]);t.clients.set(i,a)}});return L_(t),t},z_=(e,t,n,r)=>{dh(e.clients,t,()=>[]).push(new M_(n,r))},B_=()=>new N_,V_=e=>{let t=B_();return e.clients.forEach((e,n)=>{let r=[];for(let t=0;t<e.length;t++){let n=e[t];if(n.deleted){let i=n.id.clock,a=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[++t+1])a+=n.length;r.push(new M_(i,a))}}r.length>0&&t.clients.set(n,r)}),t},H_=(e,t)=>{Gh(e.restEncoder,t.clients.size),gh(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),Gh(e.restEncoder,t);let r=n.length;Gh(e.restEncoder,r);for(let t=0;t<r;t++){let r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},U_=e=>{let t=new N_,n=Sg(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();let n=Sg(e.restDecoder),r=Sg(e.restDecoder);if(r>0){let i=dh(t.clients,n,()=>[]);for(let t=0;t<r;t++)i.push(new M_(e.readDsClock(),e.readDsLen()))}}return t},W_=(e,t,n)=>{let r=new N_,i=Sg(e.restDecoder);for(let a=0;a<i;a++){e.resetDsCurVal();let i=Sg(e.restDecoder),a=Sg(e.restDecoder),o=n.clients.get(i)||[],s=Lv(n,i);for(let n=0;n<a;n++){let n=e.readDsClock(),a=n+e.readDsLen();if(n<s){s<a&&z_(r,i,s,a-s);let e=zv(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,ab(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<a);)c.deleted||(a<c.id.clock+c.length&&o.splice(e,0,ab(t,c,a-c.id.clock)),c.delete(t))}else z_(r,i,n,a-n)}}if(r.clients.size>0){let e=new tv;return Gh(e.restEncoder,0),H_(e,r),e.toUint8Array()}return null},G_=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(let[n,r]of e.clients.entries()){let e=t.clients.get(n);if(e===void 0||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},K_=Ng;var q_=class e extends yh{constructor({guid:e=Pg(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:i=null,autoLoad:a=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=K_(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Fv,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=a,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ig(e=>{this.on(`load`,()=>{this.isLoaded=!0,e(this)})});let s=()=>Ig(e=>{let t=n=>{(n===void 0||n===!0)&&(this.off(`sync`,t),e())};this.on(`sync`,t)});this.on(`sync`,e=>{e===!1&&this.isSynced&&(this.whenSynced=s()),this.isSynced=e===void 0||e===!0,this.isSynced&&!this.isLoaded&&this.emit(`load`,[this])}),this.whenSynced=s()}load(){let e=this._item;e!==null&&!this.shouldLoad&&Yv(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(gh(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Yv(this,e,t)}get(e,t=fy){let n=dh(this.share,e,()=>{let e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==fy&&r!==t)if(r===fy){let r=new t;r._map=n._map,n._map.forEach(e=>{for(;e!==null;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;e!==null;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}else throw Error(`Type with the name ${e} has already been defined with a different constructor`);return n}getArray(e=``){return this.get(e,Oy)}getText(e=``){return this.get(e,Hy)}getMap(e=``){return this.get(e,ky)}getXmlElement(e=``){return this.get(e,Gy)}getXmlFragment(e=``){return this.get(e,Wy)}toJSON(){let e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,gh(this.subdocs).forEach(e=>e.destroy());let t=this._item;if(t!==null){this._item=null;let n=t.content;n.doc=new e({guid:this.guid,...n.opts,shouldLoad:!1}),n.doc._item=t,Yv(t.parent.doc,e=>{let r=n.doc;t.deleted||e.subdocsAdded.add(r),e.subdocsRemoved.add(this)},null,!0)}this.emit(`destroyed`,[!0]),this.emit(`destroy`,[this]),super.destroy()}},J_=class{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Sg(this.restDecoder)}readDsLen(){return Sg(this.restDecoder)}},Y_=class extends J_{readLeftID(){return Ev(Sg(this.restDecoder),Sg(this.restDecoder))}readRightID(){return Ev(Sg(this.restDecoder),Sg(this.restDecoder))}readClient(){return Sg(this.restDecoder)}readInfo(){return xg(this.restDecoder)}readString(){return wg(this.restDecoder)}readParentInfo(){return Sg(this.restDecoder)===1}readTypeRef(){return Sg(this.restDecoder)}readLen(){return Sg(this.restDecoder)}readAny(){return Dg(this.restDecoder)}readBuf(){return f_(bg(this.restDecoder))}readJSON(){return JSON.parse(wg(this.restDecoder))}readKey(){return wg(this.restDecoder)}},X_=class{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Sg(this.restDecoder),this.dsCurrVal}readDsLen(){let e=Sg(this.restDecoder)+1;return this.dsCurrVal+=e,e}},Z_=class extends X_{constructor(e){super(e),this.keys=[],Sg(e),this.keyClockDecoder=new Ag(bg(e)),this.clientDecoder=new kg(bg(e)),this.leftClockDecoder=new Ag(bg(e)),this.rightClockDecoder=new Ag(bg(e)),this.infoDecoder=new Og(bg(e),xg),this.stringDecoder=new jg(bg(e)),this.parentInfoDecoder=new Og(bg(e),xg),this.typeRefDecoder=new kg(bg(e)),this.lenDecoder=new kg(bg(e))}readLeftID(){return new wv(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new wv(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return this.parentInfoDecoder.read()===1}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return Dg(this.restDecoder)}readBuf(){return bg(this.restDecoder)}readJSON(){return Dg(this.restDecoder)}readKey(){let e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{let e=this.stringDecoder.read();return this.keys.push(e),e}}},Q_=class{constructor(){this.restEncoder=Rh()}toUint8Array(){return Vh(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Gh(this.restEncoder,e)}writeDsLen(e){Gh(this.restEncoder,e)}},$_=class extends Q_{writeLeftID(e){Gh(this.restEncoder,e.client),Gh(this.restEncoder,e.clock)}writeRightID(e){Gh(this.restEncoder,e.client),Gh(this.restEncoder,e.clock)}writeClient(e){Gh(this.restEncoder,e)}writeInfo(e){Wh(this.restEncoder,e)}writeString(e){Yh(this.restEncoder,e)}writeParentInfo(e){Gh(this.restEncoder,+!!e)}writeTypeRef(e){Gh(this.restEncoder,e)}writeLen(e){Gh(this.restEncoder,e)}writeAny(e){ig(this.restEncoder,e)}writeBuf(e){Zh(this.restEncoder,e)}writeJSON(e){Yh(this.restEncoder,JSON.stringify(e))}writeKey(e){Yh(this.restEncoder,e)}},ev=class{constructor(){this.restEncoder=Rh(),this.dsCurrVal=0}toUint8Array(){return Vh(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){let t=e-this.dsCurrVal;this.dsCurrVal=e,Gh(this.restEncoder,t)}writeDsLen(e){e===0&&pg(),Gh(this.restEncoder,e-1),this.dsCurrVal+=e}},tv=class extends ev{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new lg,this.clientEncoder=new sg,this.leftClockEncoder=new lg,this.rightClockEncoder=new lg,this.infoEncoder=new ag(Wh),this.stringEncoder=new ug,this.parentInfoEncoder=new ag(Wh),this.typeRefEncoder=new sg,this.lenEncoder=new sg}toUint8Array(){let e=Rh();return Gh(e,0),Zh(e,this.keyClockEncoder.toUint8Array()),Zh(e,this.clientEncoder.toUint8Array()),Zh(e,this.leftClockEncoder.toUint8Array()),Zh(e,this.rightClockEncoder.toUint8Array()),Zh(e,Vh(this.infoEncoder)),Zh(e,this.stringEncoder.toUint8Array()),Zh(e,Vh(this.parentInfoEncoder)),Zh(e,this.typeRefEncoder.toUint8Array()),Zh(e,this.lenEncoder.toUint8Array()),Xh(e,Vh(this.restEncoder)),Vh(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(+!!e)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){ig(this.restEncoder,e)}writeBuf(e){Zh(this.restEncoder,e)}writeJSON(e){ig(this.restEncoder,e)}writeKey(e){let t=this.keyMap.get(e);t===void 0?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}};const nv=(e,t,n,r)=>{r=Ch(r,t[0].id.clock);let i=zv(t,r);Gh(e.restEncoder,t.length-i),e.writeClient(n),Gh(e.restEncoder,r);let a=t[i];a.write(e,r-a.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)},rv=(e,t,n)=>{let r=new Map;n.forEach((e,n)=>{Lv(t,n)>e&&r.set(n,e)}),Iv(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),Gh(e.restEncoder,r.size),gh(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{nv(e,t.clients.get(n),n,r)})},iv=(e,t)=>{let n=lh(),r=Sg(e.restDecoder);for(let i=0;i<r;i++){let r=Sg(e.restDecoder),i=Array(r),a=e.readClient(),o=Sg(e.restDecoder);n.set(a,{i:0,refs:i});for(let n=0;n<r;n++){let r=e.readInfo();switch(31&r){case 0:{let t=e.readLen();i[n]=new Jy(Ev(a,o),t),o+=t;break}case 10:{let t=Sg(e.restDecoder);i[n]=new ub(Ev(a,o),t),o+=t;break}default:{let s=(r&192)==0,c=new cb(Ev(a,o),null,(r&128)==128?e.readLeftID():null,null,(r&64)==64?e.readRightID():null,s?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,s&&(r&32)==32?e.readString():null,lb(e,r));i[n]=c,o+=c.length}}}}return n},av=(e,t,n)=>{let r=[],i=gh(n.keys()).sort((e,t)=>e-t);if(i.length===0)return null;let a=()=>{if(i.length===0)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;)if(i.pop(),i.length>0)e=n.get(i[i.length-1]);else return null;return e},o=a();if(o===null)return null;let s=new Fv,c=new Map,l=(e,t)=>{let n=c.get(e);(n==null||n>t)&&c.set(e,t)},u=o.refs[o.i++],d=new Map,f=()=>{for(let e of r){let t=e.id.client,r=n.get(t);r?(r.i--,s.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):s.clients.set(t,[e]),i=i.filter(e=>e!==t)}r.length=0};for(;;){if(u.constructor!==ub){let i=dh(d,u.id.client,()=>Lv(t,u.id.client))-u.id.clock;if(i<0)r.push(u),l(u.id.client,u.id.clock-1),f();else{let a=u.getMissing(e,t);if(a!==null){r.push(u);let e=n.get(a)||{refs:[],i:0};if(e.refs.length===e.i)l(a,Lv(t,a)),f();else{u=e.refs[e.i++];continue}}else (i===0||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(o!==null&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=a(),o===null)break;u=o.refs[o.i++]}}if(s.clients.size>0){let e=new tv;return rv(e,s,new Map),Gh(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null},ov=(e,t)=>rv(e,t.doc.store,t.beforeState),sv=(e,t,n,r=new Z_(e))=>Yv(t,e=>{e.local=!1;let t=!1,n=e.doc,i=n.store,a=av(e,i,iv(r,n)),o=i.pendingStructs;if(o){for(let[e,n]of o.missing)if(n<Lv(i,e)){t=!0;break}if(a){for(let[e,t]of a.missing){let n=o.missing.get(e);(n==null||n>t)&&o.missing.set(e,t)}o.update=ey([o.update,a.update])}}else i.pendingStructs=a;let s=W_(r,e,i);if(i.pendingDs){let t=new Z_(_g(i.pendingDs));Sg(t.restDecoder);let n=W_(t,e,i);s&&n?i.pendingDs=ey([s,n]):i.pendingDs=s||n}else i.pendingDs=s;if(t){let t=i.pendingStructs.update;i.pendingStructs=null,cv(e.doc,t)}},n,!1),cv=(e,t,n,r=Z_)=>{let i=_g(t);sv(i,e,n,new r(i))},lv=(e,t,n)=>cv(e,t,n,Y_),uv=(e,t,n=new Map)=>{rv(e,t.store,n),H_(e,V_(t.store))},dv=(e,t=new Uint8Array([0]),n=new tv)=>{uv(n,e,mv(t));let r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Iie(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===$_)return Pie(r.map((e,t)=>t===0?e:Rie(e)));if(n.constructor===tv)return ey(r)}return r[0]},fv=(e,t)=>dv(e,t,new $_),pv=e=>{let t=new Map,n=Sg(e.restDecoder);for(let r=0;r<n;r++){let n=Sg(e.restDecoder),r=Sg(e.restDecoder);t.set(n,r)}return t},mv=e=>pv(new J_(_g(e))),hv=(e,t)=>(Gh(e.restEncoder,t.size),gh(t.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{Gh(e.restEncoder,t),Gh(e.restEncoder,n)}),e),gv=(e,t)=>hv(e,Iv(t.store)),_v=(e,t=new ev)=>(e instanceof Map?hv(t,e):gv(t,e),t.toUint8Array()),vv=e=>_v(e,new Q_);var yv=class{constructor(){this.l=[]}};const bv=()=>new yv,xv=(e,t)=>e.l.push(t),Sv=(e,t)=>{let n=e.l,r=n.length;e.l=n.filter(e=>t!==e),r===e.l.length&&console.error(`[yjs] Tried to remove event handler that doesn't exist.`)},Cv=(e,t,n)=>Qg(e.l,[t,n]);var wv=class{constructor(e,t){this.client=e,this.clock=t}};const Tv=(e,t)=>e===t||e!==null&&t!==null&&e.client===t.client&&e.clock===t.clock,Ev=(e,t)=>new wv(e,t),Dv=e=>{for(let[t,n]of e.doc.share.entries())if(n===e)return t;throw pg()},Ov=(e,t)=>{for(;t!==null;){if(t.parent===e)return!0;t=t.parent._item}return!1};var kv=class{constructor(e,t){this.ds=e,this.sv=t}};const Av=(e,t)=>new kv(e,t);Av(B_(),new Map);const jv=e=>Av(V_(e.store),Iv(e.store)),Mv=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!I_(t.ds,e.id),Nv=(e,t)=>{let n=dh(e.meta,Nv,ph),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Lv(r,n)&&Hv(e,Ev(n,t))}),P_(e,t.ds,e=>{}),n.add(t))},Pv=(e,t,n=Z_)=>{let r=new n(_g(t)),i=new Qv(r,!1);for(let t=i.curr;t!==null;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;let a=R_([e.ds,U_(r)]);return G_(e.ds,a)},Eie=(e,t)=>Pv(e,t,Y_);var Fv=class{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}};const Iv=e=>{let t=new Map;return e.clients.forEach((e,n)=>{let r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},Lv=(e,t)=>{let n=e.clients.get(t);if(n===void 0)return 0;let r=n[n.length-1];return r.id.clock+r.length},Rv=(e,t)=>{let n=e.clients.get(t.id.client);if(n===void 0)n=[],e.clients.set(t.id.client,n);else{let e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw pg()}n.push(t)},zv=(e,t)=>{let n=0,r=e.length-1,i=e[r],a=i.id.clock;if(a===t)return r;let o=bh(t/(a+i.length-1)*r);for(;n<=r;){if(i=e[o],a=i.id.clock,a<=t){if(t<a+i.length)return o;n=o+1}else r=o-1;o=bh((n+r)/2)}throw pg()},Bv=(e,t)=>{let n=e.clients.get(t.client);return n[zv(n,t.clock)]},Vv=(e,t,n)=>{let r=zv(t,n),i=t[r];return i.id.clock<n&&i instanceof cb?(t.splice(r+1,0,ab(e,i,n-i.id.clock)),r+1):r},Hv=(e,t)=>{let n=e.doc.store.clients.get(t.client);return n[Vv(e,n,t.clock)]},Uv=(e,t,n)=>{let r=t.clients.get(n.client),i=zv(r,n.clock),a=r[i];return n.clock!==a.id.clock+a.length-1&&a.constructor!==Jy&&r.splice(i+1,0,ab(e,a,n.clock-a.id.clock+1)),a},Die=(e,t,n)=>{let r=e.clients.get(t.id.client);r[zv(r,t.id.clock)]=n},Wv=(e,t,n,r,i)=>{if(r===0)return;let a=n+r,o=Vv(e,t,n),s;do s=t[o++],a<s.id.clock+s.length&&Vv(e,t,a),i(s);while(o<t.length&&t[o].id.clock<a)};var Oie=class{constructor(e,t,n){this.doc=e,this.deleteSet=new N_,this.beforeState=Iv(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}};const Gv=(e,t)=>t.deleteSet.clients.size===0&&!fh(t.afterState,(e,n)=>t.beforeState.get(n)!==e)?!1:(L_(t.deleteSet),ov(e,t),H_(e,t.deleteSet),!0),Kv=(e,t,n)=>{let r=t._item;(r===null||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&dh(e.changed,t,ph).add(n)},qv=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0;n=r,r=e[--i-1]){if(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n)){n instanceof cb&&n.parentSub!==null&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);continue}break}let a=t-i;return a&&e.splice(t+1-a,a),a},kie=(e,t,n)=>{for(let[r,i]of e.clients.entries()){let e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){let a=i[r],o=a.clock+a.len;for(let r=zv(e,a.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){let i=e[r];if(a.clock+a.len<=i.id.clock)break;i instanceof cb&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Aie=(e,t)=>{e.clients.forEach((e,n)=>{let r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){let n=e[t],i=Sh(r.length-1,1+zv(r,n.clock+n.len-1));for(let e=i,t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+qv(r,e)}})},Jv=(e,t)=>{if(t<e.length){let n=e[t],r=n.doc,i=r.store,a=n.deleteSet,o=n._mergeStructs;try{L_(a),n.afterState=Iv(n.doc.store),r.emit(`beforeObserverCalls`,[n,r]);let e=[];n.changed.forEach((t,r)=>e.push(()=>{(r._item===null||!r._item.deleted)&&r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((t,r)=>{r._dEH.l.length>0&&(r._item===null||!r._item.deleted)&&(t=t.filter(e=>e.target._item===null||!e.target._item.deleted),t.forEach(e=>{e.currentTarget=r,e._path=null}),t.sort((e,t)=>e.path.length-t.path.length),e.push(()=>{Cv(r._dEH,t,n)}))}),e.push(()=>r.emit(`afterTransaction`,[n,r])),e.push(()=>{n._needFormattingCleanup&&$ie(n)})}),Qg(e,[])}finally{r.gc&&kie(a,i,r.gcFilter),Aie(a,i),n.afterState.forEach((e,t)=>{let r=n.beforeState.get(t)||0;if(r!==e){let e=i.clients.get(t),n=Ch(zv(e,r),1);for(let t=e.length-1;t>=n;)t-=1+qv(e,t)}});for(let e=o.length-1;e>=0;e--){let{client:t,clock:n}=o[e].id,r=i.clients.get(t),a=zv(r,n);a+1<r.length&&qv(r,a+1)>1||a>0&&qv(r,a)}if(!n.local&&n.afterState.get(r.clientID)!==n.beforeState.get(r.clientID)&&(D_(S_,h_,`[yjs] `,g_,b_,`Changed the client-id because another client seems to be using it.`),r.clientID=K_()),r.emit(`afterTransactionCleanup`,[n,r]),r._observers.has(`update`)){let e=new $_;Gv(e,n)&&r.emit(`update`,[e.toUint8Array(),n.origin,r,n])}if(r._observers.has(`updateV2`)){let e=new tv;Gv(e,n)&&r.emit(`updateV2`,[e.toUint8Array(),n.origin,r,n])}let{subdocsAdded:s,subdocsLoaded:c,subdocsRemoved:l}=n;(s.size>0||l.size>0||c.size>0)&&(s.forEach(e=>{e.clientID=r.clientID,e.collectionid??=r.collectionid,r.subdocs.add(e)}),l.forEach(e=>r.subdocs.delete(e)),r.emit(`subdocs`,[{loaded:c,added:s,removed:l},r,n]),l.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit(`afterAllTransactions`,[r,e])):Jv(e,t+1)}}},Yv=(e,t,n=null,r=!0)=>{let i=e._transactionCleanups,a=!1,o=null;e._transaction===null&&(a=!0,e._transaction=new Oie(e,n,r),i.push(e._transaction),i.length===1&&e.emit(`beforeAllTransactions`,[e]),e.emit(`beforeTransaction`,[e._transaction,e]));try{o=t(e._transaction)}finally{if(a){let t=e._transaction===i[0];e._transaction=null,t&&Jv(i,0)}}return o};var jie=class{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}};const Xv=(e,t,n)=>{P_(e,n.deletions,n=>{n instanceof cb&&t.scope.some(t=>t===e.doc||Ov(t,n))&&ib(n,!1)})},Zv=(e,t,n)=>{let r=null,i=e.doc,a=e.scope;Yv(i,n=>{for(;t.length>0&&e.currStackItem===null;){let r=i.store,o=t.pop(),s=new Set,c=[],l=!1;P_(n,o.insertions,e=>{if(e instanceof cb){if(e.redone!==null){let{item:t,diff:i}=Dae(r,e.id);i>0&&(t=Hv(n,Ev(t.id.client,t.id.clock+i))),e=t}!e.deleted&&a.some(t=>t===n.doc||Ov(t,e))&&c.push(e)}}),P_(n,o.deletions,e=>{e instanceof cb&&a.some(t=>t===n.doc||Ov(t,e))&&!I_(o.insertions,e.id)&&s.add(e)}),s.forEach(t=>{l=sb(n,t,s,o.insertions,e.ignoreRemoteMapChanges,e)!==null||l});for(let t=c.length-1;t>=0;t--){let r=c[t];e.deleteFilter(r)&&(r.delete(n),l=!0)}e.currStackItem=l?o:null}n.changed.forEach((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)}),r=n},e);let o=e.currStackItem;if(o!=null){let t=r.changedParentTypes;e.emit(`stack-item-popped`,[{stackItem:o,type:n,changedParentTypes:t,origin:e},e]),e.currStackItem=null}return o};var Mie=class extends yh{constructor(e,{captureTimeout:t=500,captureTransaction:n=e=>!0,deleteFilter:r=()=>!0,trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:a=!1,doc:o=vh(e)?e[0].doc:e instanceof q_?e:e.doc}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.currStackItem=null,this.lastChange=0,this.ignoreRemoteMapChanges=a,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!this.captureTransaction(e)||!this.scope.some(t=>e.changedParentTypes.has(t)||t===this.doc)||!this.trackedOrigins.has(e.origin)&&(!e.origin||!this.trackedOrigins.has(e.origin.constructor)))return;let t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);let i=new N_;e.afterState.forEach((t,n)=>{let r=e.beforeState.get(n)||0,a=t-r;a>0&&z_(i,n,r,a)});let a=Fg(),o=!1;if(this.lastChange>0&&a-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){let t=r[r.length-1];t.deletions=R_([t.deletions,e.deleteSet]),t.insertions=R_([t.insertions,i])}else r.push(new jie(e.deleteSet,i)),o=!0;!t&&!n&&(this.lastChange=a),P_(e,e.deleteSet,t=>{t instanceof cb&&this.scope.some(n=>n===e.doc||Ov(n,t))&&ib(t,!0)});let s=[{stackItem:r[r.length-1],origin:e.origin,type:t?`redo`:`undo`,changedParentTypes:e.changedParentTypes},this];o?this.emit(`stack-item-added`,s):this.emit(`stack-item-updated`,s)},this.doc.on(`afterTransaction`,this.afterTransactionHandler),this.doc.on(`destroy`,()=>{this.destroy()})}addToScope(e){let t=new Set(this.scope);e=vh(e)?e:[e],e.forEach(e=>{t.has(e)||(t.add(e),(e instanceof fy?e.doc!==this.doc:e!==this.doc)&&O_(`[yjs#509] Not same Y.Doc`),this.scope.push(e))})}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact(n=>{e&&(this.undoStack.forEach(e=>Xv(n,this,e)),this.undoStack=[]),t&&(this.redoStack.forEach(e=>Xv(n,this,e)),this.redoStack=[]),this.emit(`stack-cleared`,[{undoStackCleared:e,redoStackCleared:t}])})}stopCapturing(){this.lastChange=0}undo(){this.undoing=!0;let e;try{e=Zv(this,this.undoStack,`undo`)}finally{this.undoing=!1}return e}redo(){this.redoing=!0;let e;try{e=Zv(this,this.redoStack,`redo`)}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off(`afterTransaction`,this.afterTransactionHandler),super.destroy()}};function*Nie(e){let t=Sg(e.restDecoder);for(let n=0;n<t;n++){let t=Sg(e.restDecoder),n=e.readClient(),r=Sg(e.restDecoder);for(let i=0;i<t;i++){let t=e.readInfo();if(t===10){let t=Sg(e.restDecoder);yield new ub(Ev(n,r),t),r+=t}else if(31&t){let i=(t&192)==0,a=new cb(Ev(n,r),null,(t&128)==128?e.readLeftID():null,null,(t&64)==64?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&(t&32)==32?e.readString():null,lb(e,t));yield a,r+=a.length}else{let t=e.readLen();yield new Jy(Ev(n,r),t),r+=t}}}}var Qv=class{constructor(e,t){this.gen=Nie(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do this.curr=this.gen.next().value||null;while(this.filterSkips&&this.curr!==null&&this.curr.constructor===ub);return this.curr}},$v=class{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}};const Pie=e=>ey(e,Y_,$_),Fie=(e,t)=>{if(e.constructor===Jy){let{client:n,clock:r}=e.id;return new Jy(Ev(n,r+t),e.length-t)}else if(e.constructor===ub){let{client:n,clock:r}=e.id;return new ub(Ev(n,r+t),e.length-t)}else{let n=e,{client:r,clock:i}=n.id;return new cb(Ev(r,i+t),null,Ev(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},ey=(e,t=Z_,n=tv)=>{if(e.length===1)return e[0];let r=e.map(e=>new t(_g(e))),i=r.map(e=>new Qv(e,!0)),a=null,o=new n,s=new $v(o);for(;i=i.filter(e=>e.curr!==null),i.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){let n=e.curr.id.clock-t.curr.id.clock;return n===0?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===ub?1:-1:n}else return t.curr.id.client-e.curr.id.client}),i.length!==0;){let e=i[0],t=e.curr.id.client;if(a!==null){let n=e.curr,r=!1;for(;n!==null&&n.id.clock+n.length<=a.struct.id.clock+a.struct.length&&n.id.client>=a.struct.id.client;)n=e.next(),r=!0;if(n===null||n.id.client!==t||r&&n.id.clock>a.struct.id.clock+a.struct.length)continue;if(t!==a.struct.id.client)ny(s,a.struct,a.offset),a={struct:n,offset:0},e.next();else if(a.struct.id.clock+a.struct.length<n.id.clock)if(a.struct.constructor===ub)a.struct.length=n.id.clock+n.length-a.struct.id.clock;else{ny(s,a.struct,a.offset);let e=n.id.clock-a.struct.id.clock-a.struct.length;a={struct:new ub(Ev(t,a.struct.id.clock+a.struct.length),e),offset:0}}else{let t=a.struct.id.clock+a.struct.length-n.id.clock;t>0&&(a.struct.constructor===ub?a.struct.length-=t:n=Fie(n,t)),a.struct.mergeWith(n)||(ny(s,a.struct,a.offset),a={struct:n,offset:0},e.next())}}else a={struct:e.curr,offset:0},e.next();for(let n=e.curr;n!==null&&n.id.client===t&&n.id.clock===a.struct.id.clock+a.struct.length&&n.constructor!==ub;n=e.next())ny(s,a.struct,a.offset),a={struct:n,offset:0}}return a!==null&&(ny(s,a.struct,a.offset),a=null),ry(s),H_(o,R_(r.map(e=>U_(e)))),o.toUint8Array()},Iie=(e,t,n=Z_,r=tv)=>{let i=mv(t),a=new r,o=new $v(a),s=new n(_g(e)),c=new Qv(s,!1);for(;c.curr;){let e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor===ub){c.next();continue}if(e.id.clock+e.length>n)for(ny(o,e,Ch(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)ny(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next()}return ry(o),H_(a,U_(s)),a.toUint8Array()},ty=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Vh(e.encoder.restEncoder)}),e.encoder.restEncoder=Rh(),e.written=0)},ny=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ty(e),e.written===0&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Gh(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ry=e=>{ty(e);let t=e.encoder.restEncoder;Gh(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){let r=e.clientStructs[n];Gh(t,r.written),Xh(t,r.restEncoder)}},Lie=(e,t,n,r)=>{let i=new n(_g(e)),a=new Qv(i,!1),o=new r,s=new $v(o);for(let e=a.curr;e!==null;e=a.next())ny(s,t(e),0);return ry(s),H_(o,U_(i)),o.toUint8Array()},Rie=e=>Lie(e,$g,Z_,$_),iy=`You must not compute changes after the event-handler fired.`;var ay=class{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||=zie(this.currentTarget,this.target)}deletes(e){return I_(this.transaction.deleteSet,e.id)}get keys(){if(this._keys===null){if(this.transaction.doc._transactionCleanups.length===0)throw dg(iy);let e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(n!==null){let r=t._map.get(n),i,a;if(this.adds(r)){let e=r.left;for(;e!==null&&this.adds(e);)e=e.left;if(this.deletes(r))if(e!==null&&this.deletes(e))i=`delete`,a=mh(e.content.getContent());else return;else e!==null&&this.deletes(e)?(i=`update`,a=mh(e.content.getContent())):(i=`add`,a=void 0)}else if(this.deletes(r))i=`delete`,a=mh(r.content.getContent());else return;e.set(n,{action:i,oldValue:a})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(e===null){if(this.transaction.doc._transactionCleanups.length===0)throw dg(iy);let t=this.target,n=ph(),r=ph(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null,a=()=>{e&&i.push(e)};for(let i=t._start;i!==null;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&((e===null||e.delete===void 0)&&(a(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?((e===null||e.insert===void 0)&&(a(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):((e===null||e.retain===void 0)&&(a(),e={retain:0}),e.retain+=i.length);e!==null&&e.retain===void 0&&a()}this._changes=e}return e}};const zie=(e,t)=>{let n=[];for(;t._item!==null&&t!==e;){if(t._item.parentSub!==null)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&r!==null;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},oy=()=>{O_(`Invalid access: Add Yjs type to a document before reading data.`)};let sy=0;var Bie=class{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=sy++}};const Vie=e=>{e.timestamp=sy++},cy=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=sy++},Hie=(e,t,n)=>{if(e.length>=80){let r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return cy(r,t,n),r}else{let r=new Bie(t,n);return e.push(r),r}},ly=(e,t)=>{if(e._start===null||t===0||e._searchMarker===null)return null;let n=e._searchMarker.length===0?null:e._searchMarker.reduce((e,n)=>xh(t-e.index)<xh(t-n.index)?e:n),r=e._start,i=0;for(n!==null&&(r=n.p,i=n.index,Vie(n));r.right!==null&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;r.left!==null&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;r.left!==null&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return n!==null&&xh(n.index-i)<r.parent.length/80?(cy(n,r,i),n):Hie(e._searchMarker,r,i)},uy=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){let i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(t===null||t.marker===!0){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=Ch(t,i.index+n))}},dy=(e,t,n)=>{let r=e,i=t.changedParentTypes;for(;dh(i,e,()=>[]).push(n),e._item!==null;)e=e._item.parent;Cv(r._eH,n,t)};var fy=class{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=bv(),this._dEH=bv(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw fg()}clone(){throw fg()}_write(e){}get _first(){let e=this._start;for(;e!==null&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){xv(this._eH,e)}observeDeep(e){xv(this._dEH,e)}unobserve(e){Sv(this._eH,e)}unobserveDeep(e){Sv(this._dEH,e)}toJSON(){}};const py=(e,t,n)=>{e.doc??oy(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t,i=[],a=e._start;for(;a!==null&&r>0;){if(a.countable&&!a.deleted){let e=a.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}a=a.right}return i},my=e=>{e.doc??oy();let t=[],n=e._start;for(;n!==null;){if(n.countable&&!n.deleted){let e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Uie=(e,t)=>{let n=[],r=e._start;for(;r!==null;){if(r.countable&&Mv(r,t)){let e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},hy=(e,t)=>{let n=0,r=e._start;for(e.doc??oy();r!==null;){if(r.countable&&!r.deleted){let i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},gy=(e,t)=>{let n=[];return hy(e,(r,i)=>{n.push(t(r,i,e))}),n},Wie=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(n===null){for(;t!==null&&t.deleted;)t=t.right;if(t===null)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}let e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},_y=(e,t)=>{e.doc??oy();let n=ly(e,t),r=e._start;for(n!==null&&(r=n.p,t-=n.index);r!==null;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},vy=(e,t,n,r)=>{let i=n,a=e.doc,o=a.clientID,s=a.store,c=n===null?t._start:n.right,l=[],u=()=>{l.length>0&&(i=new cb(Ev(o,Lv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new tb(l)),i.integrate(e,0),l=[])};r.forEach(n=>{if(n===null)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new cb(Ev(o,Lv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Yy(new Uint8Array(n))),i.integrate(e,0);break;case q_:i=new cb(Ev(o,Lv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Qy(n)),i.integrate(e,0);break;default:if(n instanceof fy)i=new cb(Ev(o,Lv(s,o)),i,i&&i.lastId,c,c&&c.id,t,null,new rb(n)),i.integrate(e,0);else throw Error(`Unexpected content type in insert operation`)}}}),u()},yy=()=>dg(`Length exceeded!`),by=(e,t,n,r)=>{if(n>t._length)throw yy();if(n===0)return t._searchMarker&&uy(t._searchMarker,n,r.length),vy(e,t,null,r);let i=n,a=ly(t,n),o=t._start;for(a!==null&&(o=a.p,n-=a.index,n===0&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));o!==null;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Hv(e,Ev(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&uy(t._searchMarker,i,r.length),vy(e,t,o,r)},Gie=(e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;return vy(e,t,r,n)},xy=(e,t,n,r)=>{if(r===0)return;let i=n,a=r,o=ly(t,n),s=t._start;for(o!==null&&(s=o.p,n-=o.index);s!==null&&n>0;s=s.right)!s.deleted&&s.countable&&(n<s.length&&Hv(e,Ev(s.id.client,s.id.clock+n)),n-=s.length);for(;r>0&&s!==null;)s.deleted||(r<s.length&&Hv(e,Ev(s.id.client,s.id.clock+r)),s.delete(e),r-=s.length),s=s.right;if(r>0)throw yy();t._searchMarker&&uy(t._searchMarker,i,-a+r)},Sy=(e,t,n)=>{let r=t._map.get(n);r!==void 0&&r.delete(e)},Cy=(e,t,n,r)=>{let i=t._map.get(n)||null,a=e.doc,o=a.clientID,s;if(r==null)s=new tb([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:s=new tb([r]);break;case Uint8Array:s=new Yy(r);break;case q_:s=new Qy(r);break;default:if(r instanceof fy)s=new rb(r);else throw Error(`Unexpected content type`)}new cb(Ev(o,Lv(a.store,o)),i,i&&i.lastId,null,null,t,n,s).integrate(e,0)},wy=(e,t)=>{e.doc??oy();let n=e._map.get(t);return n!==void 0&&!n.deleted?n.content.getContent()[n.length-1]:void 0},Ty=e=>{let t={};return e.doc??oy(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},Ey=(e,t)=>{e.doc??oy();let n=e._map.get(t);return n!==void 0&&!n.deleted},Kie=(e,t)=>{let n={};return e._map.forEach((e,r)=>{let i=e;for(;i!==null&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;i!==null&&Mv(i,t)&&(n[r]=i.content.getContent()[i.length-1])}),n},Dy=e=>(e.doc??oy(),A_(e._map.entries(),e=>!e[1].deleted));var qie=class extends ay{},Oy=class e extends fy{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(t){let n=new e;return n.push(t),n}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof fy?e.clone():e)),t}get length(){return this.doc??oy(),this._length}_callObserver(e,t){super._callObserver(e,t),dy(this,e,new qie(this,e))}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Yv(this.doc,n=>{by(n,this,e,t)})}push(e){this.doc===null?this._prelimContent.push(...e):Yv(this.doc,t=>{Gie(t,this,e)})}unshift(e){this.insert(0,e)}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Yv(this.doc,n=>{xy(n,this,e,t)})}get(e){return _y(this,e)}toArray(){return my(this)}slice(e=0,t=this.length){return py(this,e,t)}toJSON(){return this.map(e=>e instanceof fy?e.toJSON():e)}map(e){return gy(this,e)}forEach(e){hy(this,e)}[Symbol.iterator](){return Wie(this)}_write(e){e.writeTypeRef(yae)}};const Jie=e=>new Oy;var Yie=class extends ay{constructor(e,t,n){super(e,t),this.keysChanged=n}},ky=class e extends fy{constructor(e){super(),this._prelimContent=null,e===void 0?this._prelimContent=new Map:this._prelimContent=new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return this.forEach((e,n)=>{t.set(n,e instanceof fy?e.clone():e)}),t}_callObserver(e,t){dy(this,e,new Yie(this,e,t))}toJSON(){this.doc??oy();let e={};return this._map.forEach((t,n)=>{if(!t.deleted){let r=t.content.getContent()[t.length-1];e[n]=r instanceof fy?r.toJSON():r}}),e}get size(){return[...Dy(this)].length}keys(){return j_(Dy(this),e=>e[0])}values(){return j_(Dy(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return j_(Dy(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??oy(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){this.doc===null?this._prelimContent.delete(e):Yv(this.doc,t=>{Sy(t,this,e)})}set(e,t){return this.doc===null?this._prelimContent.set(e,t):Yv(this.doc,n=>{Cy(n,this,e,t)}),t}get(e){return wy(this,e)}has(e){return Ey(this,e)}clear(){this.doc===null?this._prelimContent.clear():Yv(this.doc,e=>{this.forEach(function(t,n,r){Sy(e,r,n)})})}_write(e){e.writeTypeRef(bae)}};const Xie=e=>new ky,Ay=(e,t)=>e===t||typeof e==`object`&&typeof t==`object`&&e&&t&&Yg(e,t);var jy=class{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){switch(this.right===null&&pg(),this.right.content.constructor){case eb:this.right.deleted||Fy(this.currentAttributes,this.right.content);break;default:this.right.deleted||(this.index+=this.right.length);break}this.left=this.right,this.right=this.right.right}};const My=(e,t,n)=>{for(;t.right!==null&&n>0;){switch(t.right.content.constructor){case eb:t.right.deleted||Fy(t.currentAttributes,t.right.content);break;default:t.right.deleted||(n<t.right.length&&Hv(e,Ev(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);break}t.left=t.right,t.right=t.right.right}return t},Ny=(e,t,n,r)=>{let i=new Map,a=r?ly(t,n):null;return a?My(e,new jy(a.p.left,a.p,a.index,i),n-a.index):My(e,new jy(null,t._start,0,i),n)},Py=(e,t,n,r)=>{for(;n.right!==null&&(n.right.deleted===!0||n.right.content.constructor===eb&&Ay(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();let i=e.doc,a=i.clientID;r.forEach((r,o)=>{let s=n.left,c=n.right,l=new cb(Ev(a,Lv(i.store,a)),s,s&&s.lastId,c,c&&c.id,t,null,new eb(o,r));l.integrate(e,0),n.right=l,n.forward()})},Fy=(e,t)=>{let{key:n,value:r}=t;r===null?e.delete(n):e.set(n,r)},Iy=(e,t)=>{for(;e.right!==null&&(e.right.deleted||e.right.content.constructor===eb&&Ay(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Ly=(e,t,n,r)=>{let i=e.doc,a=i.clientID,o=new Map;for(let s in r){let c=r[s],l=n.currentAttributes.get(s)??null;if(!Ay(l,c)){o.set(s,l);let{left:r,right:u}=n;n.right=new cb(Ev(a,Lv(i.store,a)),r,r&&r.lastId,u,u&&u.id,t,null,new eb(s,c)),n.right.integrate(e,0),n.forward()}}return o},Ry=(e,t,n,r,i)=>{n.currentAttributes.forEach((e,t)=>{i[t]===void 0&&(i[t]=null)});let a=e.doc,o=a.clientID;Iy(n,i);let s=Ly(e,t,n,i),c=r.constructor===String?new nb(r):r instanceof fy?new rb(r):new $y(r),{left:l,right:u,index:d}=n;t._searchMarker&&uy(t._searchMarker,n.index,c.getLength()),u=new cb(Ev(o,Lv(a.store,o)),l,l&&l.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Py(e,t,n,s)},zy=(e,t,n,r,i)=>{let a=e.doc,o=a.clientID;Iy(n,i);let s=Ly(e,t,n,i);iterationLoop:for(;n.right!==null&&(r>0||s.size>0&&(n.right.deleted||n.right.content.constructor===eb));){if(!n.right.deleted)switch(n.right.content.constructor){case eb:{let{key:t,value:a}=n.right.content,o=i[t];if(o!==void 0){if(Ay(o,a))s.delete(t);else{if(r===0)break iterationLoop;s.set(t,a)}n.right.delete(e)}else n.currentAttributes.set(t,a);break}default:r<n.right.length&&Hv(e,Ev(n.right.id.client,n.right.id.clock+r)),r-=n.right.length;break}n.forward()}if(r>0){let i=``;for(;r>0;r--)i+=`
6
6
  `;n.right=new cb(Ev(o,Lv(a.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new nb(i)),n.right.integrate(e,0),n.forward()}Py(e,t,n,s)},By=(e,t,n,r,i)=>{let a=t,o=lh();for(;a&&(!a.countable||a.deleted);){if(!a.deleted&&a.content.constructor===eb){let e=a.content;o.set(e.key,e)}a=a.right}let s=0,c=!1;for(;t!==a;){if(n===t&&(c=!0),!t.deleted){let n=t.content;switch(n.constructor){case eb:{let{key:a,value:l}=n,u=r.get(a)??null;(o.get(a)!==n||u===l)&&(t.delete(e),s++,!c&&(i.get(a)??null)===l&&u!==l&&(u===null?i.delete(a):i.set(a,u))),!c&&!t.deleted&&Fy(i,n);break}}}t=t.right}return s},Zie=(e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;let n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===eb){let r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}},Qie=e=>{let t=0;return Yv(e.doc,n=>{let r=e._start,i=e._start,a=lh(),o=uh(a);for(;i;){if(i.deleted===!1)switch(i.content.constructor){case eb:Fy(o,i.content);break;default:t+=By(n,r,i,a,o),a=uh(o),r=i;break}i=i.right}}),t},$ie=e=>{let t=new Set,n=e.doc;for(let[r,i]of e.afterState.entries()){let a=e.beforeState.get(r)||0;i!==a&&Wv(e,n.store.clients.get(r),a,i,e=>{!e.deleted&&e.content.constructor===eb&&e.constructor!==Jy&&t.add(e.parent)})}Yv(n,n=>{P_(e,e.deleteSet,e=>{if(e instanceof Jy||!e.parent._hasFormatting||t.has(e.parent))return;let r=e.parent;e.content.constructor===eb?t.add(r):Zie(n,e)});for(let e of t)Qie(e)})},Vy=(e,t,n)=>{let r=n,i=uh(t.currentAttributes),a=t.right;for(;n>0&&t.right!==null;){if(t.right.deleted===!1)switch(t.right.content.constructor){case rb:case $y:case nb:n<t.right.length&&Hv(e,Ev(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e);break}t.forward()}a&&By(e,a,t.right,i,t.currentAttributes);let o=(t.left||t.right).parent;return o._searchMarker&&uy(o._searchMarker,t.index,-r+n),t};var eae=class extends ay{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{e===null?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(this._changes===null){let e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(this._delta===null){let e=this.target.doc,t=[];Yv(e,e=>{let n=new Map,r=new Map,i=this.target._start,a=null,o={},s=``,c=0,l=0,u=()=>{if(a!==null){let e=null;switch(a){case`delete`:l>0&&(e={delete:l}),l=0;break;case`insert`:(typeof s==`object`||s.length>0)&&(e={insert:s},n.size>0&&(e.attributes={},n.forEach((t,n)=>{t!==null&&(e.attributes[n]=t)}))),s=``;break;case`retain`:c>0&&(e={retain:c},Kg(o)||(e.attributes=Hg({},o))),c=0;break}e&&t.push(e),a=null}};for(;i!==null;){switch(i.content.constructor){case rb:case $y:this.adds(i)?this.deletes(i)||(u(),a=`insert`,s=i.content.getContent()[0],u()):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=1):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=1);break;case nb:this.adds(i)?this.deletes(i)||(a!==`insert`&&(u(),a=`insert`),s+=i.content.str):this.deletes(i)?(a!==`delete`&&(u(),a=`delete`),l+=i.length):i.deleted||(a!==`retain`&&(u(),a=`retain`),c+=i.length);break;case eb:{let{key:t,value:s}=i.content;if(this.adds(i))this.deletes(i)||(Ay(n.get(t)??null,s)?s!==null&&i.delete(e):(a===`retain`&&u(),Ay(s,r.get(t)??null)?delete o[t]:o[t]=s));else if(this.deletes(i)){r.set(t,s);let e=n.get(t)??null;Ay(e,s)||(a===`retain`&&u(),o[t]=e)}else if(!i.deleted){r.set(t,s);let n=o[t];n!==void 0&&(Ay(n,s)?n!==null&&i.delete(e):(a===`retain`&&u(),s===null?delete o[t]:o[t]=s))}i.deleted||(a===`insert`&&u(),Fy(n,i.content));break}}i=i.right}for(u();t.length>0;){let e=t[t.length-1];if(e.retain!==void 0&&e.attributes===void 0)t.pop();else break}}),this._delta=t}return this._delta}},Hy=class e extends fy{constructor(e){super(),this._pending=e===void 0?[]:[()=>this.insert(0,e)],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??oy(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){console.error(e)}this._pending=null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}_callObserver(e,t){super._callObserver(e,t);let n=new eae(this,e,t);dy(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??oy();let e=``,t=this._start;for(;t!==null;)!t.deleted&&t.countable&&t.content.constructor===nb&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){this.doc===null?this._pending.push(()=>this.applyDelta(e)):Yv(this.doc,n=>{let r=new jy(null,this._start,0,new Map);for(let i=0;i<e.length;i++){let a=e[i];if(a.insert!==void 0){let o=!t&&typeof a.insert==`string`&&i===e.length-1&&r.right===null&&a.insert.slice(-1)===`
7
7
  `?a.insert.slice(0,-1):a.insert;(typeof o!=`string`||o.length>0)&&Ry(n,this,r,o,a.attributes||{})}else a.retain===void 0?a.delete!==void 0&&Vy(n,r,a.delete):zy(n,this,r,a.retain,a.attributes||{})}})}toDelta(e,t,n){this.doc??oy();let r=[],i=new Map,a=this.doc,o=``,s=this._start;function c(){if(o.length>0){let e={},t=!1;i.forEach((n,r)=>{t=!0,e[r]=n});let n={insert:o};t&&(n.attributes=e),r.push(n),o=``}}let l=()=>{for(;s!==null;){if(Mv(s,e)||t!==void 0&&Mv(s,t))switch(s.content.constructor){case nb:{let r=i.get(`ychange`);e!==void 0&&!Mv(s,e)?(r===void 0||r.user!==s.id.client||r.type!==`removed`)&&(c(),i.set(`ychange`,n?n(`removed`,s.id):{type:`removed`})):t!==void 0&&!Mv(s,t)?(r===void 0||r.user!==s.id.client||r.type!==`added`)&&(c(),i.set(`ychange`,n?n(`added`,s.id):{type:`added`})):r!==void 0&&(c(),i.delete(`ychange`)),o+=s.content.str;break}case rb:case $y:{c();let e={insert:s.content.getContent()[0]};if(i.size>0){let t={};e.attributes=t,i.forEach((e,n)=>{t[n]=e})}r.push(e);break}case eb:Mv(s,e)&&(c(),Fy(i,s.content));break}s=s.right}c()};return e||t?Yv(a,n=>{e&&Nv(n,e),t&&Nv(n,t),l()},`cleanup`):l(),r}insert(e,t,n){if(t.length<=0)return;let r=this.doc;r===null?this._pending.push(()=>this.insert(e,t,n)):Yv(r,r=>{let i=Ny(r,this,e,!n);n||(n={},i.currentAttributes.forEach((e,t)=>{n[t]=e})),Ry(r,this,i,t,n)})}insertEmbed(e,t,n){let r=this.doc;r===null?this._pending.push(()=>this.insertEmbed(e,t,n||{})):Yv(r,r=>{let i=Ny(r,this,e,!n);Ry(r,this,i,t,n||{})})}delete(e,t){if(t===0)return;let n=this.doc;n===null?this._pending.push(()=>this.delete(e,t)):Yv(n,n=>{Vy(n,Ny(n,this,e,!0),t)})}format(e,t,n){if(t===0)return;let r=this.doc;r===null?this._pending.push(()=>this.format(e,t,n)):Yv(r,r=>{let i=Ny(r,this,e,!1);i.right!==null&&zy(r,this,i,t,n)})}removeAttribute(e){this.doc===null?this._pending.push(()=>this.removeAttribute(e)):Yv(this.doc,t=>{Sy(t,this,e)})}setAttribute(e,t){this.doc===null?this._pending.push(()=>this.setAttribute(e,t)):Yv(this.doc,n=>{Cy(n,this,e,t)})}getAttribute(e){return wy(this,e)}getAttributes(){return Ty(this)}_write(e){e.writeTypeRef(xae)}};const tae=e=>new Hy;var Uy=class{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??oy()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(e!==null&&(!this._firstCall||e.deleted||!this._filter(t)))do if(t=e.content.type,!e.deleted&&(t.constructor===Gy||t.constructor===Wy)&&t._start!==null)e=t._start;else for(;e!==null;){let t=e.next;if(t!==null){e=t;break}else e=e.parent===this._root?null:e.parent._item}while(e!==null&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,e===null?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}},Wy=class e extends fy{constructor(){super(),this._prelimContent=[]}get firstChild(){let e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new e}clone(){let t=new e;return t.insert(0,this.toArray().map(e=>e instanceof fy?e.clone():e)),t}get length(){return this.doc??oy(),this._prelimContent===null?this._length:this._prelimContent.length}createTreeWalker(e){return new Uy(this,e)}querySelector(e){e=e.toUpperCase();let t=new Uy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),gh(new Uy(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){dy(this,e,new iae(this,t,e))}toString(){return gy(this,e=>e.toString()).join(``)}toJSON(){return this.toString()}toDOM(e=document,t={},n){let r=e.createDocumentFragment();return n!==void 0&&n._createAssociation(r,this),hy(this,i=>{r.insertBefore(i.toDOM(e,t,n),null)}),r}insert(e,t){this.doc===null?this._prelimContent.splice(e,0,...t):Yv(this.doc,n=>{by(n,this,e,t)})}insertAfter(e,t){if(this.doc!==null)Yv(this.doc,n=>{let r=e&&e instanceof fy?e._item:e;vy(n,this,r,t)});else{let n=this._prelimContent,r=e===null?0:n.findIndex(t=>t===e)+1;if(r===0&&e!==null)throw dg(`Reference item not found`);n.splice(r,0,...t)}}delete(e,t=1){this.doc===null?this._prelimContent.splice(e,t):Yv(this.doc,n=>{xy(n,this,e,t)})}toArray(){return my(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return _y(this,e)}slice(e=0,t=this.length){return py(this,e,t)}forEach(e){hy(this,e)}_write(e){e.writeTypeRef(Cae)}};const nae=e=>new Wy;var Gy=class e extends Wy{constructor(e=`UNDEFINED`){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new e(this.nodeName)}clone(){let t=new e(this.nodeName);return Wg(this.getAttributes(),(e,n)=>{t.setAttribute(n,e)}),t.insert(0,this.toArray().map(e=>e instanceof fy?e.clone():e)),t}toString(){let e=this.getAttributes(),t=[],n=[];for(let t in e)n.push(t);n.sort();let r=n.length;for(let i=0;i<r;i++){let r=n[i];t.push(r+`="`+e[r]+`"`)}let i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?` `+t.join(` `):``}>${super.toString()}</${i}>`}removeAttribute(e){this.doc===null?this._prelimAttrs.delete(e):Yv(this.doc,t=>{Sy(t,this,e)})}setAttribute(e,t){this.doc===null?this._prelimAttrs.set(e,t):Yv(this.doc,n=>{Cy(n,this,e,t)})}getAttribute(e){return wy(this,e)}hasAttribute(e){return Ey(this,e)}getAttributes(e){return e?Kie(this,e):Ty(this)}toDOM(e=document,t={},n){let r=e.createElement(this.nodeName),i=this.getAttributes();for(let e in i){let t=i[e];typeof t==`string`&&r.setAttribute(e,t)}return hy(this,i=>{r.appendChild(i.toDOM(e,t,n))}),n!==void 0&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Sae),e.writeKey(this.nodeName)}};const rae=e=>new Gy(e.readKey());var iae=class extends ay{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{e===null?this.childListChanged=!0:this.attributesChanged.add(e)})}},aae=class e extends ky{constructor(e){super(),this.hookName=e}_copy(){return new e(this.hookName)}clone(){let t=new e(this.hookName);return this.forEach((e,n)=>{t.set(n,e)}),t}toDOM(e=document,t={},n){let r=t[this.hookName],i;return i=r===void 0?document.createElement(this.hookName):r.createDom(this),i.setAttribute(`data-yjs-hook`,this.hookName),n!==void 0&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(wae),e.writeKey(this.hookName)}};const oae=e=>new aae(e.readKey());var Ky=class e extends Hy{get nextSibling(){let e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){let e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new e}clone(){let t=new e;return t.applyDelta(this.toDelta()),t}toDOM(e=document,t,n){let r=e.createTextNode(this.toString());return n!==void 0&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{let t=[];for(let n in e.attributes){let r=[];for(let t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n=``;for(let e=0;e<t.length;e++){let r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){let t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=`>`}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join(``)}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Tae)}};const sae=e=>new Ky;var qy=class{constructor(e,t){this.id=e,this.length=t}get deleted(){throw fg()}mergeWith(e){return!1}write(e,t,n){throw fg()}integrate(e,t){throw fg()}},Jy=class extends qy{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Rv(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}},Yy=class e{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new e(this.content)}splice(e){throw fg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}};const cae=e=>new Yy(e.readBuf());var Xy=class e{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.len)}splice(t){let n=new e(this.len-t);return this.len=t,n}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){z_(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}};const lae=e=>new Xy(e.readLen()),Zy=(e,t)=>new q_({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});var Qy=class e{constructor(e){e._item&&console.error(`This document was already integrated as a sub-document. You should create a second instance instead with the same guid.`),this.doc=e;let t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),e.meta!==null&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new e(Zy(this.doc.guid,this.opts))}splice(e){throw fg()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}};const uae=e=>new Qy(Zy(e.readString(),e.readAny()));var $y=class e{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new e(this.embed)}splice(e){throw fg()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}};const dae=e=>new $y(e.readJSON());var eb=class e{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new e(this.key,this.value)}splice(e){throw fg()}mergeWith(e){return!1}integrate(e,t){let n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}};const fae=e=>new eb(e.readKey(),e.readJSON());var pae=class e{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeString(t===void 0?`undefined`:JSON.stringify(t))}}getRef(){return 2}};const mae=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++){let t=e.readString();t===`undefined`?n.push(void 0):n.push(JSON.parse(t))}return new pae(n)},hae=s_(`node_env`)===`development`;var tb=class e{constructor(e){this.arr=e,hae&&Zg(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new e(this.arr)}splice(t){let n=new e(this.arr.slice(t));return this.arr=this.arr.slice(0,t),n}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){let n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){let t=this.arr[r];e.writeAny(t)}}getRef(){return 8}};const gae=e=>{let t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new tb(n)};var nb=class e{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split(``)}isCountable(){return!0}copy(){return new e(this.str)}splice(t){let n=new e(this.str.slice(t));this.str=this.str.slice(0,t);let r=this.str.charCodeAt(t-1);return r>=55296&&r<=56319&&(this.str=this.str.slice(0,t-1)+`�`,n.str=`�`+n.str.slice(1)),n}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(t===0?this.str:this.str.slice(t))}getRef(){return 4}};const _ae=e=>new nb(e.readString()),vae=[Jie,Xie,tae,rae,nae,oae,sae],yae=0,bae=1,xae=2,Sae=3,Cae=4,wae=5,Tae=6;var rb=class e{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new e(this.type._copy())}splice(e){throw fg()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;t!==null;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;t!==null;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;t!==null;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}};const Eae=e=>new rb(vae[e.readTypeRef()](e)),Dae=(e,t)=>{let n=t,r=0,i;do r>0&&(n=Ev(n.client,n.clock+r)),i=Bv(e,n),r=n.clock-i.id.clock,n=i.redone;while(n!==null&&i instanceof cb);return{item:i,diff:r}},ib=(e,t)=>{for(;e!==null&&e.keep!==t;)e.keep=t,e=e.parent._item},ab=(e,t,n)=>{let{client:r,clock:i}=t.id,a=new cb(Ev(r,i+n),t,Ev(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&a.markDeleted(),t.keep&&(a.keep=!0),t.redone!==null&&(a.redone=Ev(t.redone.client,t.redone.clock+n)),t.right=a,a.right!==null&&(a.right.left=a),e._mergeStructs.push(a),a.parentSub!==null&&a.right===null&&a.parent._map.set(a.parentSub,a),t.length=n,a},ob=(e,t)=>_h(e,e=>I_(e.deletions,t)),sb=(e,t,n,r,i,a)=>{let o=e.doc,s=o.store,c=o.clientID,l=t.redone;if(l!==null)return Hv(e,l);let u=t.parent._item,d=null,f;if(u!==null&&u.deleted===!0){if(u.redone===null&&(!n.has(u)||sb(e,u,n,r,i,a)===null))return null;for(;u.redone!==null;)u=Hv(e,u.redone)}let p=u===null?t.parent:u.content.type;if(t.parentSub===null){for(d=t.left,f=t;d!==null;){let t=d;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Hv(e,t.redone);if(t!==null&&t.parent._item===u){d=t;break}d=d.left}for(;f!==null;){let t=f;for(;t!==null&&t.parent._item!==u;)t=t.redone===null?null:Hv(e,t.redone);if(t!==null&&t.parent._item===u){f=t;break}f=f.right}}else{if(f=null,t.right&&!i){for(d=t;d!==null&&d.right!==null&&(d.right.redone||I_(r,d.right.id)||ob(a.undoStack,d.right.id)||ob(a.redoStack,d.right.id));)for(d=d.right;d.redone;)d=Hv(e,d.redone);if(d&&d.right!==null)return null}else d=p._map.get(t.parentSub)||null;d!==null&&d.parent._item!==u&&(d=p._map.get(t.parentSub)||null)}let m=Ev(c,Lv(s,c)),h=new cb(m,d,d&&d.lastId,f,f&&f.id,p,t.parentSub,t.content.copy());return t.redone=m,ib(h,!0),h.integrate(e,0),h};var cb=class e extends qy{constructor(e,t,n,r,i,a,o,s){super(e,s.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=a,this.parentSub=o,this.redone=null,this.content=s,this.info=this.content.isCountable()?2:0}set marker(e){(this.info&8)>0!==e&&(this.info^=8)}get marker(){return(this.info&8)>0}get keep(){return(this.info&1)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(this.info&2)>0}get deleted(){return(this.info&4)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(t,n){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Lv(n,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Lv(n,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===wv&&this.id.client!==this.parent.client&&this.parent.clock>=Lv(n,this.parent.client))return this.parent.client;if(this.origin&&=(this.left=Uv(t,n,this.origin),this.left.lastId),this.rightOrigin&&=(this.right=Hv(t,this.rightOrigin),this.right.id),this.left&&this.left.constructor===Jy||this.right&&this.right.constructor===Jy)this.parent=null;else if(!this.parent)this.left&&this.left.constructor===e?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===e&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);else if(this.parent.constructor===wv){let e=Bv(n,this.parent);e.constructor===Jy?this.parent=null:this.parent=e.content.type}return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Uv(e,e.doc.store,Ev(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||this.right.left!==null)||this.left&&this.left.right!==this.right){let t=this.left,n;if(t!==null)n=t.right;else if(this.parentSub!==null)for(n=this.parent._map.get(this.parentSub)||null;n!==null&&n.left!==null;)n=n.left;else n=this.parent._start;let r=new Set,i=new Set;for(;n!==null&&n!==this.right;){if(i.add(n),r.add(n),Tv(this.origin,n.origin)){if(n.id.client<this.id.client)t=n,r.clear();else if(Tv(this.rightOrigin,n.rightOrigin))break}else if(n.origin!==null&&i.has(Bv(e.doc.store,n.origin)))r.has(Bv(e.doc.store,n.origin))||(t=n,r.clear());else break;n=n.right}this.left=t}if(this.left!==null){let e=this.left.right;this.right=e,this.left.right=this}else{let e;if(this.parentSub!==null)for(e=this.parent._map.get(this.parentSub)||null;e!==null&&e.left!==null;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}this.right===null?this.parentSub!==null&&(this.parent._map.set(this.parentSub,this),this.left!==null&&this.left.delete(e)):this.right.left=this,this.parentSub===null&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Rv(e.doc.store,this),this.content.integrate(e,this),Kv(e,this.parent,this.parentSub),(this.parent._item!==null&&this.parent._item.deleted||this.parentSub!==null&&this.right!==null)&&this.delete(e)}else new Jy(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;e!==null&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;e!==null&&e.deleted;)e=e.left;return e}get lastId(){return this.length===1?this.id:Ev(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Tv(e.origin,this.lastId)&&this.right===e&&Tv(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&this.redone===null&&e.redone===null&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){let t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,this.right!==null&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){let t=this.parent;this.countable&&this.parentSub===null&&(t._length-=this.length),this.markDeleted(),z_(e.deleteSet,this.id.client,this.id.clock,this.length),Kv(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw pg();this.content.gc(e),t?Die(e,this,new Jy(this.id,this.length)):this.content=new Xy(this.length)}write(e,t){let n=t>0?Ev(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,a=this.content.getRef()&31|(n===null?0:128)|(r===null?0:64)|(i===null?0:32);if(e.writeInfo(a),n!==null&&e.writeLeftID(n),r!==null&&e.writeRightID(r),n===null&&r===null){let t=this.parent;if(t._item!==void 0){let n=t._item;if(n===null){let n=Dv(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===wv?(e.writeParentInfo(!1),e.writeLeftID(t)):pg();i!==null&&e.writeString(i)}this.content.write(e,t)}};const lb=(e,t)=>Oae[t&31](e),Oae=[()=>{pg()},lae,mae,cae,_ae,dae,fae,Eae,gae,uae,()=>{pg()}];var ub=class extends qy{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor?(this.length+=e.length,!0):!1}integrate(e,t){pg()}write(e,t){e.writeInfo(10),Gh(e.restEncoder,this.length-t)}getMissing(e,t){return null}};const db=typeof globalThis<`u`?globalThis:typeof window<`u`?window:typeof global<`u`?global:{},fb=`__ $YJS$ __`;db[fb]===!0&&console.error(`Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438`),db[fb]=!0;const kae=/[\uD800-\uDBFF]/,Aae=/[\uDC00-\uDFFF]/,jae=(e,t)=>{let n=0,r=0;for(;n<e.length&&n<t.length&&e[n]===t[n];)n++;for(n>0&&kae.test(e[n-1])&&n--;r+n<e.length&&r+n<t.length&&e[e.length-r-1]===t[t.length-r-1];)r++;return r>0&&Aae.test(e[e.length-r])&&r--,{index:n,remove:e.length-n-r,insert:t.slice(n,t.length-r)}},Mae=e=>{let t=Cu(`sha256`);return t.update(e),t.digest()},Nae=new Yn(`y-sync`);new Yn(`y-undo`),new Yn(`yjs-cursor`);const Pae=e=>{for(let t=6;t<e.length;t++)e[t%6]=e[t%6]^e[t];return e.slice(0,6)},Fae=e=>d_(Pae(Mae(p_(e)))),Iae=()=>({mapping:new Map,isOMark:new Map}),pb=(e,t)=>t===void 0?!e.deleted:t.sv.has(e.id.client)&&t.sv.get(e.id.client)>e.id.clock&&!I_(t.ds,e.id),Lae=(e,t,n,r,i,a)=>{let o=n.mapping.get(e);if(o===void 0){if(e instanceof Gy)return mb(e,t,n,r,i,a);throw fg()}return o},mb=(e,t,n,r,i,a)=>{let o=[],s=e=>{if(e instanceof Gy){let s=Lae(e,t,n,r,i,a);s!==null&&o.push(s)}else{let s=e._item.right?.content?.type;s instanceof Hy&&!s._item.deleted&&s._item.id.client===s.doc.clientID&&(e.applyDelta([{retain:e.length},...s.toDelta()]),s.doc.transact(e=>{s._item.delete(e)}));let c=Rae(e,t,n,r,i,a);c!==null&&c.forEach(e=>{e!==null&&o.push(e)})}};r===void 0||i===void 0?e.toArray().forEach(s):Uie(e,new kv(i.ds,r.sv)).forEach(s);try{let s=e.getAttributes(r);r!==void 0&&(pb(e._item,r)?pb(e._item,i)||(s.ychange=a?a(`added`,e._item.id):{type:`added`}):s.ychange=a?a(`removed`,e._item.id):{type:`removed`});let c=xb(s),l=Eb(c.marks,t),u=t.node(e.nodeName,c.plain,o,l.length?l:void 0);return n.mapping.set(e,u),u}catch(r){console.warn(`[y-prosemirror] schema.node(`+e.nodeName+`) threw:`,String(r&&r.message||r));let i=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};if(t.nodes[e.nodeName]&&t.nodes[e.nodeName].spec&&t.nodes[e.nodeName].spec.inline)i.inline++;else if(i.block++,t.nodes.rawMdxFallback)try{let i=t.node(`rawMdxFallback`,{reason:String(r&&r.message||r)},[t.text(e.nodeName)]);return n.mapping.set(e,i),i}catch(e){console.warn(`[y-prosemirror] rawMdxFallback substitution also failed:`,String(e&&e.message||e))}return n.mapping.delete(e),null}},Rae=(e,t,n,r,i,a)=>{let o=[],s=e.toDelta(r,i,a);try{for(let e=0;e<s.length;e++){let n=s[e];o.push(t.text(n.insert,Eb(n.attributes,t)))}}catch(e){console.warn(`[y-prosemirror] schema.text() threw:`,String(e&&e.message||e));let t=globalThis.__okYpsCounters=globalThis.__okYpsCounters||{block:0,inline:0};return t.inline++,null}return o},zae=(e,t)=>{let n=new Ky,r=e.map(e=>({insert:e.text,attributes:Db(e.marks,t)}));return n.applyDelta(r),t.mapping.set(n,e),n},Bae=(e,t)=>{let n=new Gy(e.type.name);for(let t in e.attrs){let r=e.attrs[t];r!==null&&t!==`ychange`&&n.setAttribute(t,r)}let r=Db(e.marks||[],t);for(let e in r)n.setAttribute(bb+e,{...r[e]});return n.insert(0,vb(e).map(e=>hb(e,t))),t.mapping.set(n,e),n},hb=(e,t)=>e instanceof Array?zae(e,t):Bae(e,t),gb=e=>typeof e==`object`&&!!e,_b=(e,t)=>{let n=Object.keys(e).filter(t=>e[t]!==null),r=n.length===Object.keys(t).filter(e=>t[e]!==null).length;for(let i=0;i<n.length&&r;i++){let a=n[i],o=e[a],s=t[a];r=a===`ychange`||o===s||gb(o)&&gb(s)&&_b(o,s)}return r},vb=e=>{let t=e.content.content,n=[];for(let e=0;e<t.length;e++){let r=t[e];if(r.isText){let r=[];for(let n=t[e];e<t.length&&n.isText;n=t[++e])r.push(n);e--,n.push(r)}else n.push(r)}return n},yb=(e,t)=>{let n=e.toDelta();return n.length===t.length&&n.every((e,n)=>e.insert===t[n].text&&Ug(e.attributes||{}).length===t[n].marks.length&&qg(e.attributes,(e,r)=>{let i=Tb(r),a=t[n].marks;return a.find(e=>e.type.name===i)?_b(e,a.find(e=>e.type.name===i)?.attrs):!1}))},bb=`ymark:`,xb=e=>{let t={},n={};for(let r in e)r.startsWith(bb)?n[r.slice(6)]=e[r]:t[r]=e[r];return{plain:t,marks:n}},Vae=(e,t)=>{let n=Object.keys(e);return n.length===t.length?n.every(n=>{let r=Tb(n),i=t.find(e=>e.type.name===r);return i?_b(e[n],i.attrs):!1}):!1},Sb=(e,t)=>{if(e instanceof Gy&&!(t instanceof Array)&&kb(e,t)){let n=vb(t),r=xb(e.getAttributes());return e._length===n.length&&Vae(r.marks,t.marks)&&_b(r.plain,t.attrs)&&e.toArray().every((e,t)=>Sb(e,n[t]))}return e instanceof Ky&&t instanceof Array&&yb(e,t)},Cb=(e,t)=>e===t||e instanceof Array&&t instanceof Array&&e.length===t.length&&e.every((e,n)=>t[n]===e),wb=(e,t,n)=>{let r=e.toArray(),i=vb(t),a=i.length,o=r.length,s=Sh(o,a),c=0,l=0,u=!1;for(;c<s;c++){let e=r[c],t=i[c];if(Cb(n.mapping.get(e),t))u=!0;else if(!Sb(e,t))break}for(;c+l<s;l++){let e=r[o-l-1],t=i[a-l-1];if(Cb(n.mapping.get(e),t))u=!0;else if(!Sb(e,t))break}return{equalityFactor:c+l,foundMappedChild:u}},Hae=e=>{let t=``,n=e._start,r={};for(;n!==null;)n.deleted||(n.countable&&n.content instanceof nb?t+=n.content.str:n.content instanceof eb&&(r[n.content.key]=null)),n=n.right;return{str:t,nAttrs:r}},Uae=(e,t,n)=>{n.mapping.set(e,t);let{nAttrs:r,str:i}=Hae(e),a=t.map(e=>({insert:e.text,attributes:Object.assign({},r,Db(e.marks,n))})),{insert:o,remove:s,index:c}=jae(i,a.map(e=>e.insert).join(``));e.delete(c,s),e.insert(c,o),e.applyDelta(a.map(e=>({retain:e.insert.length,attributes:e.attributes})))},Wae=/(.*)(--[a-zA-Z0-9+/=]{8})$/,Tb=e=>Wae.exec(e)?.[1]??e,Eb=(e,t)=>{let n=[];for(let r in e)n.push(t.mark(Tb(r),e[r]));return n},Db=(e,t)=>{let n={};return e.forEach(e=>{if(e.type.name!==`ychange`){let r=dh(t.isOMark,e.type,()=>!e.type.excludes(e.type));n[r?`${e.type.name}--${Fae(e.toJSON())}`:e.type.name]=e.attrs}}),n},Ob=(e,t,n,r)=>{if(t instanceof Gy&&t.nodeName!==n.type.name)throw Error(`node name mismatch!`);if(r.mapping.set(t,n),t instanceof Gy){let e=t.getAttributes(),i=n.attrs;for(let n in i)i[n]===null?t.removeAttribute(n):e[n]!==i[n]&&n!==`ychange`&&t.setAttribute(n,i[n]);for(let n in e)i[n]===void 0&&!n.startsWith(bb)&&t.removeAttribute(n);let a=Db(n.marks||[],r);for(let n in a){let r=e[bb+n];(r===void 0||!_b(r,a[n]))&&t.setAttribute(bb+n,{...a[n]})}for(let n in e)n.startsWith(bb)&&a[n.slice(6)]===void 0&&t.removeAttribute(n)}let i=vb(n),a=i.length,o=t.toArray(),s=o.length,c=Sh(a,s),l=0,u=0;for(;l<c;l++){let e=o[l],t=i[l];if(!Cb(r.mapping.get(e),t))if(Sb(e,t))r.mapping.set(e,t);else break}for(;u+l+1<c;u++){let e=o[s-u-1],t=i[a-u-1];if(!Cb(r.mapping.get(e),t))if(Sb(e,t))r.mapping.set(e,t);else break}e.transact(()=>{for(;s-l-u>0&&a-l-u>0;){let n=o[l],c=i[l],d=o[s-u-1],f=i[a-u-1];if(n instanceof Ky&&c instanceof Array)yb(n,c)||Uae(n,c,r),l+=1;else{let i=n instanceof Gy&&kb(n,c),a=d instanceof Gy&&kb(d,f);if(i&&a){let e=wb(n,c,r),t=wb(d,f,r);e.foundMappedChild&&!t.foundMappedChild?a=!1:!e.foundMappedChild&&t.foundMappedChild||e.equalityFactor<t.equalityFactor?i=!1:a=!1}i?(Ob(e,n,c,r),l+=1):a?(Ob(e,d,f,r),u+=1):(r.mapping.delete(t.get(l)),t.delete(l,1),t.insert(l,[hb(c,r)]),l+=1)}}let n=s-l-u;if(s===1&&a===0&&o[0]instanceof Ky?(r.mapping.delete(o[0]),o[0].delete(0,o[0].length)):n>0&&(t.slice(l,l+n).forEach(e=>r.mapping.delete(e)),t.delete(l,n)),l+u<a){let e=[];for(let t=l;t<a-u;t++)e.push(hb(i[t],r));t.insert(l,e)}},Nae)},kb=(e,t)=>!(t instanceof Array)&&e.nodeName===t.type.name,Gae=(e,t)=>{let n=e.toArray().map(e=>mb(e,t,Iae())).filter(e=>e!==null);return Mo.fromArray(n)},Ab=(e,t)=>t.topNodeType.create(null,Gae(e,t));function jb(e,t,n,r){let{body:i}=jt(t);return r!==void 0&&r.rawContent===t?r.parsedJson:Go(`md.parseWithFallback`,{attributes:{"body.bytes":i.length,"doc.name":e.guid}},()=>Ho.parseWithFallback(i,Mb(n)))}function Mb(e){return e?{resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,sourcePath:e.sourcePath}:void 0}function Nb(e){return Ho.serialize(Ab(e,Vo).toJSON())}function Pb(e,t,n,r,i,a){let o=Nb(r),s=Ho.serialize(n),{body:c}=jt(e.baselineFullMd),l=Ho.serialize(Ho.parseWithFallback(c,a));e.report({pendingBody:t,baselineBody:l,ytextDerivedBody:s,rebuiltBody:o,restorePayload:Qt(i,t).md})}function Fb(e,t,n,r,i,a){Go(`bridge.composeAndWriteRawBody`,{attributes:{surface:n,"body.bytes":t.length,"doc.name":e.guid}},()=>{let n=e.getXmlFragment(`default`),o=e.getText(`source`),s=o.toString(),c=jb(e,t,r,i),l=Vo.nodeFromJSON(c),u=a?Nb(n):void 0;if(s!==t&&Qn(o,s,t),Ob(e,n,l,{mapping:new Map,isOMark:new Map}),a&&u!==void 0){let{frontmatter:e}=jt(a.baselineFullMd);Pb(a,u,c,n,e,Mb(r))}})}function Ib(e,t,n,r,i){Go(`bridge.replaceRawBody`,{attributes:{"body.bytes":t.length,"doc.name":e.guid}},()=>{let a=e.getXmlFragment(`default`),o=e.getText(`source`),s=jb(e,t,n,r),c=Vo.nodeFromJSON(s),l=i?Nb(a):void 0,u=o.toString();if(u!==t&&(o.delete(0,u.length),o.insert(0,t)),Ob(e,a,c,{mapping:new Map,isOMark:new Map}),i&&l!==void 0){let{frontmatter:e}=jt(i.baselineFullMd);Pb(i,l,s,a,e,Mb(n))}})}function Kae(e,t,n){let r=e.getXmlFragment(`default`),{frontmatter:i,body:a}=jt(e.getText(`source`).toString()),o=Mb(t),s=Ho.parseWithFallback(a,o),c=Vo.nodeFromJSON(s),l=n?Ho.serialize(Ab(r,Vo).toJSON()):void 0;if(Ob(e,r,c,{mapping:new Map,isOMark:new Map}),n&&l!==void 0){let e=Ho.serialize(Ab(r,Vo).toJSON()),t=Ho.serialize(s),{body:a}=jt(n.baselineFullMd),c=Ho.serialize(Ho.parseWithFallback(a,o));n.report({pendingBody:l,baselineBody:c,ytextDerivedBody:t,rebuiltBody:e,restorePayload:Qt(i,l).md})}}const qae=F(`loss-capture`),Lb=`detector-trip`,Rb=`backstop-trip`,zb=`checkpoint-write`;N({ts:i(),schemaVersion:i(),seq:i(),event:u(),docName:u(),writerId:u().nullable(),site:u().optional(),direction:u().optional(),lostLen:i().optional(),digest:u().optional(),checkpointSha:u().optional()});const Bb=[`.ok`,`local`,`loss-capture`];function Jae(e){return L(e,...Bb,`loss-current.jsonl`)}function Yae(e){return L(e,...Bb,`loss-prev.jsonl`)}var Xae=class{#e;#t;#n=new Map;constructor(e){this.#e=new As({currentPath:Jae(e.projectDir),previousPath:Yae(e.projectDir),maxBytes:e.maxBytes}),this.#t=e.now??Date.now}record(e){let t=(this.#n.get(e.docName)??0)+1;this.#n.set(e.docName,t);let n={ts:this.#t(),schemaVersion:1,seq:t,event:e.event,docName:e.docName,writerId:e.writerId,...e.site===void 0?{}:{site:e.site},...e.direction===void 0?{}:{direction:e.direction},...e.lostLen===void 0?{}:{lostLen:e.lostLen},...e.digest===void 0?{}:{digest:e.digest},...e.checkpointSha===void 0?{}:{checkpointSha:e.checkpointSha}};return this.#e.append(`${JSON.stringify(n)}\n`).catch(t=>{qae.warn({event:e.event,err:t},`[loss-capture] failed to write loss-class event`)})}async drain(){await this.#e.drain()}};const Vb=F(`checkpoint-chain`);async function Hb(e,t){let n;try{n=await e.raw(`for-each-ref`,`--format=%(objectname)`,`refs/checkpoints/${t}/`)}catch(e){throw Vb.warn({branch:t,err:e},`[checkpoint-chain] for-each-ref failed; anchors are unknown`),e}let r=n.trim().split(`
@@ -24,7 +24,7 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt
24
24
  `))n.trim()!==``&&(e.stderrTail.push(n.slice(0,500)),e.stderrTail.length>40&&e.stderrTail.shift())}),o.on(`error`,t=>{this.emitStatus(e,`error`,`agent failed to start: ${t.message}`,{reason:`connect`,agentMessage:t.message})}),o.on(`exit`,(t,n)=>{if(e.child=null,a.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on agent exit failed`)}),e.closed||e.info.archived===!0)return;if(e.info.status===`error`){this.failPendingPermissions(e);return}let r=e.stderrTail.slice(-10).join(`
25
25
  `);this.emitStatus(e,`exited`,`agent exited (${n??t??`unknown`})${r?`\n${r}`:``}`),this.failPendingPermissions(e)}),o.stdin===null||o.stdout===null)throw new cE(`spawn-failed`,`agent process has no stdio`);let s=tie(Xte.toWeb(o.stdin),xu.toWeb(o.stdout)),c=Cie({name:`open-knowledge`}).onRequest(Rm.client.session.requestPermission,t=>this.handlePermissionRequest(e,t.params.toolCall,t.params.options)).onRequest(Rm.client.fs.readTextFile,e=>this.handleFsRead(e.params.path,e.params.line??null,e.params.limit??null)).onRequest(Rm.client.fs.writeTextFile,async t=>(await this.handleFsWrite(e,t.params.path,t.params.content),{})).onRequest(Rm.client.terminal.create,t=>(e.info.lastActivityAt=Date.now(),a.create(t.params))).onRequest(Rm.client.terminal.output,e=>a.output(e.params.terminalId)).onRequest(Rm.client.terminal.waitForExit,e=>a.waitForExit(e.params.terminalId)).onRequest(Rm.client.terminal.kill,async e=>(await a.kill(e.params.terminalId),{})).onRequest(Rm.client.terminal.release,async e=>(await a.release(e.params.terminalId),{})).onNotification(Rm.client.session.update,t=>this.handleSessionUpdate(e,t.params)).connect(s);e.conn=c,c.closed.then(()=>{!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`exited`,`agent connection closed`)},t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] agent connection closed with error`),!e.closed&&e.info.archived!==!0&&e.info.status!==`exited`&&e.info.status!==`error`&&this.emitStatus(e,`error`,`agent connection failed: ${t instanceof Error?t.message:String(t)}`)});let l;try{l=await c.agent.request(Rm.agent.initialize,{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0},terminal:!0,session:{configOptions:{boolean:{}}}}})}catch(t){throw this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] initialize failed`),new cE(`spawn-failed`,`initialize failed: ${vE(t)}`)}return e.closed?null:(e.lastInit=l,e.info.promptCapabilities=l.agentCapabilities?.promptCapabilities??{},this.emitInfo(e),{conn:c,init:l,launch:n})}async ensureLaunchable(e,t){try{return await iT(t),await this.withLoginShellPathIfEligible(t)}catch(n){if(!(n instanceof Zw)||n.code!==`command-not-found`)throw n;let r=await this.retryWithLoginShellPath(t);if(r!==null)return r;if(t.kind!==`npx`&&t.kind!==`uvx`)throw n;let i=ST(t.kind);if(!jT(i))throw n;let a=await this.provideManagedRuntime(e,i);if(a===null)return null;let o=Gce(t,a);return await iT(o),o}}async retryWithLoginShellPath(e){let t=await this.withLoginShellPathIfEligible(e);if(aT(t.env)===aT(e.env))return null;try{await iT(t)}catch(t){if(!(t instanceof Zw))throw t;return this.opts.log.debug({cmd:e.cmd,kind:e.kind},`[acp] login-shell PATH did not resolve the command either`),null}return this.opts.log.info({cmd:e.cmd,kind:e.kind},`[acp] command resolved via the login-shell PATH; skipping the managed-runtime offer`),t}async withLoginShellPathIfEligible(e){if(e.pathFromOverlay||oT(e.cmd))return e;let t=await this.resolveLoginShellPath().catch(()=>null);return t===null?e:tT(e,t)}async provideManagedRuntime(e,t){let n=this.opts.runtimeInstall?.root;await RT(t,this.opts.log,n);let r=await FT(t,n).catch(()=>null);if(r!==null)return r;let i=(await VT(this.opts.runtimeInstall?.consentHome))[t]??await this.requestRuntimeConsent(e,t);if(i===`closed`||e.closed)return null;if(i!==`granted`)throw new Zw(`command-not-found`,gE(t));try{let n=await this.downloadRuntime(e,t);return e.closed?null:n}catch(e){let n=CT(t).displayName;throw new Zw(`install-failed`,`couldn't install ${n}: ${e instanceof Error?e.message:String(e)}`)}}requestRuntimeConsent(e,t){let n=crypto.randomUUID(),r=CT(t);return this.appendEvent(e,{kind:`runtime_consent_request`,requestId:n,runtime:t,displayName:r.displayName,provides:r.provides,version:r.version,approxSizeMB:r.approxSizeMB,sourceHost:r.sourceHost,agentName:e.info.agent.name,ts:Date.now()}),new Promise(r=>{let i=setTimeout(()=>{e.pendingRuntimeConsent.delete(n),this.appendEvent(e,{kind:`runtime_consent_resolved`,requestId:n,decision:`timeout`,ts:Date.now()}),r(`timeout`)},3e5);i.unref?.(),e.pendingRuntimeConsent.set(n,{runtime:t,resolve:r,timer:i})})}respondRuntimeConsent(e,t,n){let r=this.mustGet(e),i=r.pendingRuntimeConsent.get(t);if(i===void 0)return;r.pendingRuntimeConsent.delete(t),clearTimeout(i.timer);let a=n.kind===`granted`?`granted`:`declined`;n.remember===!0&&HT(i.runtime,a,this.opts.log,this.opts.runtimeInstall?.consentHome),this.appendEvent(r,{kind:`runtime_consent_resolved`,requestId:t,decision:a,ts:Date.now()}),i.resolve(a)}async downloadRuntime(e,t){this.emitStatus(e,`installing`);let n=0;return zT(t,this.opts.log,{root:this.opts.runtimeInstall?.root,fetchImpl:this.opts.runtimeInstall?.fetchImpl,onProgress:r=>{let i=Date.now();i-n<400||(n=i,!e.closed&&this.appendEvent(e,{kind:`runtime_install_progress`,runtime:t,phase:`downloading`,receivedBytes:r.receivedBytes,totalBytes:r.totalBytes??void 0,ts:i}))}})}async buildMcpServers(e,t){if(await this.harnessAlreadyHasOkMcp(e)!==null)return[];let n=[],r=this.opts.getServerUrl?.();if(r!==void 0&&t.agentCapabilities?.mcpCapabilities?.http===!0)n.push({type:`http`,name:`open-knowledge`,url:`${r}/mcp`,headers:[{name:Nw,value:`1`}]});else{let e=this.opts.getMcpStdioCommand?.();e!=null&&n.push({name:`open-knowledge`,command:e.command,args:[...e.args],env:[{name:Ti,value:`1`}]})}return n}async harnessAlreadyHasOkMcp(e){let t=this.opts.probeHarnessManagedMcpEntry;if(t===void 0||e.agentRef.source!==`registry`)return null;let n=Tne[e.agentRef.id];if(n===void 0)return null;let r;try{r=await t(n,e.cwd)}catch(t){return this.opts.log.warn({err:t,threadId:e.info.threadId,editorId:n},`[acp-threads] harness MCP-config probe failed — injecting OK MCP`),null}return r!==null&&this.opts.log.info({threadId:e.info.threadId,agentId:e.agentRef.id,editorId:r.editorId,scope:r.scope,configPath:r.configPath},`[acp-threads] skipping OK MCP injection — the agent's harness already loads OK's managed entry`),r}async startThread(e,t,n){let r;try{r=await this.connectAgent(e,n)}catch(t){let n=t instanceof Zw||t instanceof cE?t.message:String(t);this.emitStatus(e,`error`,n,{reason:`connect`,agentMessage:n,machineDetail:xE(e)}),await this.teardownFailedAgent(e);return}if(r===null)return;let{conn:i,init:a,launch:o}=r;await this.openSession(e,i,a,t.settings)&&(this.opts.log.info({threadId:e.info.threadId,agentId:e.info.agent.id,launchKind:o.kind,msToReady:Date.now()-e.info.createdAt},`[acp-threads] agent ready`),t.prompt!==void 0&&t.prompt!==``&&this.sendPrompt(e.info.threadId,t.prompt))}async openSession(e,t,n,r){e.info.availableCommands=null;let i=await this.buildMcpServers(e,n);try{let n=await t.agent.request(Rm.agent.session.new,{cwd:e.cwd,mcpServers:i});e.sessionId=n.sessionId,e.envNotePending=!0,this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),n.modes!==void 0&&n.modes!==null&&(e.info.modes=n.modes,this.emitInfo(e)),n.configOptions!==void 0&&n.configOptions!==null&&(e.info.configOptions=n.configOptions,this.emitInfo(e))}catch(t){let r=SE(yE(t),xE(e));return _E(t)?this.emitStatus(e,`auth_required`,`sign in required: ${vE(t)}`,{reason:`auth-required`,agentMessage:vE(t),machineDetail:r,authMethods:CE(n.authMethods)}):(this.emitStatus(e,`error`,`session setup failed: ${vE(t)}`,{reason:`session-setup`,agentMessage:vE(t),machineDetail:r}),await this.teardownFailedAgent(e)),!1}return e.closed||r?.config!==void 0&&(await this.applyInitialConfig(e,t,r.config),e.closed)||r?.modeId!==void 0&&(await this.applyInitialMode(e,t,r.modeId),e.closed)?!1:(this.emitStatus(e,`ready`),!0)}async resumeThread(e,t){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived!==!0)throw new cE(`not-ready`,`thread is not archived`);if(n.resumeInFlight)throw new cE(`not-ready`,`a resume is already in progress`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.resumeInFlight=!0;let r=Date.now();try{await this.ensureLogResolved(n);let i=n.sessionId,{info:a,custom:o}=await this.resolveAgentInfo(n.agentRef);if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);if(this.liveThreadCount()>=this.maxThreads)throw new cE(`capacity`,`maximum of ${this.maxThreads} concurrent agent threads`);n.info.agent=a,n.info.archived=!1,n.info.availableCommands=null,n.stderrTail=[],n.midTurnOnDisk&&(n.midTurnOnDisk=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),t!==void 0&&t!==``&&(this.echoUserMessage(n,t),this.flushBroadcast(n)),this.emitStatus(n,`installing`);try{if(i===null)throw new cE(`resume-unsupported`,`this thread never completed an agent session`);let a=await this.connectAgent(n,o);if(a===null)throw new cE(`not-ready`,`thread closed during resume`);let{conn:s,init:c}=a,l=await this.buildMcpServers(n,c),u=c.agentCapabilities,d=u?.sessionCapabilities?.resume!=null,f;if(d)f=await s.agent.request(Rm.agent.session.resume,{sessionId:i,cwd:n.cwd,mcpServers:l});else if(u?.loadSession===!0){n.suppressUpdates=!0,n.lastSuppressedAt=Date.now();try{f=await s.agent.request(Rm.agent.session.load,{sessionId:i,cwd:n.cwd,mcpServers:l}),await this.awaitReplayQuiescence(n)}finally{n.suppressUpdates=!1}}else throw new cE(`resume-unsupported`,`${n.info.agent.name} doesn't support resuming previous sessions`);n.sessionId=i;let p=f.modes;p!=null&&(n.info.modes=p);let m=f.configOptions;return m!=null&&(n.info.configOptions=m),this.emitStatus(n,`ready`),this.opts.log.info({threadId:e,agentId:n.info.agent.id,method:d?`session/resume`:`session/load`,msToResumed:Date.now()-r},`[acp-threads] thread resumed`),t!==void 0&&t!==``&&this.dispatchPrompt(n,t,{echo:!1}),{...n.info}}catch(t){throw await this.abortResume(n),t instanceof cE?t:t instanceof Zw?new cE(t.code===`install-failed`?`install-failed`:`spawn-failed`,t.message):(this.opts.log.warn({err:t,threadId:e},`[acp-threads] resume rejected by the agent`),new cE(`resume-unsupported`,`couldn't resume the previous session: ${vE(t)}`))}}finally{n.resumeInFlight=!1}}async retryThread(e){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let t=this.mustGet(e);if(t.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(t.info.status!==`error`&&t.info.status!==`auth_required`&&!t.authInFlight)throw new cE(`not-ready`,`this thread did not fail to start`);if(t.sessionId!==null)throw new cE(`not-ready`,`this thread already has an agent session`);if(t.resumeInFlight)throw new cE(`not-ready`,`a retry is already in progress`);t.resumeInFlight=!0;try{Bce();let{info:n,custom:r}=await this.resolveAgentInfo(t.agentRef);await this.teardownFailedAgent(t),t.info.agent=n,t.stderrTail=[],t.cancelRequested=!1,t.turnActive=!1,this.emitStatus(t,`installing`);try{await this.startThread(t,{agent:t.agentRef,settings:t.launchSettings},r)}catch(e){let n=e instanceof Error?e.message:String(e);throw this.emitStatus(t,`error`,n,{reason:`connect`,agentMessage:n}),new cE(`spawn-failed`,n)}if(t.closed)throw new cE(`not-ready`,`thread closed during retry`);let i=this.getInfo(e)?.status;if(i===`ready`||i===`running`)return this.opts.log.info({threadId:e,agentId:t.info.agent.id},`[acp-threads] thread retry succeeded`),{...t.info};throw new cE(`spawn-failed`,bE(t)??`the agent failed to start`)}finally{t.resumeInFlight=!1}}async authenticateThread(e,t){if(this.destroyed)throw new cE(`capacity`,`server is shutting down`);let n=this.mustGet(e);if(n.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it instead`);if(n.info.status!==`auth_required`)throw new cE(`not-ready`,`this thread is not waiting for a sign-in`);let r=n.conn,i=n.lastInit;if(r===null||i===null||n.child===null)throw new cE(`not-ready`,`${n.info.agent.name} is no longer running — use Retry to start it again`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is starting over — wait for the retry`);if(n.authInFlight)throw new cE(`not-ready`,`a sign-in is already in progress`);n.authInFlight=!0;try{this.emitStatus(n,`installing`);try{await this.requestAuthenticate(r,t)}catch(e){if(n.conn!==r)throw uE();let t=e instanceof lE?`the sign-in didn't complete in time — try again`:vE(e);throw this.emitStatus(n,`auth_required`,`sign-in failed: ${t}`,{reason:`auth-required`,agentMessage:t,machineDetail:SE(yE(e),xE(n)),authMethods:CE(i.authMethods)}),new cE(`not-ready`,t)}if(n.closed)throw new cE(`not-ready`,`thread closed during sign-in`);if(n.conn!==r)throw uE();if(!await this.openSession(n,r,i,n.launchSettings))throw new cE(`not-ready`,bE(n)??`${n.info.agent.name} still couldn't start a conversation`);return this.opts.log.info({threadId:e,agentId:n.info.agent.id,methodId:t},`[acp-threads] thread signed in`),{...n.info}}finally{n.authInFlight=!1}}async requestAuthenticate(e,t){let n,r=new Promise((e,t)=>{n=setTimeout(()=>t(new lE),this.authenticateTimeoutMs),n.unref?.()});try{await Promise.race([e.agent.request(Rm.agent.authenticate,{methodId:t}),r])}finally{n!==void 0&&clearTimeout(n)}}async abortResume(e){e.closed=!0,e.suppressUpdates=!1,this.failPendingPermissions(e),this.failPendingRuntimeConsent(e);try{e.conn?.close()}catch{}let t=e.child;t!==null&&await gT(t,{graceMs:sE}),e.child=null,e.conn=null,e.lastInit=null,e.closed=!1,e.turnActive=!1,this.opts.agentPresenceBroadcaster?.clearPresence(ih(e.agentSessionId)),e.info.archived=!0,this.emitStatus(e,`exited`,`resume failed`),this.flushBroadcast(e),this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e)),await this.persistence.whenIdle(e.info.threadId),e.baseSeq=e.info.lastSeq+1,e.events=[]}async awaitReplayQuiescence(e){let t=Date.now()+3e3;for(;Date.now()-e.lastSuppressedAt<300&&Date.now()<t;)await new Promise(e=>setTimeout(e,50))}sendPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`not-ready`,`thread has no live agent session`);if(n.turnActive){let e=n.info.queue??[];if(e.length>=20)throw new cE(`not-ready`,`20 messages are already waiting — let the agent catch up`);n.info.queue=[...e,{id:crypto.randomUUID(),content:t,ts:Date.now()}],n.info.lastActivityAt=Date.now(),this.emitInfo(n);return}this.dispatchPrompt(n,t,{echo:!0})}steerPrompt(e,t){let n=this.mustGet(e);if(n.info.archived===!0)throw new cE(`not-ready`,`the thread is archived — resume it first`);if(n.resumeInFlight)throw new cE(`not-ready`,`the thread is still resuming`);if(n.authInFlight)throw new cE(`not-ready`,`the thread is still signing in`);if(n.sessionId===null||n.conn===null)throw new cE(`not-ready`,`thread has no live agent session`);if(!n.turnActive){this.dispatchPrompt(n,t,{echo:!0});return}this.clearSteer(n),n.info.steer={content:t,ts:Date.now()},n.info.lastActivityAt=Date.now(),this.emitInfo(n);let r=setTimeout(()=>this.demoteStalledSteer(n),this.steerStallMs);r.unref?.(),n.steerStallTimer=r,this.cancelTurn(n,{clearQueue:!1})}demoteStalledSteer(e){e.steerStallTimer=null;let t=e.info.steer;t===void 0||e.closed||!e.turnActive||(e.info.steer=void 0,e.info.queue=[{id:crypto.randomUUID(),content:t.content,ts:t.ts},...e.info.queue??[]],this.emitInfo(e))}clearSteer(e){e.steerStallTimer!==null&&(clearTimeout(e.steerStallTimer),e.steerStallTimer=null),e.info.steer=void 0}takeSteer(e){let t=e.info.steer;return t===void 0?null:(this.clearSteer(e),t)}editQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,content:n,held:!1}:e),this.emitInfo(r),this.drainIfIdle(r),!0):!1}holdQueued(e,t,n){let r=this.mustGet(e),i=r.info.queue??[];return i.some(e=>e.id===t)?(r.info.queue=i.map(e=>e.id===t?{...e,held:n}:e),this.emitInfo(r),n||this.drainIfIdle(r),!0):!1}removeQueued(e,t){let n=this.mustGet(e),r=n.info.queue??[],i=r.filter(e=>e.id!==t);return i.length===r.length?!1:(n.info.queue=i.length>0?i:void 0,this.emitInfo(n),!0)}drainIfIdle(e){if(e.turnActive||e.closed||e.resumeInFlight||e.info.archived===!0||e.sessionId===null||e.conn===null)return;let t=this.takeNextQueued(e);t!==null&&this.dispatchPrompt(e,t.content,{echo:!0})}takeNextQueued(e){let t=e.info.queue;if(t===void 0||t.length===0)return null;let n=t.findIndex(e=>e.held!==!0);if(n===-1)return null;let r=t[n],i=[...t.slice(0,n),...t.slice(n+1)];return e.info.queue=i.length>0?i:void 0,r??null}echoUserMessage(e,t){if(e.hadUserMessage=!0,e.info.title===e.info.agent.name&&t.trim()!==``){let n=e.titleHint!==void 0&&e.titleHint.trim()!==``?e.titleHint:t;e.titleHint=void 0,e.info.title=rE(n),this.appendEvent(e,{kind:`title_changed`,title:e.info.title,ts:Date.now()}),this.emitInfo(e)}this.appendEvent(e,{kind:`user_message`,content:t,ts:Date.now()})}async renameThread(e,t){let n=this.mustGet(e);if(n.closed)throw new cE(`not-ready`,`the thread is closing`);let r=nE(t);r===``||r===n.info.title||(await this.ensureLogResolved(n),n.info.title=r,n.info.lastActivityAt=Date.now(),this.appendEvent(n,{kind:`title_changed`,title:r,ts:Date.now()}),this.flushBroadcast(n),this.emitInfo(n),await this.persistence.whenIdle(n.info.threadId))}dispatchPrompt(e,t,n){if(e.sessionId===null||e.conn===null)throw new cE(`not-ready`,`thread has no live agent session`);n.echo&&this.echoUserMessage(e,t);let r=t;e.envNotePending&&!t.startsWith(`/`)&&(e.envNotePending=!1,r=`Note on your environment: you are running inside the OpenKnowledge app, connected over ACP (Agent Client Protocol) — not inside your own terminal app. Your host CLI's terminal UI is not present, so its built-in slash commands (such as /tasks or /bashes) and keyboard shortcuts (such as Ctrl+O) do not exist here; never recommend them. The only slash commands available to the user are the ones you advertise over ACP.\n\n${t}`),e.turnActive=!0,e.cancelRequested=!1,this.appendEvent(e,{kind:`turn_started`,ts:Date.now()}),this.emitStatus(e,`running`);let i=e.sessionId;e.conn.agent.request(Rm.agent.session.prompt,{sessionId:i,prompt:[{type:`text`,text:r}]}).then(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:t.stopReason,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}let n=this.takeNextQueued(e);if(n!==null){this.dispatchPrompt(e,n.content,{echo:!0});return}}this.emitStatus(e,`ready`)}}).catch(t=>{if(e.turnActive=!1,!e.closed){if(this.appendEvent(e,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()}),e.sessionId!==null&&e.conn!==null){let t=this.takeSteer(e);if(t!==null){this.dispatchPrompt(e,t.content,{echo:!0});return}}if(e.cancelRequested){this.emitStatus(e,`ready`),this.drainIfIdle(e);return}this.emitStatus(e,`error`,`prompt failed: ${vE(t)}`,{reason:`prompt`,agentMessage:vE(t),machineDetail:SE(yE(t),xE(e))})}})}cancel(e){this.cancelTurn(this.mustGet(e),{clearQueue:!0})}cancelTurn(e,t){t.clearQueue&&(e.info.queue!==void 0||e.info.steer!==void 0)&&(e.info.queue=void 0,this.clearSteer(e),this.emitInfo(e)),!(e.conn===null||e.sessionId===null)&&(e.turnActive&&(e.cancelRequested=!0),this.failPendingPermissions(e),this.restoreRunningAfterPermission(e),e.conn.agent.notify(Rm.agent.session.cancel,{sessionId:e.sessionId}).catch(t=>{this.opts.log.debug({err:t,threadId:e.info.threadId},`[acp-threads] cancel notification never reached the agent`)}))}setMode(e,t){let n=this.mustGet(e);if(n.conn===null||n.sessionId===null)throw new cE(`not-ready`,`thread has no live agent session`);n.conn.agent.request(Rm.agent.session.setMode,{sessionId:n.sessionId,modeId:t}).then(()=>{n.info.modes&&(n.info.modes={...n.info.modes,currentModeId:t},this.emitInfo(n))}).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] set_mode failed`)})}setConfigOption(e,t,n){let r=this.mustGet(e);if(r.conn===null||r.sessionId===null)throw new cE(`not-ready`,`thread has no live agent session`);let i=typeof n==`boolean`?{sessionId:r.sessionId,configId:t,type:`boolean`,value:n}:{sessionId:r.sessionId,configId:t,value:n};r.conn.agent.request(Rm.agent.session.setConfigOption,i).then(e=>{r.info.configOptions=e.configOptions,this.emitInfo(r)}).catch(n=>{this.opts.log.warn({err:n,threadId:e,configId:t},`[acp-threads] set_config_option failed`)})}async applyInitialConfig(e,t,n){let r=e.sessionId;if(r===null)return;let i=t=>(e.info.configOptions??[]).find(e=>e.id===t)?.category===`model`,a=Object.keys(n).sort((e,t)=>Number(i(t))-Number(i(e))),o=!1,s=[];for(let i of a){let a=n[i];if(a===void 0)continue;let c=(e.info.configOptions??[]).find(e=>e.id===i);if(c===void 0||c.currentValue===a||!hE(c,a))continue;let l=typeof a==`boolean`?{sessionId:r,configId:i,type:`boolean`,value:a}:{sessionId:r,configId:i,value:a};try{let n=await t.agent.request(Rm.agent.session.setConfigOption,l);e.info.configOptions=n.configOptions,o=!0}catch(t){s.push(i),this.opts.log.warn({err:t,threadId:e.info.threadId,configId:i},`[acp-threads] initial config apply failed`)}if(e.closed)return}s.length>0&&this.opts.log.warn({threadId:e.info.threadId,rejectedConfigIds:s},`[acp-threads] some remembered config options could not be applied to the new session`),o&&this.emitInfo(e)}async applyInitialMode(e,t,n){let r=e.sessionId;if(r===null)return;let i=e.info.modes;if(i!=null&&i.availableModes.some(e=>e.id===n)){if(i.currentModeId===n)return;try{await t.agent.request(Rm.agent.session.setMode,{sessionId:r,modeId:n}),e.info.modes={...i,currentModeId:n},this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_mode`},`[acp-threads] initial mode apply failed`)}return}let a=(e.info.configOptions??[]).find(e=>e.category===`mode`&&hE(e,n));if(!(a===void 0||a.currentValue===n))try{let i=await t.agent.request(Rm.agent.session.setConfigOption,{sessionId:r,configId:a.id,value:n});e.info.configOptions=i.configOptions,this.emitInfo(e)}catch(t){this.opts.log.warn({err:t,threadId:e.info.threadId,modeId:n,method:`set_config_option`},`[acp-threads] initial mode apply failed`)}}respondPermission(e,t,n){let r=this.mustGet(e),i=r.pendingPermissions.get(t);i!==void 0&&(r.pendingPermissions.delete(t),clearTimeout(i.timer),n.kind===`selected`?(i.resolve({outcome:{outcome:`selected`,optionId:n.optionId}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:n.optionId,auto:!1,ts:Date.now()})):(i.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(r,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!1,ts:Date.now()})),this.restoreRunningAfterPermission(r))}restoreRunningAfterPermission(e){e.pendingPermissions.size===0&&e.turnActive&&e.info.status===`awaiting_permission`&&this.emitStatus(e,`running`)}async closeThread(e,t){let n=this.threads.get(e);if(n===void 0||n.info.archived===!0||n.closed)return;n.closed=!0,this.clearSteer(n),this.failPendingPermissions(n),this.failPendingRuntimeConsent(n);try{n.conn?.close()}catch{}let r=n.child;r!==null&&(await gT(r,{graceMs:t?.killGraceMs??oE})||this.opts.log.error({threadId:e,pid:r.pid},`[acp-threads] agent process survived SIGKILL escalation`)),n.child=null,n.conn=null,n.lastInit=null,await n.terminals?.disposeAll(),n.terminals=null,this.opts.agentPresenceBroadcaster?.clearPresence(ih(n.agentSessionId)),await this.opts.sessionManager.closeAllForAgent(n.agentSessionId).catch(t=>{this.opts.log.warn({err:t,threadId:e},`[acp-threads] session cleanup failed`)});let i=n.info.status===`error`||n.info.status===`auth_required`;if(!n.hadUserMessage&&!i){this.threads.delete(e),n.subscribers.clear(),n.flushTimer!==null&&(clearTimeout(n.flushTimer),n.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] empty thread discarded on close`);return}n.turnActive&&(n.turnActive=!1,this.appendEvent(n,{kind:`turn_ended`,stopReason:`cancelled`,ts:Date.now()})),n.info.archived=!0,this.emitStatus(n,`exited`,`thread closed`),this.flushBroadcast(n),this.persistence.queueMetaWrite(e,this.buildMeta(n)),await this.persistence.whenIdle(e),n.baseSeq=n.info.lastSeq+1,n.events=[],n.pendingBroadcast=[],n.closed=!1,this.opts.log.info({threadId:e},`[acp-threads] thread archived`)}async deleteThread(e){let t=this.mustGet(e);if(t.info.archived!==!0)throw new cE(`not-ready`,`close the thread before deleting it`);if(t.resumeInFlight)throw new cE(`not-ready`,`a resume is in progress`);this.threads.delete(e),t.subscribers.clear(),t.flushTimer!==null&&(clearTimeout(t.flushTimer),t.flushTimer=null),await this.persistence.whenIdle(e),await this.persistence.delete(e),this.opts.log.info({threadId:e},`[acp-threads] thread deleted`)}async destroy(){this.destroyed=!0,clearInterval(this.reapTimer),await Promise.allSettled([...this.threads.keys()].map(e=>this.closeThread(e,{killGraceMs:sE})))}async handlePermissionRequest(e,t,n){e.info.lastActivityAt=Date.now();let r=this.opts.permissions.decide(e.info.agent.id,t,n);if(r.auto!==null){let t=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:r.auto.optionId,auto:!0,ts:Date.now()}),{outcome:{outcome:`selected`,optionId:r.auto.optionId}}}let i=crypto.randomUUID();return this.appendEvent(e,{kind:`permission_request`,requestId:i,toolCall:t,options:n,ts:Date.now()}),e.turnActive&&e.info.status===`running`&&this.emitStatus(e,`awaiting_permission`),new Promise(r=>{let a=setTimeout(()=>{e.pendingPermissions.delete(i),this.appendEvent(e,{kind:`permission_resolved`,requestId:i,optionId:null,auto:!0,ts:Date.now()}),this.restoreRunningAfterPermission(e),r({outcome:{outcome:`cancelled`}})},6e5);a.unref?.(),e.pendingPermissions.set(i,{timer:a,resolve:i=>{if(i.outcome.outcome===`selected`){let r=n.find(e=>i.outcome.outcome===`selected`&&e.optionId===i.outcome.optionId);r!==void 0&&this.opts.permissions.recordChoice(e.info.agent.id,t,r)}r(i)}})})}handleSessionUpdate(e,t){e.info.lastActivityAt=Date.now();let n=t.update;if(n.sessionUpdate===`current_mode_update`&&e.info.modes&&(e.info.modes={...e.info.modes,currentModeId:n.currentModeId},this.emitInfo(e)),n.sessionUpdate===`config_option_update`&&(e.info.configOptions=n.configOptions,this.emitInfo(e)),n.sessionUpdate===`available_commands_update`&&(e.info.availableCommands=n.availableCommands,this.emitInfo(e)),e.suppressUpdates){e.lastSuppressedAt=Date.now();return}this.appendEvent(e,{kind:`session_update`,update:Oce(n),ts:Date.now()})}async handleFsRead(e,t,n){let r=await this.confinePath(e),i;if(i=r.docName===null?await _u(r.abs,`utf8`):this.opts.getLoadedDocText?.(r.docName)??await _u(r.abs,`utf8`),t!==null||n!==null){let e=i.split(`
26
26
  `),r=Math.max((t??1)-1,0),a=n===null?e.length:r+n;i=e.slice(r,a).join(`
27
- `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=it(r,Sw(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-DtlsFK7O.mjs`);await e(I(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return pE(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new cE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&Ace(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>aE){let t=e.events.length-aE;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await gT(t,{graceMs:oE})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,steer:n,...r}=e.info;return{version:1,info:r,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=qr(e.info.agent.id),i=xa[r]??Ui(e.agentSessionId);n.setPresence(ih(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function pE(e,t,n){let r=await yu(e),i=Rl(Ll(t)?t:z(r,t)),a=i,o=``;for(;;)try{let e=await yu(a),i=o===``?e:L(e,o),s=R(r,i);if(s===``||s.startsWith(`..`)||Ll(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Vl).join(`/`),t=s.split(Vl).join(`/`);!Zx(e)&&!Qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Vl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=I(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):L(a.slice(t.length+1),o),a=t}}function mE(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function hE(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function gE(e){let t=CT(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function _E(e){return typeof e==`object`&&!!e&&e.code===-32e3}function vE(e){return e instanceof Error?e.message:String(e)}function yE(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function bE(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function xE(e){let t=e.stderrTail.join(`
27
+ `)}return{content:i}}async handleFsWrite(e,t,n){e.info.lastActivityAt=Date.now();let r=await this.confinePath(t);if(r.docName!==null){let t=await this.opts.sessionManager.getSession(r.docName,e.agentSessionId,{displayName:e.info.agent.name,colorSeed:e.agentSessionId,clientName:e.info.agent.id}),i=this.opts.resolveEmbed===void 0?void 0:{resolveEmbed:this.opts.resolveEmbed,sourcePath:r.rel};t.dc.document.transact(()=>{let r=Sw(t.dc.document);xw(t.dc.document,n,`replace`,i,void 0,yw(t));let a=it(r,Sw(t.dc.document))??void 0;t.dc.document.getMap(`agent-flash`).set(e.agentSessionId,{agentId:e.agentSessionId,timestamp:Date.now(),type:`insert`,description:`Added (${e.info.agent.name}): ${n.slice(0,50)}`,...a===void 0?{}:{changedBlocks:a}})},t.origin),this.setPresence(e,r.docName)}else{if(this.opts.isIgnoredPath(r.rel))throw Error(`path is excluded from the project content scope: ${t}`);let{tracedMkdir:e,tracedWriteFile:i}=await import(`./fs-traced-CChInc-O.mjs`);await e(I(r.abs),{recursive:!0}),await i(r.abs,n)}}confinePath(e){return pE(this.opts.contentDir,e,this.opts.isExcludedPath)}mustGet(e){let t=this.threads.get(e);if(t===void 0)throw new cE(`unknown-thread`,`no thread '${e}'`);return t}appendEvent(e,t){let n=e.pendingBroadcast;if(n.length>0&&Ace(n[n.length-1],t))return;let r=e.baseSeq+e.events.length;if(e.events.push(t),e.info.lastSeq=r,e.events.length>aE){let t=e.events.length-aE;e.events.splice(0,t),e.baseSeq+=t}e.pendingBroadcast.length===0&&(e.pendingBroadcastFromSeq=r),e.pendingBroadcast.push(t),e.flushTimer===null&&(e.flushTimer=setTimeout(()=>this.flushBroadcast(e),25),e.flushTimer.unref?.())}flushBroadcast(e){if(e.flushTimer!==null&&(clearTimeout(e.flushTimer),e.flushTimer=null),e.pendingBroadcast.length===0)return;let t={op:`events`,threadId:e.info.threadId,fromSeq:e.pendingBroadcastFromSeq,events:e.pendingBroadcast};this.persistence.appendEvents(e.info.threadId,e.pendingBroadcast),e.pendingBroadcast=[];for(let n of e.subscribers)try{n(t)}catch{}}emitStatus(e,t,n,r){(t===`exited`||t===`error`)&&(e.info.queue=void 0,this.clearSteer(e)),e.info.status=t,e.info.lastActivityAt=Date.now(),(t===`error`||t===`auth_required`)&&this.opts.log.warn({threadId:e.info.threadId,agentId:e.info.agent.id,status:t,detail:n,reason:r?.reason},`[acp-threads] thread failure status`),this.appendEvent(e,{kind:`status`,status:t,detail:n,...r===void 0?{}:{failure:r},ts:Date.now()}),this.emitInfo(e)}async teardownFailedAgent(e){let t=e.child,n=e.conn,r=e.terminals;e.child=null,e.conn=null,e.lastInit=null,e.terminals=null;try{n?.close()}catch{}await r?.disposeAll().catch(t=>{this.opts.log.warn({err:t,threadId:e.info.threadId},`[acp-threads] terminal cleanup on failed-agent teardown failed`)}),t!==null&&await gT(t,{graceMs:oE})}emitInfo(e){this.persistence.queueMetaWrite(e.info.threadId,this.buildMeta(e));for(let t of e.subscribers)try{t({op:`info`,info:{...e.info}})}catch{}}buildMeta(e){let{queue:t,steer:n,...r}=e.info;return{version:1,info:r,sessionId:e.sessionId,cwd:e.cwd,agentRef:e.agentRef,docName:e.docName}}failPendingPermissions(e){for(let[t,n]of e.pendingPermissions)clearTimeout(n.timer),n.resolve({outcome:{outcome:`cancelled`}}),this.appendEvent(e,{kind:`permission_resolved`,requestId:t,optionId:null,auto:!0,ts:Date.now()});e.pendingPermissions.clear()}failPendingRuntimeConsent(e){for(let t of e.pendingRuntimeConsent.values())clearTimeout(t.timer),t.resolve(`closed`);e.pendingRuntimeConsent.clear()}setPresence(e,t){let n=this.opts.agentPresenceBroadcaster;if(n!=null)try{let r=qr(e.info.agent.id),i=xa[r]??Ui(e.agentSessionId);n.setPresence(ih(e.agentSessionId),{displayName:e.info.agent.name,icon:r,color:i,currentDoc:t,mode:`writing`,ts:Date.now()})}catch(e){this.opts.log.warn({err:e},`[acp-threads] presence update failed`)}}reapIdleThreads(){let e=Date.now(),t=e-this.idleReapMs;for(let n of this.threads.values()){if(n.info.archived===!0)continue;if(n.subscribers.size===0&&!n.turnActive&&n.info.lastActivityAt<t){this.opts.log.info({threadId:n.info.threadId},`[acp-threads] reaping idle thread`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] reap failed`)});continue}if(!n.turnActive||n.unwatchedSince===null)continue;let r=e-n.unwatchedSince;r>=this.unwatchedTurnKillMs?(this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] force-closing unwatched turn that ignored cancel`),this.closeThread(n.info.threadId).catch(e=>{this.opts.log.error({err:e,threadId:n.info.threadId},`[acp-threads] force-close failed`)})):r>=this.unwatchedTurnCancelMs&&!n.unwatchedCancelSent&&(n.unwatchedCancelSent=!0,this.opts.log.warn({threadId:n.info.threadId,unwatchedFor:r},`[acp-threads] cancelling turn running with zero subscribers`),this.cancel(n.info.threadId))}}};async function pE(e,t,n){let r=await yu(e),i=Rl(Ll(t)?t:z(r,t)),a=i,o=``;for(;;)try{let e=await yu(a),i=o===``?e:L(e,o),s=R(r,i);if(s===``||s.startsWith(`..`)||Ll(s))throw Error(`path escapes the content directory: ${t}`);let c=/\.(md|mdx)$/.exec(s),l=null;if(c!==null){let e=s.slice(0,-c[0].length).split(Vl).join(`/`),t=s.split(Vl).join(`/`);!Zx(e)&&!Qx(e)&&!n(t)&&(l=e)}return{abs:i,rel:s.split(Vl).join(`/`),docName:l}}catch(e){if(e.code!==`ENOENT`)throw e;let t=I(a);if(t===a)throw e;o=o===``?i.slice(t.length+1):L(a.slice(t.length+1),o),a=t}}function mE(e){let t=e.info.status===`error`?`error`:`exited`;return{info:{...e.info,status:t,archived:!0,queue:void 0,steer:void 0},docName:e.docName,agentRef:e.agentRef,cwd:e.cwd,child:null,conn:null,lastInit:null,sessionId:e.sessionId,agentSessionId:`acp-${e.info.threadId}`,events:[],baseSeq:e.info.lastSeq+1,logResolved:!1,logResolution:null,midTurnOnDisk:!1,resumeInFlight:!1,authInFlight:!1,suppressUpdates:!1,lastSuppressedAt:0,subscribers:new Set,pendingPermissions:new Map,pendingRuntimeConsent:new Map,stderrTail:[],terminals:null,turnActive:!1,cancelRequested:!1,steerStallTimer:null,unwatchedSince:null,unwatchedCancelSent:!1,pendingBroadcast:[],pendingBroadcastFromSeq:0,flushTimer:null,closed:!1,hadUserMessage:!0,envNotePending:!1}}function hE(e,t){if(typeof t==`boolean`)return e.type===`boolean`;if(e.type!==`select`)return!1;for(let n of e.options)if(`value`in n){if(n.value===t)return!0}else if(n.options.some(e=>e.value===t))return!0;return!1}function gE(e){let t=CT(e),n=e===`node`?`https://nodejs.org`:`https://docs.astral.sh/uv/getting-started/installation/`;return`This agent needs \`${t.provides}\`, which isn't installed. OK can download a private copy of ${t.displayName} for you, or install ${t.displayName} yourself (${n}) and it'll be used automatically.`}function _E(e){return typeof e==`object`&&!!e&&e.code===-32e3}function vE(e){return e instanceof Error?e.message:String(e)}function yE(e){if(typeof e!=`object`||!e)return;let t=e.data;if(t!=null)try{return JSON.stringify(t).slice(0,300)}catch{return}}function bE(e){for(let t=e.events.length-1;t>=0;--t){let n=e.events[t];if(!(n===void 0||n.kind!==`status`)&&!(n.status!==`error`&&n.status!==`auth_required`))return n.detail??n.failure?.agentMessage}}function xE(e){let t=e.stderrTail.join(`
28
28
  `);return t===``?void 0:t}function SE(...e){let t=e.filter(e=>e!==void 0&&e!==``).join(`
29
29
  `);return t===``?void 0:t}function CE(e){return(e??[]).flatMap(e=>{if(typeof e!=`object`||!e)return[];let{id:t,name:n,description:r,type:i}=e;return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,name:n,...typeof r==`string`?{description:r}:{},...typeof i==`string`?{kind:i}:{}}]})}const wE=new Set([`create`,`subscribe`,`unsubscribe`,`prompt`,`steer`,`queue_edit`,`queue_hold`,`queue_remove`,`permission_response`,`runtime_consent_response`,`cancel`,`set_mode`,`set_config_option`,`close`,`rename`,`resume`,`retry`,`authenticate`,`delete`,`list`]);function Yce(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!=`object`||!t)return null;let n=t;if(typeof n.op!=`string`||!wE.has(n.op))return null;let r=e=>typeof n[e]==`string`&&n[e]!==``;switch(n.op){case`create`:{if(!r(`reqId`))return null;let e=n.agent;if(typeof e!=`object`||!e||e.source!==`registry`&&e.source!==`custom`||typeof e.id!=`string`||e.id===``||n.prompt!==void 0&&typeof n.prompt!=`string`||n.docName!==void 0&&typeof n.docName!=`string`)return null;if(n.settings!==void 0){let e=n.settings;if(typeof e!=`object`||!e)return null;if(e.config!==void 0){let t=e.config;if(typeof t!=`object`||!t||Array.isArray(t))return null;for(let e of Object.values(t))if(typeof e!=`string`&&typeof e!=`boolean`)return null}if(e.modeId!==void 0&&typeof e.modeId!=`string`)return null}return n}case`subscribe`:return!r(`threadId`)||n.sinceSeq!==void 0&&typeof n.sinceSeq!=`number`?null:n;case`prompt`:return!r(`threadId`)||!r(`reqId`)||typeof n.content!=`string`?null:n;case`steer`:return!r(`threadId`)||!r(`reqId`)||!r(`content`)?null:n;case`queue_edit`:return!r(`threadId`)||!r(`id`)||!r(`content`)||n.reqId!==void 0&&!r(`reqId`)?null:n;case`queue_hold`:return!r(`threadId`)||!r(`id`)||typeof n.held!=`boolean`?null:n;case`queue_remove`:return!r(`threadId`)||!r(`id`)?null:n;case`permission_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;if(typeof e!=`object`||!e)return null;if(e.kind===`selected`){if(typeof e.optionId!=`string`||e.optionId===``)return null}else if(e.kind!==`cancelled`)return null;return n}case`runtime_consent_response`:{if(!r(`threadId`)||!r(`requestId`))return null;let e=n.outcome;return typeof e!=`object`||!e||e.kind!==`granted`&&e.kind!==`declined`||e.remember!==void 0&&typeof e.remember!=`boolean`?null:n}case`set_mode`:return!r(`threadId`)||!r(`modeId`)?null:n;case`rename`:return!r(`threadId`)||!r(`title`)?null:n;case`set_config_option`:return!r(`threadId`)||!r(`configId`)||typeof n.value!=`string`&&typeof n.value!=`boolean`||n.value===``?null:n;case`resume`:return!r(`threadId`)||!r(`reqId`)||n.prompt!==void 0&&typeof n.prompt!=`string`?null:n;case`retry`:return!r(`threadId`)||!r(`reqId`)?null:n;case`authenticate`:return!r(`threadId`)||!r(`reqId`)||!r(`methodId`)?null:n;case`unsubscribe`:case`cancel`:case`close`:case`delete`:return r(`threadId`)?n:null;case`list`:return n;default:return null}}function TE(e,t,n){let r=new Map,i=t=>{try{e.send(JSON.stringify(t))}catch(e){n.warn({err:e},`[acp-thread-socket] send failed`)}},a=(e,t,n)=>i(Xce(e,t,n));e.on(`message`,e=>{let s=Yce(typeof e==`string`?e:Buffer.isBuffer(e)?e.toString(`utf8`):``);if(s===null){a(`bad-frame`,`unrecognized frame`);return}(async()=>{try{switch(s.op){case`list`:i({op:`threads`,threads:t.listThreads()});return;case`create`:{let e=await t.createThread({agent:s.agent,prompt:s.prompt,docName:s.docName,titleHint:s.titleHint,settings:s.settings});i({op:`created`,reqId:s.reqId,info:e}),await o(e.threadId,0);return}case`subscribe`:await o(s.threadId,s.sinceSeq??0);return;case`resume`:{let e=await t.resumeThread(s.threadId,s.prompt);i({op:`resumed`,reqId:s.reqId,info:e}),await o(s.threadId,0);return}case`retry`:{let e=await t.retryThread(s.threadId);i({op:`retried`,reqId:s.reqId,info:e});return}case`authenticate`:{let e=await t.authenticateThread(s.threadId,s.methodId);i({op:`authenticated`,reqId:s.reqId,info:e});return}case`delete`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.deleteThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}case`unsubscribe`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId));return}case`prompt`:t.sendPrompt(s.threadId,s.content);return;case`steer`:t.steerPrompt(s.threadId,s.content);return;case`queue_edit`:{let e=t.editQueued(s.threadId,s.id,s.content);s.reqId!==void 0&&(e?i({op:`queue_edited`,reqId:s.reqId,threadId:s.threadId}):a(`not-ready`,`queued message already dispatched`,{reqId:s.reqId,threadId:s.threadId}));return}case`queue_hold`:t.holdQueued(s.threadId,s.id,s.held);return;case`queue_remove`:t.removeQueued(s.threadId,s.id);return;case`permission_response`:t.respondPermission(s.threadId,s.requestId,s.outcome);return;case`runtime_consent_response`:t.respondRuntimeConsent(s.threadId,s.requestId,s.outcome);return;case`cancel`:t.cancel(s.threadId);return;case`set_mode`:t.setMode(s.threadId,s.modeId);return;case`rename`:await t.renameThread(s.threadId,s.title);return;case`set_config_option`:t.setConfigOption(s.threadId,s.configId,s.value);return;case`close`:{let e=r.get(s.threadId);e!==void 0&&(t.unsubscribe(s.threadId,e),r.delete(s.threadId)),await t.closeThread(s.threadId),i({op:`threads`,threads:t.listThreads()});return}}}catch(e){e instanceof cE?a(e.code,e.message,{reqId:`reqId`in s?s.reqId:void 0,threadId:`threadId`in s?s.threadId:void 0}):(n.error({err:e,op:s.op},`[acp-thread-socket] frame handling failed`),a(`internal`,`internal error`,{reqId:`reqId`in s?s.reqId:void 0}))}})()});let o=async(e,n)=>{if(r.has(e))return;let o=e=>i(e);r.set(e,o);try{let s=t.getInfo(e);if(s===void 0){r.delete(e),a(`unknown-thread`,`no thread '${e}'`,{threadId:e});return}i({op:`subscribed`,threadId:e,fromSeq:Math.max(n,0),info:s}),await t.subscribe(e,n,o)}catch(t){if(r.delete(e),t instanceof cE)a(t.code,t.message,{threadId:e});else throw t}};e.on(`close`,()=>{for(let[e,n]of r)t.unsubscribe(e,n);r.clear()}),e.on(`error`,e=>{n.warn({err:e},`[acp-thread-socket] socket error`)})}function Xce(e,t,n){return{op:`error`,code:e,message:t,...n}}var EE=class{hocuspocus;log=F(`agent-focus`);warnedMissing=!1;constructor(e){this.hocuspocus=e}setFocus(e,t){ah(e)&&this.mutateAgentFocus(n=>({...n,[e]:t}))}clearFocus(e){ah(e)&&this.mutateAgentFocus(t=>{if(!(e in t))return t;let{[e]:n,...r}=t;return r})}getFocusMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentFocus??{}:{}}mutateAgentFocus(e){let t=this.resolveAwareness();if(t)try{let n=t.getLocalState()??{},r=e(n.agentFocus??{});t.setLocalState({...n,agentFocus:r})}catch(e){this.log.error({err:e},`[agent-focus] awareness mutation failed`)}}resolveAwareness(){let e=this.hocuspocus.documents.get(ga);return e?(this.warnedMissing&&=(this.log.info({},`[agent-focus] __system__ document now available — resuming focus updates`),!1),Zce(e)):(this.warnedMissing||=(this.log.warn({},`[agent-focus] __system__ document not found — focus updates will be dropped until it is materialized`),!0),null)}};function Zce(e){return e?.awareness??null}var DE=class{hocuspocus;log=F(`agent-presence`);warnedMissing=!1;destroyed=!1;constructor(e){this.hocuspocus=e}setPresence(e,t){if(!ah(e))return;let n=0;this.mutateAgentPresence(r=>{let i=Date.now(),a={};for(let[t,o]of Object.entries(r)){if(i-o.ts>=2e4&&t!==e){n++;continue}a[t]=o}return a[e]=t,a})&&(this.log.debug({agentId:e,action:`set`,currentDoc:t.currentDoc,ts:t.ts},`[agent-presence] set`),n>0&&this.log.info({evictedCount:n,thresholdMs:2e4},`[agent-presence] evicted stale entries`))}clearPresence(e){if(!ah(e))return;let t=!1;this.mutateAgentPresence(n=>{if(!n[e])return n;t=!0;let{[e]:r,...i}=n;return i})&&t&&this.log.info({agentId:e,action:`clear`,currentDoc:null,ts:Date.now()},`[agent-presence] clear`)}touchMode(e,t){if(!ah(e))return;let n=[],r=!1,i=this.mutateAgentPresence(i=>{let a=i[e];if(!a)return i;r=!0;let o=Date.now();return n.push({currentDoc:a.currentDoc,ts:o}),{...i,[e]:{...a,mode:t,ts:o}}}),a=n[0];i&&a?this.log.debug({agentId:e,action:`touchMode`,currentDoc:a.currentDoc,ts:a.ts,mode:t},`[agent-presence] touchMode`):r||this.log.debug({agentId:e,action:`touchMode`,mode:t,reason:`entry-missing`},`[agent-presence] touchMode skipped — no entry for agentId`)}bumpPresenceTs(e){if(!ah(e))return;let t=null;this.mutateAgentPresence(n=>{let r=n[e];if(!r)return n;let i=Date.now();return t=i,{...n,[e]:{...r,ts:i}}}),t!==null&&this.log.debug({agentId:e,action:`bumpTs`,ts:t},`[agent-presence] bumpTs`)}getPresenceMap(){let e=this.resolveAwareness();return e?e.getLocalState()?.agentPresence??{}:{}}destroy(){this.destroyed=!0}mutateAgentPresence(e){if(this.destroyed)return!1;let t=this.resolveAwareness();if(!t)return!1;try{let n=t.getLocalState()??{},r=e(n.agentPresence??{});return t.setLocalState({...n,agentPresence:r}),!0}catch(e){return mse(),this.log.error({err:e},`[agent-presence] awareness mutation failed`),!1}}resolveAwareness(){let e=this.hocuspocus.documents.get(ga);return e?(this.warnedMissing&&=(this.log.info({},`[agent-presence] __system__ document now available — resuming presence updates`),!1),Qce(e)):(this.warnedMissing||=(this.log.warn({},`[agent-presence] __system__ document not found — presence updates will be dropped until it is materialized`),!0),null)}};function Qce(e){return e?.awareness??null}var OE=class extends Error{};const $ce=[`/.well-known/agent-skills/index.json`,`/.well-known/skills/index.json`],kE=1024*1024;async function AE(e,t,n,r){let i=t;for(let t=0;t<=5;t++){let t=await e(i,{...r,redirect:`manual`});if(t.status<300||t.status>=400)return t;let a=t.headers.get(`location`);if(a===null||a===``)throw new OE(`Website skill redirect carried no location: ${i}`);let o;try{o=new URL(a,i)}catch{throw new OE(`Website skill redirect target is not a URL: ${a}`)}if(o.protocol!==`https:`||o.origin!==n)throw new OE(`Website skill redirect left the origin (${n}): ${o.href}`);i=o.href}throw new OE(`Website skill fetch exceeded 5 redirects: ${t}`)}function jE(e){let t;try{t=new URL(e)}catch{throw new OE(`Invalid website skill origin: ${e}`)}if(t.protocol!==`https:`||t.username||t.password)throw new OE(`Website skill origins must be credential-free HTTPS URLs: ${e}`);if(t.pathname!==`/`||t.search||t.hash)throw new OE(`Website skill origins cannot include a path, query, or fragment: ${e}`);return t.origin}function ME(e){return!e||e.includes(`\\`)||e.includes(`\0`)||e.startsWith(`/`)?!1:e.split(`/`).every(e=>e!==``&&e!==`.`&&e!==`..`)}function ele(e){if(!e||typeof e!=`object`)return null;let t=e.skills;if(!Array.isArray(t))return null;let n=[];for(let e of t){if(!e||typeof e!=`object`)return null;let{name:t,description:r,files:i}=e;if(typeof t!=`string`||!ME(t)||t.includes(`/`)||r!==void 0&&typeof r!=`string`||!Array.isArray(i)||i.length===0||i.length>513||!i.every(e=>typeof e==`string`&&ME(e))||new Set(i).size!==i.length||!i.includes(`SKILL.md`))return null;n.push({name:t,description:r??``,files:i})}return n}function tle(e,t,n,r){let i=[n,...r.split(`/`)].map(encodeURIComponent).join(`/`);return new URL(`${t}/${i}`,e).href}async function NE(e,t,n){let r=[];for(let i of $ce){let a=new URL(i,e).href;try{let o=await AE(t,a,e,{signal:AbortSignal.timeout(n)});if(!o.ok){r.push(`${i}: HTTP ${o.status}`);continue}let s=await o.text();if(Buffer.byteLength(s)>kE){r.push(`${i}: index exceeds ${kE} bytes`);continue}let c;try{c=JSON.parse(s)}catch{r.push(`${i}: response is not JSON`);continue}let l=ele(c);if(!l){r.push(`${i}: unsupported or malformed index`);continue}return{basePath:i.slice(0,-11),skills:l}}catch(e){r.push(`${i}: ${e instanceof Error?e.message:String(e)}`)}}throw new OE(`No usable website skill index at ${e} (${r.join(`; `)})`)}async function nle(e,t={}){let{skills:n}=t.index??await PE(e,t);return n.map(({name:e,description:t})=>({name:e,description:t}))}async function PE(e,t={}){let n=jE(e),r=t.fetchImpl??globalThis.fetch;if(!r)throw new OE(`No fetch implementation available.`);return NE(n,r,t.timeoutMs??15e3)}async function rle(e,t={}){if(!ME(e.skill)||e.skill.includes(`/`))throw new OE(`Invalid website skill name: ${e.skill}`);let n=jE(e.origin),r=t.fetchImpl??globalThis.fetch;if(!r)throw new OE(`No fetch implementation available.`);let i=t.timeoutMs??15e3,{basePath:a,skills:o}=t.index??await NE(n,r,i),s=o.find(t=>t.name===e.skill);if(!s)throw new OE(`Website skill index does not contain ${e.skill}`);let c=Zl(L(pu(),`ok-skill-site-`)),l=L(c,s.name),u=0;try{let e=[...s.files],t=async e=>{let t=await AE(r,tle(n,a,s.name,e),n,{signal:AbortSignal.timeout(i)});if(!t.ok)throw new OE(`Website skill file returned HTTP ${t.status}: ${e}`);let o=Number(t.headers.get(`content-length`));if(Number.isFinite(o)&&o>16777216)throw new OE(`Website skill file exceeds ${qt} bytes: ${e}`);let c=new Uint8Array(await t.arrayBuffer());if(c.byteLength>16777216)throw new OE(`Website skill file exceeds ${qt} bytes: ${e}`);if(u+=c.byteLength,u>67108864)throw new OE(`Website skill bundle exceeds ${dn} bytes.`);let d=L(l,...e.split(`/`));Xl(I(d),{recursive:!0}),cu(d,c)};return await Promise.all(Array.from({length:Math.min(8,e.length)},async()=>{for(let n=e.shift();n!==void 0;n=e.shift())await t(n)})),{dir:l,cleanup:()=>iu(c,{recursive:!0,force:!0})}}catch(t){throw iu(c,{recursive:!0,force:!0}),t instanceof OE?t:new OE(`Could not fetch website skill ${e.skill}: ${t instanceof Error?t.message:String(t)}`)}}const ile=Au(Al),ale=/^(?:github\s+)?([\w.-]+)\/([\w.-]+?)(?:\.git)?(?:\/(.+))?$/,FE=[/^https?:\/\//i,/^ssh:\/\//i,/^git:\/\//i,/^git@[^:]+:/];function IE(e){let t=e.trim();if(t===``)return null;if(t.startsWith(`file://`))return{kind:`local`,path:t.slice(7)};if(t.startsWith(`/`)||t.startsWith(`.`)||t.startsWith(`~`))return{kind:`local`,path:t};if(t.startsWith(`git@`)||t.includes(`://`))return FE.some(e=>e.test(t))?{kind:`git`,url:t}:null;let n=ale.exec(t);if(n){let[,e,t,r]=n;return{kind:`git`,url:`https://github.com/${e}/${t}.git`,subpath:r}}return null}function LE(e){let t=e.trim();if(t===``)return null;let n=e=>{let t=e.split(`/`).filter(Boolean).map(decodeURIComponent);if(t.length!==3)return null;let[n,r,i]=t,a=n===`site`?r:n,o=i;return a&&o?{owner:a,skill:o}:null};if(/^https?:\/\//i.test(t))try{let e=new URL(t),r=e.hostname.toLowerCase();return r!==`skills.sh`&&r!==`www.skills.sh`?null:n(e.pathname)}catch{return null}let r=/^skills\.sh\/(.+)$/i.exec(t);if(r)return n(r[1]??``);let i=/^skills\.sh\s+([\w.-]+)\/([\w.-]+)$/i.exec(t);if(i){let[,e,t]=i;return e&&t?{owner:e,skill:t}:null}return null}async function RE(e,t={}){if(e.kind===`well-known`)return rle(e,t);if(e.kind===`local`){let t=z(e.path.replace(/^~(?=\/|$)/,process.env.HOME??`~`));if(!B(t))throw new OE(`Local path not found: ${t}`);return{dir:t,cleanup:()=>{}}}if(/^[a-z][a-z0-9+.-]+:/i.test(e.url)&&!FE.some(t=>t.test(e.url)))throw new OE(`Unsupported git transport: ${e.url}`);let n=Zl(L(pu(),`ok-skill-import-`));try{await ile(`git`,[`-c`,`core.symlinks=false`,`clone`,`-q`,`--depth`,`1`,`--`,e.url,n],{timeout:6e4,maxBuffer:16*1024*1024,env:{...process.env,GIT_TERMINAL_PROMPT:`0`}})}catch(t){iu(n,{recursive:!0,force:!0});let r=t instanceof Error?t.message:String(t);throw new OE(`git clone failed for ${e.url}: ${r}`)}let r;try{r=Rte(`git`,[`-C`,n,`rev-parse`,`HEAD`],{stdio:`pipe`}).toString().trim()}catch{}let i=e.subpath?z(n,e.subpath):n,a=R(n,i);if(a.startsWith(`..`)||Ll(a))throw iu(n,{recursive:!0,force:!0}),new OE(`subpath escapes the clone: ${e.subpath}`);if(!B(i))throw iu(n,{recursive:!0,force:!0}),new OE(`subpath not found in repo: ${e.subpath}`);return{dir:i,ref:r,cleanup:()=>iu(n,{recursive:!0,force:!0})}}const zE=[`.ok`,`skills-lock.json`],ole=ve({source:u(),pluginProvider:u().optional(),skill:u().optional(),ref:u().optional(),contentHash:u(),files:P(u()).optional(),localHash:u().optional(),baselineRef:u().optional(),publisher:u().optional(),importedAt:a(),autoUpdate:D().optional()}),sle=ve({schema:x(1),skills:C(u(),ole).default({})});function BE(){return{schema:1,skills:{}}}function VE(e){let t;try{t=JSON.parse(e)}catch{return null}let n=sle.safeParse(t);return n.success?n.data:null}function HE(e,t,n){return{...e,skills:{...e.skills,[t]:n}}}const cle=new Set(Object.values(xr));function lle(e,t,n,r){return e.startsWith(`open-knowledge-pack-`)?UE(e,t,n):!cle.has(e)||r?.selfIdentifiesAsPack!==!0?null:UE(e,t,n)}function UE(e,t,n){return{source:Wt,skill:e,contentHash:t,importedAt:n}}function ule(e,t){for(let[n,r]of Object.entries(e.skills))if(r.contentHash===t)return n;return null}function WE(e,t){let n=t,r=``,{frontmatter:i}=jt(e);if(i!==``){let{map:e}=En(Xt(i)),t=e?.name,a=e?.description;typeof t==`string`&&t.trim()!==``&&(n=t),typeof a==`string`&&(r=a)}return{name:n,description:r}}const GE=new Set([`.git`,`node_modules`]),dle=new Set([...GE,`scripts`,`references`]);function fle(e){let t=[],n=r=>{for(let i of tu(r,{withFileTypes:!0})){let a=L(r,i.name);if(i.isDirectory()){GE.has(i.name)||n(a);continue}if(!i.isFile())continue;let o=R(e,a).split(`\\`).join(`/`);if(o===`SKILL.md`)continue;let s=V(a);t.push(s.includes(0)?{relPath:o,content:null,bytes:new Uint8Array(s)}:{relPath:o,content:s.toString(`utf-8`)})}};return n(e),t.sort((e,t)=>e.relPath.localeCompare(t.relPath))}function KE(e){let t=L(e,`SKILL.md`);return B(t)?WE(V(t,`utf-8`),Pl(e)):null}function qE(e){let t=0,n=0,r=null,i=(e,t)=>(r=`Skill bundle could not be read (${e}): ${t instanceof Error?t.message:String(t)}`,null);try{n=B(L(e,`SKILL.md`))?ou(L(e,`SKILL.md`)).size:0}catch(e){return i(`stat SKILL.md`,e)??r}if(n>16777216)return`SKILL.md is ${n} bytes; the import per-file cap is ${qt}.`;if(n>67108864)return`Skill exceeds ${dn} bytes; that is the import bundle cap.`;let a=o=>{if(r!==null)return;let s;try{s=tu(o,{withFileTypes:!0})}catch(e){i(`read directory`,e);return}for(let c of s){if(r!==null)return;let s=L(o,c.name);if(c.isDirectory()){GE.has(c.name)||a(s);continue}if(!c.isFile())continue;let l=R(e,s).split(`\\`).join(`/`);if(l===`SKILL.md`)continue;if(t+=1,t>512){r=`Skill has more than 512 dependent files; that is the import cap.`;return}let u;try{u=ou(s).size}catch(e){i(`stat ${l}`,e);return}if(u>16777216){r=`${l} is ${u} bytes; the import per-file cap is ${qt}.`;return}if(n+=u,n>67108864){r=`Skill exceeds ${dn} bytes; that is the import bundle cap.`;return}}};try{a(e)}catch(e){return`Skill bundle could not be measured: ${e instanceof Error?e.message:String(e)}`}return r}function JE(e){let t=L(e,`SKILL.md`);if(!B(t))return null;let n=V(t,`utf-8`),{name:r,description:i}=WE(n,Pl(e)),a=fle(e),o=Cu(`sha256`);o.update(`SKILL.md\n${n}\n`);for(let e of a)o.update(`${e.relPath}\n`),o.update(e.bytes??e.content??``),o.update(`
30
30
  `);return{name:r,description:i,skillMd:n,files:a,contentHash:o.digest(`hex`)}}function YE(e){if(B(L(e,`SKILL.md`)))return[{name:Pl(e),dir:e}];let t=[],n=0,r=(e,i)=>{if(i>8||++n>5e3)return;if(B(L(e,`SKILL.md`))){t.push({name:Pl(e),dir:e});return}let a;try{a=tu(e,{withFileTypes:!0})}catch{return}for(let t of a)t.isDirectory()&&!dle.has(t.name)&&r(L(e,t.name),i+1)};return r(e,0),t.sort((e,t)=>e.name.localeCompare(t.name))}function XE(e){let t=e?.skills;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.source==`string`&&t.source?t.source:void 0,i=typeof t.id==`string`&&t.id?t.id:r;if(!i||!r)continue;let a=typeof t.name==`string`&&t.name?t.name:bt(i);za(a,r)||n.push({id:i,name:a,source:r,description:typeof t.description==`string`?t.description:``,installs:Number.isInteger(t.installs)&&t.installs>=0?t.installs:null,publisher:at(r)})}return n}const ple={"&amp;":`&`,"&lt;":`<`,"&gt;":`>`,"&quot;":`"`,"&#39;":`'`,"&#x27;":`'`,"&apos;":`'`};function mle(e){return e.replace(/&(?:amp|lt|gt|quot|apos|#39|#x27);/g,e=>ple[e]??e)}function hle(e){let t={},n=e.match(/<meta\b[^>]*>/gi)??[];for(let e of n){let n=e.match(/\bproperty\s*=\s*["'](og:[^"']+)["']/i)?.[1]?.toLowerCase();if(!n)continue;let r=e.match(/\bcontent\s*=\s*["']([^"']*)["']/i)?.[1];if(r==null)continue;let i=mle(r);n===`og:title`&&t.title==null?t.title=i:n===`og:description`&&t.description==null?t.description=i:n===`og:image`&&t.image==null&&(t.image=i)}return t}function gle(e){let t=e?.items;if(!Array.isArray(t))return[];let n=[];for(let e of t){if(typeof e!=`object`||!e)continue;let t=e,r=typeof t.full_name==`string`&&t.full_name?t.full_name:void 0;r&&n.push({id:r,name:typeof t.name==`string`&&t.name?t.name:bt(r),source:r,description:typeof t.description==`string`?t.description:``,installs:null,publisher:at(r)})}return n}function ZE(e){return e.trim().toLowerCase()}function _le(e){return e.split(`/`).filter(Boolean).pop()??e}function QE(e){let t=po(e.trim());if(t?.kind===`site`)return{hostname:t.hostname};let n=LE(e);if(!n)return null;let r=po(n.owner);return r?.kind===`site`?{hostname:r.hostname,skill:n.skill}:null}async function $E(e,t,n={}){let r=QE(e);if(r){let e=t??r.skill;if(!e)throw new OE(`Website skill sources require a skill name.`);return{source:r.hostname,skill:e,publisher:r.hostname,spec:{kind:`well-known`,origin:`https://${r.hostname}`,skill:e}}}let i=LE(e);if(!i)return null;let a=n.fetchImpl??globalThis.fetch;if(!a)throw new OE(`No fetch implementation available.`);let o=t??i.skill,s=ZE(o),c=ZE(i.owner),l;try{let e=await a(`https://skills.sh/api/search?q=${encodeURIComponent(o)}&limit=30`,{signal:AbortSignal.timeout(n.timeoutMs??8e3)});if(!e.ok)throw new OE(`skills.sh lookup failed with HTTP ${e.status}`);l=await e.json()}catch(e){throw e instanceof OE?e:new OE(`skills.sh lookup failed: ${e instanceof Error?e.message:String(e)}`)}let u=XE(l).find(e=>{if((e.publisher?ZE(e.publisher):``)!==c)return!1;let t=ZE(e.name),n=ZE(_le(e.id));return t===s||n===s});if(!u)throw new OE(`No skills.sh result matched ${i.owner}/${i.skill}`);let d=po(u.source),f=d?.kind===`site`?{kind:`well-known`,origin:`https://${d.hostname}`,skill:t??u.name}:IE(u.source);if(!f||f.kind===`local`)throw new OE(`skills.sh returned an unsafe source for ${i.owner}/${i.skill}: ${u.source}`);return{source:u.source,skill:t??u.name,...u.publisher?{publisher:u.publisher}:{},spec:f}}const eD=[`agents`,`claude`,`cursor`,`codex`,`opencode`,`pi`,`copilot`];function tD(e){let t=eD.indexOf(e);return t===-1?eD.length:t}function nD(e){let t=new Map,n=new Map;for(let r of e){let e=`${r.scope}|${r.name}`,i=`${e}|${r.contentHash}`,a=t.get(i);a||(a=[],t.set(i,a)),a.push(r);let o=n.get(e);o||(o=new Set,n.set(e,o)),o.add(r.contentHash)}let r=[];for(let e of t.values()){let t=[...e].sort((e,t)=>{let n=Number(e.viaLink===!0)-Number(t.viaLink===!0);if(n!==0)return n;let r=Number(t.preferredSource===!0)-Number(e.preferredSource===!0);if(r!==0)return r;let i=tD(e.editor)-tD(t.editor);return i===0?e.editor.localeCompare(t.editor):i}),i=t[0];i&&r.push({name:i.name,scope:i.scope,contentHash:i.contentHash,canonical:i,copies:t.slice(1),isFork:(n.get(`${i.scope}|${i.name}`)?.size??1)>1})}return r.sort((e,t)=>e.scope.localeCompare(t.scope)||e.name.localeCompare(t.name)||e.contentHash.localeCompare(t.contentHash))}function rD(e){if(!B(e))return[];try{return tu(e,{recursive:!0,withFileTypes:!0}).filter(e=>e.isFile()).map(e=>L(e.parentPath,e.name)).sort()}catch{return[]}}function iD(e,t,n,r){let i=L(e,`SKILL.md`);if(!B(i))return null;let a=Pl(e),o=a,s=``;try{({name:o,description:s}=WE(V(i,`utf-8`),a))}catch{}return{name:o,description:s,home:e,harness:t,skillMd:i,scripts:rD(L(e,`scripts`)),references:rD(L(e,`references`)),provenance:n,inert:r}}function aD(e){if(!B(e))return[];try{return tu(e,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name).sort()}catch{return[]}}function vle(e){let t=e=>{try{return ou(e).isDirectory()}catch{return!1}};return{commands:t(L(e,`commands`)),hooks:t(L(e,`hooks`)),mcp:B(L(e,`.mcp.json`))}}const yle={commands:!1,hooks:!1,mcp:!1};function oD(e,t){let n=[];for(let r of aD(e)){let i=iD(L(e,r),t,{},yle);i&&n.push({packName:i.name,packVersion:`0.0.0`,harness:t,skills:[i]})}return n}function sD(e){try{return tu(e).length>0}catch{return!1}}function ble(e){let t=new Set,n=(e,r)=>{if(r>4)return;let i;try{i=tu(e,{withFileTypes:!0})}catch{return}if(B(L(e,`SKILL.md`))||B(L(e,`SKILL.mdx`))){t.add(e.split(`/`).pop()??e);return}for(let t of i)t.isDirectory()&&n(L(e,t.name),r+1)};return n(L(e,`skills`),0),[...t].sort()}function xle(e){return{commands:sD(L(e,`commands`)),hooks:sD(L(e,`hooks`))||B(L(e,`hooks.json`)),mcp:B(L(e,`.mcp.json`)),agents:sD(L(e,`agents`))}}function Sle(e){let t=e.lastIndexOf(`@`);return t<=0?{plugin:e}:{plugin:e.slice(0,t),marketplace:e.slice(t+1)}}function Cle(e){let t=new Map;for(let n of e){if(n.orphaned_at||!n.installPath||!B(n.installPath))continue;let e=`${n.scope??``} ${n.projectPath??``}`,r=t.get(e);(!r||(n.lastUpdated??``)>(r.lastUpdated??``))&&t.set(e,n)}return[...t.values()]}function wle(e){let t=L(e,`.claude-plugin`,`plugin.json`);try{let e=JSON.parse(V(t,`utf-8`));return e&&typeof e==`object`?e:{}}catch{return{}}}function Tle(e,t){let n=L(e,`installed_plugins.json`);if(!B(n))return[];let r;try{r=JSON.parse(V(n,`utf-8`))}catch(e){return console.warn(`[skills-catalog] failed to parse installed_plugins.json, skipping Claude plugins`,{manifestPath:n,err:e}),[]}let i=r?.plugins;if(!i||typeof i!=`object`)return[];let a=[];for(let[e,n]of Object.entries(i)){if(!Array.isArray(n))continue;let{plugin:r,marketplace:i}=Sle(e);for(let e of Cle(n)){let n=e.installPath,o=vle(n),s=wle(n),c=L(n,`skills`),l=[];for(let n of aD(c)){let a={plugin:r,...i?{marketplace:i}:{},...e.version?{version:e.version}:{},...e.gitCommitSha?{gitCommitSha:e.gitCommitSha}:{},...e.scope?{scope:e.scope}:{},...e.projectPath?{projectPath:e.projectPath}:{}},s=iD(L(c,n),t,a,o);s&&l.push(s)}l.length!==0&&a.push({packName:r,packVersion:e.version??s.version??`0.0.0`,...typeof s.description==`string`?{packDescription:s.description}:{},...typeof s.author?.name==`string`?{packAuthor:s.author.name}:{},harness:t,skills:l})}}return a}const cD=/^(.*\/plugins\/cache\/([^/]+)\/([^/]+))\/([^/]+)(?:\/.*)?$/,Ele=/^(.*\/plugins)\/(?:cache|marketplaces)\/([^/]+)\//,Dle=/^(.*\/plugins\/marketplaces\/([^/]+))(?:\/.*)?$/;function lD(e){return e.replaceAll(`\\`,`/`).replace(/\/+$/,``)}function Ole(e){let t=Ele.exec(lD(e));if(!t)return null;try{let e=V(`${t[1]}/known_marketplaces.json`,`utf-8`),n=JSON.parse(e)[t[2]];return n?.source?.source===`github`&&n.source.repo?`https://github.com/${n.source.repo}`:null}catch{return null}}function uD(e,t){let n=z(e);try{ou(n).isDirectory()||(n=I(n))}catch{return null}let r=z(t);for(;n===r||n.startsWith(`${r}/`);){try{let e=JSON.parse(V(L(n,`.claude-plugin`,`plugin.json`),`utf-8`));if(typeof e.name==`string`&&e.name.length>0)return{name:e.name,...typeof e.version==`string`?{version:e.version}:{}}}catch{}if(n===r)break;n=I(n)}return null}function kle(e){let t=lD(e),n=cD.exec(t);if(n){let t=uD(e,`${n[1]}/${n[4]}`);return!t||t.name!==n[3]?null:{plugin:n[3],marketplace:n[2],version:t.version??n[4]}}let r=Dle.exec(t);if(!r)return null;let i=uD(e,r[1]);return i?{plugin:i.name,marketplace:r[2],...i.version?{version:i.version}:{}}:null}function Ale(e){return[...e].sort((e,t)=>e.localeCompare(t,void 0,{numeric:!0})).pop()}function jle(e){let t=lD(e),n=cD.exec(t);if(!n)return e;let[r,i]=[n[1],n[4]],a=t.slice(n[0].indexOf(`/${i}`)+i.length+1),o;try{o=tu(r,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return e}let s=Ale(o);if(s===void 0||s===i)return e;let c=`${r}/${s}${a}`;return B(c)?c:e}function dD(e,t){for(let n of t)try{let t=JSON.parse(V(L(e,n),`utf-8`));if(typeof t.name==`string`&&t.name.length>0)return{plugin:t.name,...typeof t.version==`string`?{version:t.version}:{},...typeof t.description==`string`?{description:t.description}:{}}}catch{}return null}function Mle(e){let t=dD(e,[`.claude-plugin/plugin.json`]);if(t)return{...t,setupSupported:!0};try{let t=JSON.parse(V(L(e,`.claude-plugin`,`marketplace.json`),`utf-8`)),n=t.plugins?.find(e=>e.source===`./`)??t.plugins?.[0],r=typeof n?.name==`string`?n.name:t.name;if(typeof r==`string`&&r.length>0)return{plugin:r,...typeof n?.description==`string`?{description:n.description}:{},setupSupported:!0}}catch{}return null}const Nle={id:`claude`,homes:e=>[{harness:`claude`,dir:L(e,`.claude`,`plugins`)}],enumerate:Tle,inspectSource:kle,repositoryUrl:Ole,resolveUpdateSource:jle,detectDir:Mle};function fD(e,t){return{id:e,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let n=dD(e,t);return n?{...n,setupSupported:!1}:null}}}function Ple(e,t){try{return JSON.parse(V(L(e,t),`utf-8`)).skills!==void 0}catch{return!1}}const pD=[Nle,fD(`codex`,[`.codex-plugin/plugin.json`]),fD(`gemini`,[`gemini-extension.json`]),{id:`copilot`,homes:()=>[],enumerate:()=>[],inspectSource:()=>null,repositoryUrl:()=>null,resolveUpdateSource:e=>e,detectDir:e=>{let t=dD(e,[`.plugin/plugin.json`,`.github/plugin/plugin.json`]);if(t)return{...t,setupSupported:!1};if(!Ple(e,`plugin.json`))return null;let n=dD(e,[`plugin.json`]);return n?{...n,setupSupported:!1}:null}}];function mD(e){return pD.find(t=>t.id===e)}function hD(e){if(e===void 0)return pD;let t=mD(e);return t?[t]:[]}function Fle(e){return pD.flatMap(t=>t.homes(e).map(e=>({provider:t.id,...e})))}function Ile(e,t,n=e){let r=mD(e);if(!r)throw Error(`unknown plugin provider: ${e}`);return r.enumerate(t,n).map(t=>({...t,skills:t.skills.map(t=>({...t,provenance:{...t.provenance,pluginProvider:e}}))}))}function gD(e,t){for(let n of hD(t)){let t=n.inspectSource(e);if(!t)continue;let r=n.repositoryUrl(e);return{provider:n.id,...t,...r?{repositoryUrl:r}:{}}}return null}function Lle(e){for(let t of pD){let n=t.detectDir(e);if(!n)continue;let r=ble(e);return r.length===0?null:{provider:t.id,plugin:n.plugin,...n.version?{version:n.version}:{},...n.description?{description:n.description}:{},bundledSkills:r,capabilities:xle(e),setupSupported:n.setupSupported}}return null}function Rle(e,t){for(let n of hD(t)){if(!n.inspectSource(e))continue;let t=n.repositoryUrl(e);if(t)return t}return null}function zle(e,t){for(let n of hD(t))if(n.inspectSource(e))return n.resolveUpdateSource(e);return e}function Ble(e=uu()){let t=Za.flatMap(t=>{let n=_i[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:L(e,...n.split(`/`))}]});return[...Fle(e).map(e=>({kind:`plugin-provider`,...e})),...t,{harness:`agents`,kind:`skill-dir`,dir:L(e,`.agents`,`skills`)}]}function Vle(e){return Za.flatMap(t=>{let n=io[t];return n===null?[]:[{harness:t,kind:`skill-dir`,dir:L(e,...n.split(`/`))}]})}function _D(e){return Object.keys(e.provenance).length>0}function vD(e){return e.provenance.plugin!==void 0}function Hle(e,t){if(vD(e)!==vD(t))return vD(e)?e:t;if(_D(e)!==_D(t))return _D(e)?e:t;let n=e.scripts.length+e.references.length;return t.scripts.length+t.references.length>n?t:e}function Ule(e,t){return{name:e.name,description:e.description,files:{skillMd:e.skillMd,scripts:e.scripts,references:e.references},sourceHarness:e.harness,sourceHarnesses:t,home:e.home,provenance:e.provenance,inert:e.inert}}function Wle(e){try{return JE(e.home)?.contentHash??`unreadable:${e.home}`}catch{return`unreadable:${e.home}`}}function Gle(e){let t=new Map;for(let n of e){let e=pt(n.provenance.scope),r=`${e}\0${e===`project`?n.provenance.projectPath??``:``}\0${n.name}\0${Wle(n)}`,i=t.get(r);i?(i.winner=Hle(i.winner,n),i.harnesses.add(n.harness)):t.set(r,{winner:n,harnesses:new Set([n.harness])})}return[...t.values()].map(({winner:e,harnesses:t})=>Ule(e,[...t].sort())).sort((e,t)=>e.name.localeCompare(t.name)||pt(e.provenance.scope).localeCompare(pt(t.provenance.scope))||e.home.localeCompare(t.home))}function Kle(e){let t=new Map;for(let n of e){let e=t.get(n.packName),r=e??{version:`0.0.0`,skills:new Set,hosts:new Set};r.version===`0.0.0`&&n.packVersion!==`0.0.0`&&(r.version=n.packVersion),!r.description&&n.packDescription&&(r.description=n.packDescription),!r.author&&n.packAuthor&&(r.author=n.packAuthor);for(let e of n.skills)r.skills.add(e.name);r.hosts.add(n.harness),e||t.set(n.packName,r)}return[...t.entries()].map(([e,t])=>({schema:1,name:e,version:t.version,...t.description?{description:t.description}:{},...t.author?{author:{name:t.author}}:{},skills:[...t.skills].sort(),hostCompatibility:[...t.hosts].sort()})).sort((e,t)=>e.name.localeCompare(t.name))}function yD(e={}){let t=[];for(let n of Ble(e.home))try{switch(n.kind){case`plugin-provider`:t.push(...Ile(n.provider,n.dir,n.harness));break;case`skill-dir`:t.push(...oD(n.dir,n.harness));break;default:throw Error(`unhandled harness home kind: ${String(n)}`)}}catch(e){console.warn(`[skills-catalog] failed to enumerate harness home, skipping`,{harness:n.harness,dir:n.dir,err:e})}e.projectDir!==void 0&&t.push(...qle(e.projectDir));let n=e.projectDir===void 0?t:t.map(t=>({...t,skills:t.skills.filter(t=>Dn(t.provenance,e.projectDir))})).filter(e=>e.skills.length>0);return{skills:Gle(n.flatMap(e=>e.skills)),packs:Kle(n)}}function qle(e){let t=bD(z(e,`.ok`,`skills`)),n=[];for(let r of Vle(e))try{for(let i of oD(r.dir,r.harness)){let r=i.skills.filter(e=>!Yle(e,t));r.length!==0&&n.push({...i,skills:r.map(t=>Jle(t,e))})}}catch(e){console.warn(`[skills-catalog] failed to enumerate project harness skills, skipping`,{harness:r.harness,dir:r.dir,err:e})}return n}function Jle(e,t){return{...e,provenance:{...e.provenance,scope:`project`,projectPath:t}}}function Yle(e,t){if(e.name.startsWith(`open-knowledge`))return!0;let n=bD(e.home);return n===t||n.startsWith(t+Vl)}function bD(e){try{return H(e)}catch{return z(e)}}function Xle(e){if(!e.includes(`self.__next_f`))return e;let t=/self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g,n=``;for(let r of e.matchAll(t))n+=JSON.parse(r[1]);return n}const Zle=[`skillId`,`source`,`installs`];function Qle(e){let t={};if(e.length>8192)return t;let n=new Uint8Array(e.length),r=0,i=!1,a=!1;for(let t=0;t<e.length;t++){n[t]=Math.min(r,255);let o=e[t];if(a){a=!1;continue}if(o===`\\`){a=i;continue}if(o===`"`){i=!i;continue}i||(o===`{`||o===`[`?r++:(o===`}`||o===`]`)&&r--)}for(let r of e.matchAll(/"(skillId|source|installs)"\s*:\s*("(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?)/g)){let e=r[1];if(r.index===void 0||n[r.index]!==1||e in t)continue;let i=r[2];t[e]=i.startsWith(`"`)?JSON.parse(i):Number(i)}return t}function*$le(e){let t=[],n=!1,r=!1;for(let i=0;i<e.length;i++){let a=e[i];if(r){r=!1;continue}if(a===`\\`){r=n;continue}if(a===`"`){n=!n;continue}if(!n){if(a===`{`)t.push(i);else if(a===`}`){let n=t.pop();if(n===void 0)continue;let r=e.slice(n,i+1);if(!Zle.every(e=>r.includes(`"${e}"`)))continue;try{let e=JSON.parse(r);if(typeof e==`object`&&e&&!Array.isArray(e)){yield e;continue}}catch{}yield Qle(r)}}}}function eue(e){let t=Xle(e),n=[];for(let e of $le(t)){let{skillId:t,source:r,installs:i}=e;typeof t!=`string`||t===``||typeof r!=`string`||r===``||typeof i!=`number`||!Number.isFinite(i)||n.push({skillId:t,source:r,installs:i})}return n}function tue(e){let t=new Map;for(let n of eue(e)){let e=`${n.source}/${n.skillId}`;t.has(e)||za(n.skillId,n.source)||t.set(e,{id:e,name:n.skillId,source:n.source,description:``,installs:n.installs,publisher:at(n.source)})}return[...t.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}const xD=/href="\/([^"/]+)\/([^"/]+)\/([^"/?#]+)"([\s\S]*?)<\/a>/g,nue=/<span[^>]*font-mono[^>]*>\s*([\d,]+)\s*<\/span>/;function rue(e,t){let n=new Map;xD.lastIndex=0;for(let r=xD.exec(e);r!==null;r=xD.exec(e)){let[,e,i,a,o]=r;if(!e||!i||!a||!o||`${e}/${i}`!==t||za(a,t))continue;let s=Number.parseInt(nue.exec(o)?.[1]?.replaceAll(`,`,``)??``,10);if(!Number.isInteger(s)||s<0)continue;let c=`${t}/${a}`;n.has(c)||n.set(c,{id:c,name:a,source:t,description:``,installs:s,publisher:at(t)})}return[...n.values()].sort((e,t)=>(t.installs??-1)-(e.installs??-1))}function iue(e,t){return`${e}/${t}`}function aue(e){if(e.preferredSource===!0)return-1;let t=eD.indexOf(e.editor);return t===-1?eD.length:t}function oue(e){let t=nD(e),n=new Set,r=new Map,i=new Set,a=new Map;for(let e of t){n.add(e.canonical.dir);for(let t of e.copies)i.add(t.dir);let t=iue(e.scope,e.name),o=aue(e.canonical),s=a.get(t);(s===void 0||o<s)&&(a.set(t,o),r.set(t,e.canonical.dir))}return{admittedDirs:n,canonicalDir:r,excludedCopyDirs:i}}var SD=n(((e,t)=>{function n(e){if(e.length===0)return;let t=Object.create(null),n=0;for(;n<e.length;++n){let t=e.charCodeAt(n);if(u[t]!==1){if(t!==47||n===0)return;break}}if(n===e.length)return;let i=e.slice(0,n).toLowerCase(),a=++n;for(;n<e.length;++n)if(u[e.charCodeAt(n)]!==1){if(n===a||r(e,n,t)===void 0)return;break}if(n!==a)return{type:i,subtype:e.slice(a,n).toLowerCase(),params:t}}function r(e,t,n){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let r,i=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n!==61)return;break}}if(t===e.length||(r=e.slice(i,t),++t,t===e.length))return;let a=``,o;if(e.charCodeAt(t)===34){o=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(o=t,n=!1):(a+=e.slice(o,t),n=!0);continue}if(r===34){if(n){o=t,n=!1;continue}a+=e.slice(o,t);break}if(n&&=(o=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(o=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===o)return;break}a=e.slice(o,t)}r=r.toLowerCase(),n[r]===void 0&&(n[r]=a)}return n}function i(e,t){if(e.length===0)return;let n=Object.create(null),r=0;for(;r<e.length;++r)if(u[e.charCodeAt(r)]!==1){if(a(e,r,n,t)===void 0)return;break}return{type:e.slice(0,r).toLowerCase(),params:n}}function a(e,t,n,r){for(;t<e.length;){for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)break;if(e.charCodeAt(t++)!==59)return;for(;t<e.length;++t){let n=e.charCodeAt(t);if(n!==32&&n!==9)break}if(t===e.length)return;let i,a=t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(u[n]!==1){if(n===61)break;return}}if(t===e.length)return;let o=``,s,l;if(i=e.slice(a,t),i.charCodeAt(i.length-1)===42){let n=++t;for(;t<e.length;++t){let n=e.charCodeAt(t);if(f[n]!==1){if(n!==39)return;break}}if(t===e.length)return;for(l=e.slice(n,t),++t;t<e.length&&e.charCodeAt(t)!==39;++t);if(t===e.length||(++t,t===e.length))return;s=t;let r=0;for(;t<e.length;++t){let n=e.charCodeAt(t);if(p[n]!==1){if(n===37){let n,i;if(t+2<e.length&&(n=m[e.charCodeAt(t+1)])!==-1&&(i=m[e.charCodeAt(t+2)])!==-1){let a=(n<<4)+i;o+=e.slice(s,t),o+=String.fromCharCode(a),t+=2,s=t+1,a>=128?r=2:r===0&&(r=1);continue}return}break}}if(o+=e.slice(s,t),o=c(o,l,r),o===void 0)return}else{if(++t,t===e.length)return;if(e.charCodeAt(t)===34){s=++t;let n=!1;for(;t<e.length;++t){let r=e.charCodeAt(t);if(r===92){n?(s=t,n=!1):(o+=e.slice(s,t),n=!0);continue}if(r===34){if(n){s=t,n=!1;continue}o+=e.slice(s,t);break}if(n&&=(s=t-1,!1),d[r]!==1)return}if(t===e.length)return;++t}else{for(s=t;t<e.length;++t)if(u[e.charCodeAt(t)]!==1){if(t===s)return;break}o=e.slice(s,t)}if(o=r(o,2),o===void 0)return}i=i.toLowerCase(),n[i]===void 0&&(n[i]=o)}return n}function o(e){let t;for(;;)switch(e){case`utf-8`:case`utf8`:return s.utf8;case`latin1`:case`ascii`:case`us-ascii`:case`iso-8859-1`:case`iso8859-1`:case`iso88591`:case`iso_8859-1`:case`windows-1252`:case`iso_8859-1:1987`:case`cp1252`:case`x-cp1252`:return s.latin1;case`utf16le`:case`utf-16le`:case`ucs2`:case`ucs-2`:return s.utf16le;case`base64`:return s.base64;default:if(t===void 0){t=!0,e=e.toLowerCase();continue}return s.other.bind(e)}}let s={utf8:(e,t)=>{if(e.length===0)return``;if(typeof e==`string`){if(t<2)return e;e=Buffer.from(e,`latin1`)}return e.utf8Slice(0,e.length)},latin1:(e,t)=>e.length===0?``:typeof e==`string`?e:e.latin1Slice(0,e.length),utf16le:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.ucs2Slice(0,e.length)),base64:(e,t)=>e.length===0?``:(typeof e==`string`&&(e=Buffer.from(e,`latin1`)),e.base64Slice(0,e.length)),other:(t,n)=>{if(t.length===0)return``;typeof t==`string`&&(t=Buffer.from(t,`latin1`));try{return new TextDecoder(e).decode(t)}catch{}}};function c(e,t,n){let r=o(t);if(r)return r(e,n)}function l(e){if(typeof e!=`string`)return``;for(let t=e.length-1;t>=0;--t)switch(e.charCodeAt(t)){case 47:case 92:return e=e.slice(t+1),e===`..`||e===`.`?``:e}return e===`..`||e===`.`?``:e}let u=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],d=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],f=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],p=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,0,0,0,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],m=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1];t.exports={basename:l,convertToUTF8:c,getDecoder:o,parseContentType:n,parseDisposition:i}})),sue=n(((e,t)=>{function n(e,t,n,r,i){for(let a=0;a<i;++a)if(e[t+a]!==n[r+a])return!1;return!0}var r=class{constructor(e,t){if(typeof t!=`function`)throw Error(`Missing match callback`);if(typeof e==`string`)e=Buffer.from(e);else if(!Buffer.isBuffer(e))throw Error(`Expected Buffer for needle, got ${typeof e}`);let n=e.length;if(this.maxMatches=1/0,this.matches=0,this._cb=t,this._lookbehindSize=0,this._needle=e,this._bufPos=0,this._lookbehind=Buffer.allocUnsafe(n),this._occ=[n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n,n],n>1)for(let t=0;t<n-1;++t)this._occ[e[t]]=n-1-t}reset(){this.matches=0,this._lookbehindSize=0,this._bufPos=0}push(e,t){let n;Buffer.isBuffer(e)||(e=Buffer.from(e,`latin1`));let r=e.length;for(this._bufPos=t||0;n!==r&&this.matches<this.maxMatches;)n=i(this,e);return n}destroy(){let e=this._lookbehindSize;e&&this._cb(!1,this._lookbehind,0,e,!1),this.reset()}};function i(e,t){let r=t.length,i=e._needle,o=i.length,s=-e._lookbehindSize,c=o-1,l=i[c],u=r-o,d=e._occ,f=e._lookbehind;if(s<0){for(;s<0&&s<=u;){let n=s+c,r=n<0?f[e._lookbehindSize+n]:t[n];if(r===l&&a(e,t,s,c))return e._lookbehindSize=0,++e.matches,s>-e._lookbehindSize?e._cb(!0,f,0,e._lookbehindSize+s,!1):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<0&&!a(e,t,s,r-s);)++s;if(s<0){let n=e._lookbehindSize+s;return n>0&&e._cb(!1,f,0,n,!1),e._lookbehindSize-=n,f.copy(f,0,n,e._lookbehindSize),f.set(t,e._lookbehindSize),e._lookbehindSize+=r,e._bufPos=r,r}e._cb(!1,f,0,e._lookbehindSize,!1),e._lookbehindSize=0}s+=e._bufPos;let p=i[0];for(;s<=u;){let r=t[s+c];if(r===l&&t[s]===p&&n(i,0,t,s,c))return++e.matches,s>0?e._cb(!0,t,e._bufPos,s,!0):e._cb(!0,void 0,0,0,!0),e._bufPos=s+o;s+=d[r]}for(;s<r;){if(t[s]!==p||!n(t,s,i,0,r-s)){++s;continue}t.copy(f,0,s,r),e._lookbehindSize=r-s;break}return s>0&&e._cb(!1,t,e._bufPos,s<r?s:r,!0),e._bufPos=r,r}function a(e,t,n,r){let i=e._lookbehind,a=e._lookbehindSize,o=e._needle;for(let e=0;e<r;++e,++n)if((n<0?i[a+n]:t[n])!==o[e])return!1;return!0}t.exports=r})),cue=n(((t,n)=>{let{Readable:r,Writable:i}=e(`stream`),a=sue(),{basename:o,convertToUTF8:s,getDecoder:c,parseContentType:l,parseDisposition:u}=SD(),d=Buffer.from(`\r
@@ -94,12 +94,12 @@ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$t as r,At as i,Bt
94
94
  `).trim()),i=[]):i.push(e)}if(i.length>0){let e=i.join(`
95
95
  `).trim();e&&r.push(e)}return r}function hz(e){if(Zx(e.docName)||Qx(e.docName)||eS(e.docName)||tS(e.docName))return{kind:`noop`};let{base:t,ours:n,theirs:r}=e;if(pz(r))return{kind:`refused`,reason:`conflict-markers`};if(r===t)return{kind:`noop`};if(n===t)return{kind:`clean`,newContent:r};let i=mz(t),a=mz(n),o=mz(r);return(i.length+1)*(a.length+1)>4e6||(i.length+1)*(o.length+1)>4e6?{kind:`refused`,reason:`too-large`}:gz(i,a,o)}function gz(e,t,n){let r=_z(e,t),i=_z(e,n),a=[],o=[];for(let t=0;t<e.length;t++){let n=e[t],s=r.get(t),c=i.get(t),l=s?.insertsBefore??[],u=c?.insertsBefore??[];a.push(...l,...u);let d=s?.action??`keep`,f=c?.action??`keep`;if(d===`keep`&&f===`keep`)a.push(n);else if(d===`keep`&&f!==`keep`)f===`modify`&&c?.newContent!==void 0&&a.push(c.newContent);else if(d!==`keep`&&f===`keep`)d===`modify`&&s?.newContent!==void 0&&a.push(s.newContent);else{let e=d===`modify`?s?.newContent:null,r=f===`modify`?c?.newContent:null;e===r||o.push({blockIndex:t,base:n,ours:e??``,theirs:r??``}),e!=null&&a.push(e)}}let s=r.get(e.length),c=i.get(e.length);s?.insertsBefore&&a.push(...s.insertsBefore),c?.insertsBefore&&a.push(...c.insertsBefore);let l=a.length>0?`${a.join(`
96
96
 
97
- `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function _z(e,t){let n=new Map,r=vz(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function vz(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint32Array((n+1)*i);for(let o=1;o<=n;o++){let n=o*i,s=(o-1)*i;for(let i=1;i<=r;i++)if(e[o-1]===t[i-1])a[n+i]=a[s+(i-1)]+1;else{let e=a[s+i],t=a[n+(i-1)];a[n+i]=e>t?e:t}}let o=[],s=n,c=r;for(;s>0&&c>0;)e[s-1]===t[c-1]?(o.push([s-1,c-1]),s--,c--):a[(s-1)*i+c]>=a[s*i+(c-1)]?s--:c--;return o.reverse()}function yz(e,t,n,r,i,a,o){if(Zx(n)||Qx(n)||eS(n)||tS(n))return;let s=t.documents.get(n);if(!s)return;let c=s.getText(`source`).toString(),l=c===r,u=jt(c).frontmatter,{frontmatter:d}=jt(r),f=o&&Rx(uz.context.origin)?{report:e=>o(n,e,Tx.id,`file-watcher-intake`),baselineFullMd:c}:void 0;try{s.transact(()=>{dz(s,r,i,n,a,f)},uz)}catch(t){throw e.setReconciledBase(n,s.getText(`source`).toString()),t}u!==d&&ES(`file-watcher`),l||ej(n,Tx.id,Tx.name,Tx.id,sd(n)),e.setReconciledBase(n,r)}function bz(e,t,n,r,i){return async(a,o)=>{try{yz(e,t,a,o,n,r,i),F(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof yt||e instanceof Qr)throw e;nse(),F(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const xz={reconciled:!1,baseBytes:0,diskBytes:0};function Sz(e){let{frontmatter:t,body:n}=jt(e.getText(`source`).toString());return Fn(t,n)}function Cz(e,t,n,r,i,a){if(Zx(n)||Qx(n)||eS(n)||tS(n))return xz;let o=t.documents.get(n);if(o&&mS(o))return xz;let s=e.getReconciledBase(n);if(s===void 0)return xz;let c;try{let e=cN(n,r);if(!B(e))return xz;c=H(e)}catch{return xz}if(!lN(c,r))return F(`reconcile`).warn({docName:n,canonical:c,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),xz;let l;try{l=V(c,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&F(`reconcile`).warn({docName:n,canonical:c,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),xz}if(Hi(l)===Hi(s))return xz;let u=e.peekInFlightFlush(n);if(u!==void 0){if(Hi(l)===u)return rse(),F(`reconcile`).debug({docName:n,diskBytes:l.length},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),xz;ise(),F(`reconcile`).warn({docName:n,diskBytes:l.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${n}; falling through to merge`)}if(!o)return xz;let d=hz({docName:n,base:s,ours:Sz(o),theirs:l});switch(F(`reconcile`).info({docName:n,result:d.kind,baseBytes:s.length,diskBytes:l.length},`[reconcile] before-agent-write ${n} result=${d.kind}`),d.kind){case`noop`:return xz;case`conflicts`:case`refused`:{let e=o.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,d.kind===`refused`?d.reason:`reconcile-conflicts`),xz}case`clean`:case`merged`:return yz(e,t,n,d.kind===`clean`?l:d.newContent,i,void 0,a),d.kind===`merged`&&e.setReconciledBase(n,l),{reconciled:!0,baseBytes:Buffer.byteLength(s,`utf8`),diskBytes:Buffer.byteLength(l,`utf8`),mergeOutcome:d.kind}}}const wz=new Map;function Tz(e,t){wz.set(e,t)}function Ez(e,t){let n=wz.get(e);if(n===void 0)return null;if(!Wa.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=z(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=z(n,...e)}if(!r.startsWith(n+Vl))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}const Dz=F(`file-watcher`);function Oz(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function kz(e,t){return{title:sk(e,t),icon:lk(e)}}function Az(e){let t=new Map;for(let[n,r]of e)r.kind===`markdown`&&t.set(n,r);return t}const jz=new Map,Mz=1e4;function Nz(e,t){let n=jz.get(e)??[];n.push({hash:t,timestamp:Date.now()}),jz.set(e,n)}function Pz(){let e=Date.now();for(let[t,n]of jz){let r=n.filter(t=>e-t.timestamp<=Mz);r.length===0?jz.delete(t):r.length!==n.length&&jz.set(t,r)}}function Fz(e){return Cu(`sha256`).update(e).digest(`hex`)}const Iz=[],Lz=new Map;let Rz=0,zz=0,Bz=0;function Vz(e,t,n){if(Iz.push({ts:Date.now(),decision:e,kind:t,path:ds(n),pathRole:gs(n)}),Iz.length>256&&Iz.shift(),e===`dispatched`){Rz++;return}if(e===`self-write-skip`){zz++;return}let r=e.slice(5);Lz.set(r,(Lz.get(r)??0)+1),Bz++,uB().add(1,{"disk.drop_reason":r})}function Hz(){return Iz.map(e=>({...e}))}function Uz(){if(Bz===0)return;let e=Bz;Bz=0;let t={};for(let[e,n]of Lz)t[e]=n;Dz.info({droppedSinceLastSummary:e,dropTotals:t,dispatched:Rz,selfWriteSkips:zz},`[file-watcher] drop summary: ${e} event(s) dropped since last summary`)}function Wz(){Iz.length=0,Lz.clear(),Rz=0,zz=0,Bz=0}function Gz(e,t){let n;try{n=Yl(e)}catch(t){let n=Us(t);return n===`ENOENT`?!1:(Dz.warn({path:e,code:n},`lstat failed for escape check on ${e} (${n}), dropping event`),!0)}if(!n.isSymbolicLink())return!1;let r;try{r=H(e)}catch(t){let n=Us(t);return n!==`ENOENT`&&n!==`ELOOP`&&Dz.warn({path:e,code:n},`realpath failed for escape check on ${e} (${n}), dropping event`),!0}return!lN(r,t)}function Kz(e,t){return Vx(oN(R(t,e)))}function qz(e,t){let n=R(e,t).replaceAll(`\\`,`/`);return!n||n===`.`||n===`..`||n.startsWith(`../`)?null:n}function Jz(e,t,n,r,i=n){let a=qz(t,n);return a?(e.set(a,{size:0,modified:r.mtime.toISOString(),canonicalPath:i,inode:Number(r.ino)}),a):null}function Yz(e,t){let n=!1;for(let r of e.keys())(r===t||r.startsWith(`${t}/`))&&(e.delete(r),n=!0);return n}function Xz(e){let t=Il(e);if(t===``)return null;let n=t.toLowerCase();return n===`.mdx`||n===`.md`?t:null}const Zz=new Map;function Qz(e,t){Zz.set(e,t)}function $z(e){let t=Zz.get(e);return Zz.delete(e),t}async function eB(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(zx(r.path)){if(n){let e=oN(R(t,r.path));if(n.isExcluded(e)){Vz(`drop-filter-excluded`,r.type,r.path);continue}}switch(r.type){case`delete`:i.push(r);break;case`create`:Zz.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await _u(e.path,`utf-8`))}catch(t){Vz(`drop-read-failed`,e.type,e.path),Us(t)!==`ENOENT`&&Dz.warn({path:e.path,err:t},`Failed to read ${e.path}`)}for(let e of o)try{c.set(e.path,await _u(e.path,`utf-8`))}catch(t){Vz(`drop-read-failed`,e.type,e.path),Us(t)!==`ENOENT`&&Dz.warn({path:e.path,err:t},`Failed to read ${e.path}`)}function l(e){let n=Kz(e,t);if(!r)return n;let i=null;try{i=Yl(e)}catch(t){return Us(t)!==`ENOENT`&&Dz.warn({path:e,err:t},`resolveDocName lstat failed for ${e}`),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=H(e)}catch(t){let i=Us(t);return i!==`ENOENT`&&i!==`ELOOP`&&Dz.warn({path:e,err:t},`resolveDocName realpath failed for ${e}`),r.delete(n),n}if(!lN(a,t))return r.delete(n),n;let o=Kz(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=$z(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=Fz(r);if(i===t){d.add(n.path),f.add(e.path),Qz(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||($z(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=Fz(t);Qz(e.path,n),pz(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=Fz(t);Qz(e.path,n),pz(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function tB(e,t){let n=jz.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&jz.delete(e),!0)}async function nB(e,t,n,r,i,a,o,s){let c=s??new Set;try{let s=await vu(e,{withFileTypes:!0});for(let l of s){let s=L(e,l.name),u;try{u=await gu(s)}catch(e){Us(e)!==`ENOENT`&&Dz.warn({path:s,err:e},`Failed to lstat ${s}, skipping`);continue}if(u.isSymbolicLink()){let e;try{e=await yu(s)}catch(e){let t=Us(e);t===`ENOENT`||t===`ELOOP`?Dz.warn({path:s,code:t},`Broken/cyclic symlink at ${s}, skipping`):Dz.warn({path:s,err:e},`Failed to resolve symlink ${s}`);continue}if(!lN(e,t)){Dz.warn({path:s,canonical:e},`Symlink escape: ${s} → ${e}, skipping`);continue}try{let u=await bu(e);if(c.has(u.ino)){if(u.isFile()&&zx(l.name)){let n=Kz(s,t),i=Kz(e,t);a.set(n,i);let o=r.get(i);o&&!o.aliases.includes(n)&&o.aliases.push(n)}else if(u.isDirectory()){let r=qz(t,s);(!n||r&&!n.isDirExcluded(r))&&o.set(Kz(s,t),Kz(e,t))}continue}if(c.add(u.ino),u.isDirectory()){let l=qz(t,s);if(n&&(!l||n.isDirExcluded(l)))continue;o.set(Kz(s,t),Kz(e,t)),await nB(e,t,n,r,i,a,o,c)}else if(u.isFile()&&zx(l.name)){if(n){let r=oN(R(t,e));if(n.isExcluded(r))continue}let i=Kz(s,t),o=Kz(e,t);a.set(i,o);try{let t=await _u(e,`utf-8`),n=Fz(t);Zz.set(e,n);let a=Xz(e);if(a){let e=Gx(o,a);if(e.shadowed&&(Dz.warn({docName:o,effective:e.effective,shadowed:e.shadowed},`docName "${o}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(o,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[i],kind:`markdown`,...kz(t,o)})}catch(t){Us(t)!==`ENOENT`&&Dz.warn({path:e,err:t},`Failed to seed hash for ${e}`)}}else if(u.isFile()){if(n){let r=oN(R(t,e));if(n.isPathIgnored(r))continue}let i=Kz(s,t);if(Zx(i)||Qx(i))continue;r.set(i,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[],kind:`file`})}}catch(t){Dz.warn({path:e,err:t},`Failed to stat symlink target ${e}`)}}else if(u.isDirectory()){let e=qz(t,s);if(n&&(!e||n.isDirExcluded(e)))continue;Jz(i,t,s,u),await nB(s,t,n,r,i,a,o,c)}else if(u.isFile()&&zx(l.name)){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=oN(R(t,s));if(n.isExcluded(e))continue}try{let e=await _u(s,`utf-8`);Zz.set(s,Fz(e));let n=Kz(s,t),i=Xz(s);if(i){let e=Gx(n,i);if(e.shadowed&&(Dz.warn({docName:n,effective:e.effective,shadowed:e.shadowed},`docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`markdown`,...kz(e,n)})}catch(e){let t=Us(e);t===`EACCES`?Dz.warn({path:s,code:t},`Permission denied reading ${s}, file excluded from index`):t!==`ENOENT`&&Dz.warn({path:s,err:e},`Failed to seed hash for ${s}`)}}else if(u.isFile()){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=oN(R(t,s));if(n.isPathIgnored(e))continue}let e=Kz(s,t);if(Zx(e)||Qx(e))continue;r.set(e,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`file`})}}}catch(t){Us(t)!==`ENOENT`&&Dz.warn({dir:e,err:t},`Failed to read directory ${e}`)}}function rB(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let n=e.relativePath;if(Zx(n)||Qx(n))return;if(e.kind===`file-delete`){let e=t.get(n);e&&e.kind===`file`&&t.delete(n);return}let r=t.get(n);if(r&&r.kind===`markdown`)return;t.set(n,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:e.inode||r?.inode||0,aliases:r?.aliases??[],kind:`file`});return}if(!nS(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=Xz(e.path);i&&Gx(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[],kind:`markdown`,...kz(e.content,n)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),Xx(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),Xx(e.oldDocName);let r=Xz(e.newPath);r&&Gx(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[],kind:`markdown`,...kz(e.content,e.newDocName)});break}default:Oz(e)}}}function iB(e,t,n,r){let i=[],a=[];for(let o of e){let e=qz(t,o.path);if(!e)continue;if(o.type===`delete`){Yz(r,e)&&i.push({kind:`folder-delete`,path:o.path,relativePath:e});continue}let s;try{s=Yl(o.path)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:o.path,code:t},`folder lstat failed for ${o.path} (${t})`);continue}let c=null,l=o.path;if(s.isDirectory())c=s;else if(s.isSymbolicLink())try{if(l=H(o.path),!lN(l,t))continue;let e=ou(l);e.isDirectory()&&(c=e)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:o.path,code:t},`folder symlink resolve failed for ${o.path} (${t})`),c=null}if(!c||n?.isDirExcluded(e))continue;let u=r.has(e);Jz(r,t,o.path,c,l),u||(i.push({kind:`folder-create`,path:o.path,relativePath:e}),aB(l,t,n,r,i,a))}return{events:i,untrackedFiles:a}}function aB(e,t,n,r,i,a){let o=[e];for(;o.length>0;){let e=o.shift();if(e===void 0)continue;let s;try{s=tu(e,{withFileTypes:!0})}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({dir:e,code:n},`folder rescan readdir failed for ${e} (${n})`);continue}for(let c of s){if(c.isFile()){a.push(L(e,c.name));continue}if(!c.isDirectory())continue;let s=L(e,c.name),l=qz(t,s);if(!l||n?.isDirExcluded(l))continue;let u;try{u=Yl(s)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:s,code:t},`folder rescan lstat failed for ${s} (${t})`);continue}u.isDirectory()&&(r.has(l)||(Jz(r,t,s,u),i.push({kind:`folder-create`,path:s,relativePath:l})),o.push(s))}}}async function oB(e,t,n,r,i,a,o){let s=e.filter(e=>Gz(e.path,t)?(Vz(`drop-symlink-escape`,e.type,e.path),Dz.warn({path:e.path,type:e.type},`Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:c,untrackedFiles:l}=iB(s,t,n,i),u=[];if(l.length>0){let e=new Set(s.map(e=>e.path)),n=new Set;for(let e of r.values())n.add(e.canonicalPath);u=l.filter(t=>!e.has(t)&&!Zz.has(t)&&!n.has(t)).filter(e=>Gz(e,t)?(Vz(`drop-symlink-escape`,`create`,e),!1):!0).map(e=>({type:`create`,path:e})),u.length>0&&Dz.debug({count:u.length,paths:u.map(e=>oN(R(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let d=u.length>0?s.concat(u):s,f=d.filter(e=>zx(e.path)),p=d.filter(e=>Bx(e.path,le)),m=d.filter(e=>!zx(e.path));if(f.length===0&&p.length===0&&c.length===0&&m.length===0)return;let h=f.length>0?await eB(f,t,n,o):[];for(let e of h){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=Fz(e.content),r=e.path;try{r=H(e.path)}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({path:e.path,code:n},`realpathSync failed for self-write check on ${e.path} (${n})`)}t=tB(r,n)}else if(e.kind===`rename`){let n=Fz(e.content),r=e.newPath;try{r=H(e.newPath)}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({path:e.newPath,code:n},`realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=tB(r,n)}if(rB(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(I(e.docName));break;case`delete`:n.decrementMdDir(I(e.docName));break;case`rename`:n.decrementMdDir(I(e.oldDocName)),n.incrementMdDir(I(e.newDocName));break;case`update`:case`conflict`:break;default:Oz(e)}if(t){Dz.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!0}),Vz(`self-write-skip`,e.kind,e.kind===`rename`?e.newPath:e.path);continue}Dz.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!1});let i=e.kind===`rename`?e.newPath:e.path;Vz(`dispatched`,e.kind,i),await Zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":ds(i),"disk.path.role":gs(i)}},async()=>a(e))}for(let e of c)Dz.debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!1}),Vz(`dispatched`,e.kind,e.path),await Zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":ds(e.path),"disk.path.role":gs(e.path)}},async()=>a(e));for(let e of p){if(n){let r=oN(R(t,e.path));if(n.isExcluded(r)){Vz(`drop-filter-excluded`,e.type,e.path);continue}}let r=oN(R(t,e.path)),i=e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r};Vz(`dispatched`,i.kind,e.path),await a(i)}for(let e of m){let i=oN(R(t,e.path));if(n?.isPathIgnored(i)){Vz(`drop-filter-excluded`,e.type,e.path);continue}if(Zx(i)||Qx(i)){Vz(`drop-reserved-doc`,e.type,e.path);continue}if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:i};rB(t,r),Vz(`dispatched`,t.kind,e.path),await a(t);continue}let o;try{o=Yl(e.path),o.isSymbolicLink()&&(o=ou(e.path))}catch(t){let n=Us(t);Vz(`drop-stat-failed`,e.type,e.path),n!==`ENOENT`&&Dz.warn({path:e.path,code:n},`file-event lstat failed for ${e.path} (${n})`);continue}if(!o.isFile())continue;let s=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)}:{kind:`file-update`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)};rB(s,r),Vz(`dispatched`,s.kind,e.path),await a(s)}}let sB=null;function cB(){return sB||=xs().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),sB}let lB=null;function uB(){return lB||=xs().createCounter(`ok.file_watcher.drops`,{description:`File-watcher events dropped before dispatch, by bounded reason`}),lB}async function dB(e,t,n,r,i,a,o,s){let c;try{c=await import(`@parcel/watcher`)}catch(e){return Dz.debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let l=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await c.subscribe(e,async(c,l)=>{if(c){Dz.error({err:c},`parcel watcher callback error`);return}try{s?.(l.map(e=>e.path)),await oB(l.map(e=>({type:e.type,path:e.path})),e,t,n,r,i,a),o()}catch(e){Dz.error({err:e},`parcel batch error`)}},l)}catch(e){return Dz.warn({err:e},`@parcel/watcher subscribe failed, falling back to chokidar`),null}}function fB(e,t,n,r){let i=oN(R(e,n));if(i===``||i===`.`)return!1;let a;if(r)a=r.isDirectory();else try{a=Yl(n).isDirectory()}catch{return!1}if(a){let n=/^(\.[A-Za-z0-9_-]+)(\/skills(\/[^/]+)?)?$/.exec(i);return n&&n[1]!==`.ok`&&(n[2]!==void 0||B(L(e,i,`skills`)))?!1:t.isDirExcluded(i)}return t.isExcluded(i)}async function pB(e,t,n,r,i,a,o,s){let{watch:c}=await import(`./chokidar-dh8zokRd.mjs`),l=c(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(n,r)=>fB(e,t,n,r):void 0});l.on(`error`,e=>Dz.error({err:e},`chokidar error`));let u=[],d=null;function f(c,l){u.push({type:c,path:l}),d||=setTimeout(()=>{let c=u;u=[],d=null,s?.(c.map(e=>e.path)),oB(c,e,t,n,r,i,a).then(o).catch(e=>Dz.error({err:e},`chokidar batch error`))},50)}return l.on(`add`,e=>f(`create`,e)),l.on(`change`,e=>f(`update`,e)),l.on(`unlink`,e=>f(`delete`,e)),l.on(`addDir`,e=>f(`create`,e)),l.on(`unlinkDir`,e=>f(`delete`,e)),await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};l.once(`ready`,n),setTimeout(n,1e4).unref()}),{unsubscribe:()=>(d&&(clearTimeout(d),d=null,u=[]),l.close())}}async function mB(e,t,n,r={}){let{onRawBatch:i}=r,a;try{a=H(e)}catch{a=e}let o=new Map,s=new Map,c=new Map,l=new Map,u=0,d=null,f=-1,p=()=>{u++};await nB(a,a,n,o,s,c,l),p();let m=setInterval(Pz,Mz),h=setInterval(Uz,6e4),g,_,v=process.env.OK_FILE_WATCHER_BACKEND===`chokidar`;try{let e=v||r.forceBackend===`chokidar`?null:await dB(a,n,o,s,t,c,p,i);if(e)g=e,_=`parcel`;else{if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable (forced backend)`);g=await pB(a,n,o,s,t,c,p,i),_=`chokidar`}}catch(e){throw clearInterval(m),clearInterval(h),e}let y=g.unsubscribe.bind(g);return Dz.info({contentDir:a,backend:_},`watching for external .md changes`),{async unsubscribe(){return clearInterval(m),clearInterval(h),jz.clear(),Zz.clear(),Wz(),y()},getFileIndex(){return d&&f===u?d:(d=Az(o),f=u,d)},getAllFilesIndex(){return o},getFileIndexGeneration(){return u},getFolderIndex(){return s},getAliasMap(){return c},getFolderAliasIndex(){return l},mutateFileIndex(e){rB(e,o),p()},pruneFileIndexNowExcluded(){if(!n)return 0;let e=0;for(let[t,r]of o){let i=oN(R(a,r.canonicalPath));(r.kind===`file`?n.isPathIgnored(i):n.isExcluded(i))&&(o.delete(t),e++)}return e>0&&p(),e},pruneFolderIndexNowExcluded(){if(!n)return 0;let e=0;for(let t of s.keys())n.isDirExcluded(t)&&(s.delete(t),e++);return e},async rescanFromDisk(){await nB(a,a,n,o,s,c,l),p()}}}async function hB(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),n=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:n}}function gB(e){try{return ou(z(e,ce)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function _B(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=gB(t)}catch{e=!1}if(e)return{rootPath:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}async function vB(e,t){let{git:n}=Is(e),[r,i]=await Promise.allSettled([toe(n),Wb(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function yB(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function bB(e,t,n,r){let{git:i}=Is(e);await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``?!0:i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=vB(e,t).catch(e=>(SB(e)||F(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${VF(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const xB=`git-branch-info`;function SB(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const CB=F(`git-checkout`),wB=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function TB(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(wB);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=H(n)}catch{r=n}return{held:!0,path:r}}const EB=`git-checkout`,DB=ho;async function OB(e,t,n){if(n?.fastForward&&await kB(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r}=Is(e),i=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!i)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:DB(e)?`branch-not-found`:`fetch-failed`}}let a=await vB(e,i?t:`origin/${t}`);if(a.conflicts)return{ok:!1,reason:`dirty-conflict`,files:a.files};try{return await r.raw([`checkout`,t]),{ok:!0}}catch(e){let n=TB(e);return n.held?(CB.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(CB.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${VF(e)}`),{ok:!1,reason:`checkout-failed`})}}async function kB(e,t){let{git:n}=Is(e,{timeoutMs:15e3}),r=e=>n.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await n.raw([`fetch`,`origin`,t])}catch(e){return CB.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${VF(e)}`),`unavailable`}let i=await r(`refs/remotes/origin/${t}`);if(!i)return`unavailable`;let a=await r(`refs/heads/${t}`);if(!a||a===i)return`up-to-date`;let o=await n.raw([`merge-base`,a,i]).then(e=>e.trim()).catch(()=>``);if(o===a){try{await n.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return CB.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${VF(e)}`),`unavailable`}return await r(`refs/heads/${t}`)===i?`advanced`:`unavailable`}return o===i?`up-to-date`:`diverged`}const AB=(e,t)=>{let n=Ml(`git`,[`config`,`--get`,t],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));return n.status!==0||!n.stdout?null:n.stdout.trim()||null};function jB(e){let t=Ml(`git`,[`rev-parse`,`--git-dir`],fN({cwd:e,encoding:`utf-8`,timeout:5e3})),n=Ml(`git`,[`rev-parse`,`--git-common-dir`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||n.status!==0?!1:z(e,t.stdout.trim())!==z(e,n.stdout.trim())}function MB(e){let t=Ml(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let n=Ml(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(n.status!==0){let e=n.stderr?.trim()??``,t=n.error?` [${n.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function NB(e,t,n,r=AB){let i=r(e,`user.name`),a=r(e,`user.email`);if(i&&a)return{name:i,email:a};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function PB(e,t,n){let r=`--local`;jB(e)&&(MB(e),r=`--worktree`);let i=(t,n)=>{let i=Ml(`git`,[`config`,r,t,n],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(i.status!==0){let e=i.stderr?.trim()??``,n=i.error?` [${i.error.message}]`:``;throw Error(`git config ${r} ${t} failed: ${e}${n}`)}};i(`user.name`,t),i(`user.email`,n)}zo(),Ms();function FB(e){if(e===`null`||e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function IB(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function LB(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function RB(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function zB(e,t){return e!==void 0&&RB(e)===t}const BB=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function VB(e){return BB.some(t=>e.headers[t]!==void 0)}const HB=`Add this host to server.bind or set server.publicUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var UB=class extends Error{};const WB=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function GB(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function KB(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(GB).filter(e=>!WB.has(e)&&!e.startsWith(`127.`)),r;if(t?.publicUrlSource===`server`&&t.publicUrl!==void 0){let e=new URL(t.publicUrl);r={host:RB(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,publicOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function qB(e,t){return IB(e)?!0:t.allowExternal&&e!==void 0}function JB(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function YB(e,t){if(LB(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=JB(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.publicOrigin!==void 0&&zB(e,t.publicOrigin.host)}function XB(e,t){if(FB(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.publicOrigin!==void 0&&n.protocol===t.publicOrigin.protocol&&RB(n.host)===t.publicOrigin.host)return!0;if(t.bindLiterals.length>0){let e=GB(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function ZB(e,t){return!t.tolerateForwardedHeaders&&VB(e)}const QB=new WeakMap;function $B(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:IB(n)?`loopback`:`external`,actor:void 0};return QB.set(e,r),r}function eV(e){return QB.get(e)}let tV=null;Xo(()=>{tV=null});function nV(){return tV||=xs().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),tV}function rV(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??KB({}),a=e=>YB(e,i);return async(e,o)=>{let s=e.url?.split(`?`)[0];if(!s)return!1;let c=r.resolve(s);if(!c)return!1;let l=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};dj({ts:Date.now(),url:s,method:e.method??``,ua:l(`user-agent`),origin:l(`origin`),referer:l(`referer`),host:l(`host`),remote:e.socket?.remoteAddress,secChUa:l(`sec-ch-ua`),secChUaMobile:l(`sec-ch-ua-mobile`),secChUaPlatform:l(`sec-ch-ua-platform`),secFetchSite:l(`sec-fetch-site`),secFetchDest:l(`sec-fetch-dest`),secFetchMode:l(`sec-fetch-mode`),secFetchUser:l(`sec-fetch-user`)});let u=e.method??`GET`,d=c.template,f=s.startsWith(`/api/`)?Gse(e):void 0;if($B(e,{requestId:f}),f!==void 0&&(Kse(e,f),typeof o.setHeader==`function`&&o.setHeader(oS,f),typeof o.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:f,method:u,route:d,status:o.statusCode,durationMs:Date.now()-e,...o.writableFinished?{}:{aborted:!0}},`${u} ${d} ${o.statusCode}`))};o.once(`finish`,r),o.once(`close`,r)}if(s.startsWith(`/api/`)){let t=e.headers.origin;if(t!==void 0&&!XB(t,i))return K(o,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`}),!0;if(typeof o.setHeader==`function`&&(t!==void 0&&(o.setHeader(`Access-Control-Allow-Origin`,t),o.setHeader(`Vary`,`Origin`)),o.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),o.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${oS}, ${bi.protocol}, ${bi.runtime}, ${bi.kind}`),o.setHeader(`Access-Control-Expose-Headers`,oS)),e.method===`OPTIONS`)return o.writeHead(204),o.end(),!0}if(r.isMutating(s)){let t=e.socket?.remoteAddress;if(t!==void 0&&!qB(t,i))return K(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(e.headers.host))return K(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:HB}),!0}if(s.startsWith(`/api/`)){let t=n?`api-ephemeral-gate`:`api-read-gate`,r=e.socket?.remoteAddress;if(r!==void 0&&!qB(r,i))return K(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:t}),!0;if(!a(e.headers.host))return K(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:t,detail:HB}),!0}if(!s.startsWith(`/api/`))return!1;let p=Lo.extract(Bo.active(),e.headers),m=es(),h=Date.now();return await Bo.with(p,()=>m.startActiveSpan(`HTTP ${u} ${d}`,{kind:Ro.SERVER,attributes:{[Ds]:u,[ws]:d,[Ts]:s,[Cs]:`http`,[Ss]:e.headers[`user-agent`]??``,"ok.request.id":f}},async t=>{try{let n=c.dispatch;n===void 0?K(o,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${u} ${s}`}):await n(e,o);let r=o.statusCode;t.setAttribute(js,r),r>=500&&t.setStatus({code:Io.ERROR,message:`status ${r}`})}catch(e){throw t.recordException(e),t.setStatus({code:Io.ERROR,message:e instanceof Error?e.message:String(e)}),!o.headersSent&&!o.writableEnded&&!o.destroyed&&K(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:d,cause:e}),t.setAttribute(js,o.statusCode),e}finally{t.end();let e=(Date.now()-h)/1e3;nV().record(e,{[Ds]:u,[ws]:d,[js]:o.statusCode})}})),!0}}function iV(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof Qr||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;K(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}const aV=F(`asset-references`),oV=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function sV(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function cV(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),n=t.indexOf(`#`),r=n>=0?t.slice(0,n):t,i=r.indexOf(`?`);return i>=0?r.slice(0,i):r}function lV(e){let t=cV(e);return!t||sV(t)?!1:le.has(Il(t).slice(1).toLowerCase())}function uV(e){return e?[...new Set(_V(e).filter(lV))].sort().join(`\0`):``}function dV(e,t){return uV(e)!==uV(t)}function fV(e){let t=cV(e);try{return decodeURI(t)}catch{return t}}function pV(e){return Ae(Il(e).slice(1).toLowerCase())}function mV(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function hV(e,t){for(let n of Pue(e,{nestedBracketLabels:!0}))n.href&&t.add(n.href);for(let n of Nue(e))t.add(n.target);for(let n of e.matchAll(oV)){let e=n[1]??n[2]??n[3]??n[4];e&&t.add(e)}}function gV(e,t){let n=e,r=``;for(;n.length>0;){if(t.inComment){let e=n.indexOf(`-->`);if(e===-1)return r;n=n.slice(e+3),t.inComment=!1;continue}let e=n.indexOf(`<!--`);if(e===-1)return r+n;r+=n.slice(0,e),n=n.slice(e+4),t.inComment=!0}return r}function _V(e){let t=new Set,n=Tr(),r={inComment:!1};for(let i of e.replaceAll(`\r
97
+ `)}\n`:``;return o.length>0?{kind:`conflicts`,newContent:l,conflicts:o}:{kind:`merged`,newContent:l,mergedBlocks:a.length}}function _z(e,t){let n=new Map,r=vz(e,t);for(let t=0;t<=e.length;t++)n.set(t,{action:`keep`,insertsBefore:[]});let i=new Set,a=new Set;for(let[e,t]of r)i.add(e),a.add(t);let o=-1;for(let s=0;s<e.length;s++)if(i.has(s)){let e=r.find(e=>e[0]===s)?.[1]??-1,i=[];for(let n=o+1;n<e;n++)a.has(n)||i.push(t[n]);let c=n.get(s);c&&(c.insertsBefore=i),o=e}else{let e=r.find(e=>e[0]>s),i=e?e[1]:t.length,c=[];for(let e=o+1;e<i;e++)a.has(e)||c.push(e);if(c.length>0){let e=c[0];a.add(e);let r=n.get(s);r&&(r.action=`modify`,r.newContent=t[e])}else{let e=n.get(s);e&&(e.action=`delete`)}}let s=[];for(let e=o+1;e<t.length;e++)a.has(e)||s.push(t[e]);let c=n.get(e.length);return c&&(c.insertsBefore=s),n}function vz(e,t){let n=e.length,r=t.length,i=r+1,a=new Uint32Array((n+1)*i);for(let o=1;o<=n;o++){let n=o*i,s=(o-1)*i;for(let i=1;i<=r;i++)if(e[o-1]===t[i-1])a[n+i]=a[s+(i-1)]+1;else{let e=a[s+i],t=a[n+(i-1)];a[n+i]=e>t?e:t}}let o=[],s=n,c=r;for(;s>0&&c>0;)e[s-1]===t[c-1]?(o.push([s-1,c-1]),s--,c--):a[(s-1)*i+c]>=a[s*i+(c-1)]?s--:c--;return o.reverse()}function yz(e,t,n,r,i,a,o){if(Zx(n)||Qx(n)||eS(n)||tS(n))return;let s=t.documents.get(n);if(!s)return;let c=s.getText(`source`).toString(),l=c===r,u=jt(c).frontmatter,{frontmatter:d}=jt(r),f=o&&Rx(uz.context.origin)?{report:e=>o(n,e,Tx.id,`file-watcher-intake`),baselineFullMd:c}:void 0;try{s.transact(()=>{dz(s,r,i,n,a,f)},uz)}catch(t){throw e.setReconciledBase(n,s.getText(`source`).toString()),t}u!==d&&ES(`file-watcher`),l||ej(n,Tx.id,Tx.name,Tx.id,sd(n)),e.setReconciledBase(n,r)}function bz(e,t,n,r,i){return async(a,o)=>{try{yz(e,t,a,o,n,r,i),F(`file-watcher`).info({docName:a},`applied external change`)}catch(e){if(e instanceof yt||e instanceof Qr)throw e;nse(),F(`file-watcher`).error({docName:a,err:e},`Failed to apply external change for ${a}`)}}}const xz={reconciled:!1,baseBytes:0,diskBytes:0};function Sz(e){let{frontmatter:t,body:n}=jt(e.getText(`source`).toString());return Fn(t,n)}function Cz(e,t,n,r,i,a){if(Zx(n)||Qx(n)||eS(n)||tS(n))return xz;let o=t.documents.get(n);if(o&&mS(o))return xz;let s=e.getReconciledBase(n);if(s===void 0)return xz;let c;try{let e=cN(n,r);if(!B(e))return xz;c=H(e)}catch{return xz}if(!lN(c,r))return F(`reconcile`).warn({docName:n,canonical:c,contentDir:r},`[reconcile] symlink-escape on disk read for ${n}; skipping reconcile`),xz;let l;try{l=V(c,`utf-8`)}catch(e){let t=e?.code;return t!==`ENOENT`&&F(`reconcile`).warn({docName:n,canonical:c,code:t},`[reconcile] disk read failed for ${n} (${t??`unknown`}); skipping reconcile`),xz}if(Hi(l)===Hi(s))return xz;let u=e.peekInFlightFlush(n);if(u!==void 0){if(Hi(l)===u)return rse(),F(`reconcile`).debug({docName:n,diskBytes:l.length},`[reconcile] disk matches own in-flight flush for ${n}; skipping reconcile`),xz;ise(),F(`reconcile`).warn({docName:n,diskBytes:l.length},`[reconcile] in-flight flush present but disk differs from snapshot for ${n}; falling through to merge`)}if(!o)return xz;let d=hz({docName:n,base:s,ours:Sz(o),theirs:l});switch(F(`reconcile`).info({docName:n,result:d.kind,baseBytes:s.length,diskBytes:l.length},`[reconcile] before-agent-write ${n} result=${d.kind}`),d.kind){case`noop`:return xz;case`conflicts`:case`refused`:{let e=o.getMap(`lifecycle`);return e.set(`status`,`conflict`),e.set(`reason`,d.kind===`refused`?d.reason:`reconcile-conflicts`),xz}case`clean`:case`merged`:return yz(e,t,n,d.kind===`clean`?l:d.newContent,i,void 0,a),d.kind===`merged`&&e.setReconciledBase(n,l),{reconciled:!0,baseBytes:Buffer.byteLength(s,`utf8`),diskBytes:Buffer.byteLength(l,`utf8`),mergeOutcome:d.kind}}}const wz=new Map;function Tz(e,t){wz.set(e,t)}function Ez(e,t){let n=wz.get(e);if(n===void 0)return null;if(!Wa.test(e)||e.length>64)throw Error(`externalSkillAbsPath: invalid skill name ${JSON.stringify(e)}`);let r;if(t===null)r=z(n,`SKILL.md`);else{let e=t.split(`/`).filter(e=>e!==``&&e!==`.`);if(e.length===0||e.some(e=>e===`..`))throw Error(`externalSkillAbsPath: invalid bundle path ${JSON.stringify(t)}`);r=z(n,...e)}if(!r.startsWith(n+Vl))throw Error(`externalSkillAbsPath: path escape for ${JSON.stringify(e)}`);return r}const Dz=F(`file-watcher`);function Oz(e){throw Error(`[DiskEvent] unhandled variant: ${JSON.stringify(e)}`)}function kz(e,t){return{title:sk(e,t),icon:lk(e)}}function Az(e){let t=new Map;for(let[n,r]of e)r.kind===`markdown`&&t.set(n,r);return t}const jz=new Map,Mz=1e4;function Nz(e,t){let n=jz.get(e)??[];n.push({hash:t,timestamp:Date.now()}),jz.set(e,n)}function Pz(){let e=Date.now();for(let[t,n]of jz){let r=n.filter(t=>e-t.timestamp<=Mz);r.length===0?jz.delete(t):r.length!==n.length&&jz.set(t,r)}}function Fz(e){return Cu(`sha256`).update(e).digest(`hex`)}const Iz=[],Lz=new Map;let Rz=0,zz=0,Bz=0;function Vz(e,t,n){if(Iz.push({ts:Date.now(),decision:e,kind:t,path:ds(n),pathRole:gs(n)}),Iz.length>256&&Iz.shift(),e===`dispatched`){Rz++;return}if(e===`self-write-skip`){zz++;return}let r=e.slice(5);Lz.set(r,(Lz.get(r)??0)+1),Bz++,uB().add(1,{"disk.drop_reason":r})}function Hz(){return Iz.map(e=>({...e}))}function Uz(){if(Bz===0)return;let e=Bz;Bz=0;let t={};for(let[e,n]of Lz)t[e]=n;Dz.info({droppedSinceLastSummary:e,dropTotals:t,dispatched:Rz,selfWriteSkips:zz},`[file-watcher] drop summary: ${e} event(s) dropped since last summary`)}function Wz(){Iz.length=0,Lz.clear(),Rz=0,zz=0,Bz=0}function Gz(e,t){let n;try{n=Yl(e)}catch(t){let n=Us(t);return n===`ENOENT`?!1:(Dz.warn({path:e,code:n},`lstat failed for escape check on ${e} (${n}), dropping event`),!0)}if(!n.isSymbolicLink())return!1;let r;try{r=H(e)}catch(t){let n=Us(t);return n!==`ENOENT`&&n!==`ELOOP`&&Dz.warn({path:e,code:n},`realpath failed for escape check on ${e} (${n}), dropping event`),!0}return!lN(r,t)}function Kz(e,t){return Vx(oN(R(t,e)))}function qz(e,t){let n=R(e,t).replaceAll(`\\`,`/`);return!n||n===`.`||n===`..`||n.startsWith(`../`)?null:n}function Jz(e,t,n,r,i=n){let a=qz(t,n);return a?(e.set(a,{size:0,modified:r.mtime.toISOString(),canonicalPath:i,inode:Number(r.ino)}),a):null}function Yz(e,t){let n=!1;for(let r of e.keys())(r===t||r.startsWith(`${t}/`))&&(e.delete(r),n=!0);return n}function Xz(e){let t=Il(e);if(t===``)return null;let n=t.toLowerCase();return n===`.mdx`||n===`.md`?t:null}const Zz=new Map;function Qz(e,t){Zz.set(e,t)}function $z(e){let t=Zz.get(e);return Zz.delete(e),t}async function eB(e,t,n,r){let i=[],a=[],o=[];for(let r of e)if(zx(r.path)){if(n){let e=oN(R(t,r.path));if(n.isExcluded(e)){Vz(`drop-filter-excluded`,r.type,r.path);continue}}switch(r.type){case`delete`:i.push(r);break;case`create`:Zz.has(r.path)?o.push(r):a.push(r);break;case`update`:o.push(r);break}}let s=new Map,c=new Map;for(let e of a)try{s.set(e.path,await _u(e.path,`utf-8`))}catch(t){Vz(`drop-read-failed`,e.type,e.path),Us(t)!==`ENOENT`&&Dz.warn({path:e.path,err:t},`Failed to read ${e.path}`)}for(let e of o)try{c.set(e.path,await _u(e.path,`utf-8`))}catch(t){Vz(`drop-read-failed`,e.type,e.path),Us(t)!==`ENOENT`&&Dz.warn({path:e.path,err:t},`Failed to read ${e.path}`)}function l(e){let n=Kz(e,t);if(!r)return n;let i=null;try{i=Yl(e)}catch(t){return Us(t)!==`ENOENT`&&Dz.warn({path:e,err:t},`resolveDocName lstat failed for ${e}`),r.has(n)&&r.delete(n),n}if(!i.isSymbolicLink())return r.has(n)&&r.delete(n),n;let a;try{a=H(e)}catch(t){let i=Us(t);return i!==`ENOENT`&&i!==`ELOOP`&&Dz.warn({path:e,err:t},`resolveDocName realpath failed for ${e}`),r.delete(n),n}if(!lN(a,t))return r.delete(n),n;let o=Kz(a,t);return o===n?n:(r.set(n,o),o)}let u=[],d=new Set,f=new Set;for(let e of i){let t=$z(e.path);if(t)for(let n of a){if(d.has(n.path))continue;let r=s.get(n.path);if(r===void 0)continue;let i=Fz(r);if(i===t){d.add(n.path),f.add(e.path),Qz(n.path,i),u.push({kind:`rename`,oldPath:e.path,newPath:n.path,oldDocName:l(e.path),newDocName:l(n.path),content:r});break}}}for(let e of i)f.has(e.path)||($z(e.path),u.push({kind:`delete`,path:e.path,docName:l(e.path)}));for(let e of a){if(d.has(e.path))continue;let t=s.get(e.path);if(t===void 0)continue;let n=Fz(t);Qz(e.path,n),pz(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`create`,path:e.path,docName:l(e.path),content:t})}for(let e of o){let t=c.get(e.path);if(t===void 0)continue;let n=Fz(t);Qz(e.path,n),pz(t)?u.push({kind:`conflict`,path:e.path,docName:l(e.path),content:t}):u.push({kind:`update`,path:e.path,docName:l(e.path),content:t})}return u}function tB(e,t){let n=jz.get(e);if(!n)return!1;let r=n.findIndex(e=>e.hash===t);return r<0?!1:(n.splice(r,1),n.length===0&&jz.delete(e),!0)}async function nB(e,t,n,r,i,a,o,s){let c=s??new Set;try{let s=await vu(e,{withFileTypes:!0});for(let l of s){let s=L(e,l.name),u;try{u=await gu(s)}catch(e){Us(e)!==`ENOENT`&&Dz.warn({path:s,err:e},`Failed to lstat ${s}, skipping`);continue}if(u.isSymbolicLink()){let e;try{e=await yu(s)}catch(e){let t=Us(e);t===`ENOENT`||t===`ELOOP`?Dz.warn({path:s,code:t},`Broken/cyclic symlink at ${s}, skipping`):Dz.warn({path:s,err:e},`Failed to resolve symlink ${s}`);continue}if(!lN(e,t)){Dz.warn({path:s,canonical:e},`Symlink escape: ${s} → ${e}, skipping`);continue}try{let u=await bu(e);if(c.has(u.ino)){if(u.isFile()&&zx(l.name)){let n=Kz(s,t),i=Kz(e,t);a.set(n,i);let o=r.get(i);o&&!o.aliases.includes(n)&&o.aliases.push(n)}else if(u.isDirectory()){let r=qz(t,s);(!n||r&&!n.isDirExcluded(r))&&o.set(Kz(s,t),Kz(e,t))}continue}if(c.add(u.ino),u.isDirectory()){let l=qz(t,s);if(n&&(!l||n.isDirExcluded(l)))continue;o.set(Kz(s,t),Kz(e,t)),await nB(e,t,n,r,i,a,o,c)}else if(u.isFile()&&zx(l.name)){if(n){let r=oN(R(t,e));if(n.isExcluded(r))continue}let i=Kz(s,t),o=Kz(e,t);a.set(i,o);try{let t=await _u(e,`utf-8`),n=Fz(t);Zz.set(e,n);let a=Xz(e);if(a){let e=Gx(o,a);if(e.shadowed&&(Dz.warn({docName:o,effective:e.effective,shadowed:e.shadowed},`docName "${o}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(o,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[i],kind:`markdown`,...kz(t,o)})}catch(t){Us(t)!==`ENOENT`&&Dz.warn({path:e,err:t},`Failed to seed hash for ${e}`)}}else if(u.isFile()){if(n){let r=oN(R(t,e));if(n.isPathIgnored(r))continue}let i=Kz(s,t);if(Zx(i)||Qx(i))continue;r.set(i,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:e,inode:u.ino,aliases:[],kind:`file`})}}catch(t){Dz.warn({path:e,err:t},`Failed to stat symlink target ${e}`)}}else if(u.isDirectory()){let e=qz(t,s);if(n&&(!e||n.isDirExcluded(e)))continue;Jz(i,t,s,u),await nB(s,t,n,r,i,a,o,c)}else if(u.isFile()&&zx(l.name)){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=oN(R(t,s));if(n.isExcluded(e))continue}try{let e=await _u(s,`utf-8`);Zz.set(s,Fz(e));let n=Kz(s,t),i=Xz(s);if(i){let e=Gx(n,i);if(e.shadowed&&(Dz.warn({docName:n,effective:e.effective,shadowed:e.shadowed},`docName "${n}" has both "${e.effective}" and "${e.shadowed}" on disk; "${e.effective}" wins (industry convention). Rename or delete one to disambiguate.`),!e.changed))continue}r.set(n,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`markdown`,...kz(e,n)})}catch(e){let t=Us(e);t===`EACCES`?Dz.warn({path:s,code:t},`Permission denied reading ${s}, file excluded from index`):t!==`ENOENT`&&Dz.warn({path:s,err:e},`Failed to seed hash for ${s}`)}}else if(u.isFile()){if(c.has(u.ino))continue;if(c.add(u.ino),n){let e=oN(R(t,s));if(n.isPathIgnored(e))continue}let e=Kz(s,t);if(Zx(e)||Qx(e))continue;r.set(e,{size:u.size,modified:u.mtime.toISOString(),canonicalPath:s,inode:u.ino,aliases:[],kind:`file`})}}}catch(t){Us(t)!==`ENOENT`&&Dz.warn({dir:e,err:t},`Failed to read directory ${e}`)}}function rB(e,t){if(!(e.kind===`asset-create`||e.kind===`asset-delete`||e.kind===`folder-create`||e.kind===`folder-delete`)){if(e.kind===`file-create`||e.kind===`file-update`||e.kind===`file-delete`){let n=e.relativePath;if(Zx(n)||Qx(n))return;if(e.kind===`file-delete`){let e=t.get(n);e&&e.kind===`file`&&t.delete(n);return}let r=t.get(n);if(r&&r.kind===`markdown`)return;t.set(n,{size:e.size,modified:new Date(e.modifiedTs).toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:e.inode||r?.inode||0,aliases:r?.aliases??[],kind:`file`});return}if(!nS(e.kind===`rename`?e.newDocName:e.docName))switch(e.kind){case`create`:case`update`:case`conflict`:{let n=e.docName,r=t.get(n),i=Xz(e.path);i&&Gx(n,i),t.set(n,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:r?.canonicalPath??e.path,inode:r?.inode??0,aliases:r?.aliases??[],kind:`markdown`,...kz(e.content,n)});break}case`delete`:if(t.has(e.docName))t.delete(e.docName),Xx(e.docName);else for(let[,n]of t){let t=n.aliases.indexOf(e.docName);if(t!==-1){n.aliases.splice(t,1);break}}break;case`rename`:{let n=t.get(e.oldDocName);t.delete(e.oldDocName),Xx(e.oldDocName);let r=Xz(e.newPath);r&&Gx(e.newDocName,r),t.set(e.newDocName,{size:Buffer.byteLength(e.content,`utf-8`),modified:new Date().toISOString(),canonicalPath:n?.canonicalPath??e.newPath,inode:n?.inode??0,aliases:n?.aliases??[],kind:`markdown`,...kz(e.content,e.newDocName)});break}default:Oz(e)}}}function iB(e,t,n,r){let i=[],a=[];for(let o of e){let e=qz(t,o.path);if(!e)continue;if(o.type===`delete`){Yz(r,e)&&i.push({kind:`folder-delete`,path:o.path,relativePath:e});continue}let s;try{s=Yl(o.path)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:o.path,code:t},`folder lstat failed for ${o.path} (${t})`);continue}let c=null,l=o.path;if(s.isDirectory())c=s;else if(s.isSymbolicLink())try{if(l=H(o.path),!lN(l,t))continue;let e=ou(l);e.isDirectory()&&(c=e)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:o.path,code:t},`folder symlink resolve failed for ${o.path} (${t})`),c=null}if(!c||n?.isDirExcluded(e))continue;let u=r.has(e);Jz(r,t,o.path,c,l),u||(i.push({kind:`folder-create`,path:o.path,relativePath:e}),aB(l,t,n,r,i,a))}return{events:i,untrackedFiles:a}}function aB(e,t,n,r,i,a){let o=[e];for(;o.length>0;){let e=o.shift();if(e===void 0)continue;let s;try{s=tu(e,{withFileTypes:!0})}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({dir:e,code:n},`folder rescan readdir failed for ${e} (${n})`);continue}for(let c of s){if(c.isFile()){a.push(L(e,c.name));continue}if(!c.isDirectory())continue;let s=L(e,c.name),l=qz(t,s);if(!l||n?.isDirExcluded(l))continue;let u;try{u=Yl(s)}catch(e){let t=Us(e);t!==`ENOENT`&&Dz.warn({path:s,code:t},`folder rescan lstat failed for ${s} (${t})`);continue}u.isDirectory()&&(r.has(l)||(Jz(r,t,s,u),i.push({kind:`folder-create`,path:s,relativePath:l})),o.push(s))}}}async function oB(e,t,n,r,i,a,o){let s=e.filter(e=>Gz(e.path,t)?(Vz(`drop-symlink-escape`,e.type,e.path),Dz.warn({path:e.path,type:e.type},`Symlink escape: ${e.path}, dropping ${e.type} event`),!1):!0),{events:c,untrackedFiles:l}=iB(s,t,n,i),u=[];if(l.length>0){let e=new Set(s.map(e=>e.path)),n=new Set;for(let e of r.values())n.add(e.canonicalPath);u=l.filter(t=>!e.has(t)&&!Zz.has(t)&&!n.has(t)).filter(e=>Gz(e,t)?(Vz(`drop-symlink-escape`,`create`,e),!1):!0).map(e=>({type:`create`,path:e})),u.length>0&&Dz.debug({count:u.length,paths:u.map(e=>oN(R(t,e.path)))},`[file-watcher] re-injecting rescued file creates from new-folder rescan`)}let d=u.length>0?s.concat(u):s,f=d.filter(e=>zx(e.path)),p=d.filter(e=>Bx(e.path,le)),m=d.filter(e=>!zx(e.path));if(f.length===0&&p.length===0&&c.length===0&&m.length===0)return;let h=f.length>0?await eB(f,t,n,o):[];for(let e of h){let t=!1;if(e.kind!==`delete`&&e.kind!==`rename`){let n=Fz(e.content),r=e.path;try{r=H(e.path)}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({path:e.path,code:n},`realpathSync failed for self-write check on ${e.path} (${n})`)}t=tB(r,n)}else if(e.kind===`rename`){let n=Fz(e.content),r=e.newPath;try{r=H(e.newPath)}catch(t){let n=Us(t);n!==`ENOENT`&&Dz.warn({path:e.newPath,code:n},`realpathSync failed for self-write check on ${e.newPath} (${n})`)}t=tB(r,n)}if(rB(e,r),n&&!t)switch(e.kind){case`create`:n.incrementMdDir(I(e.docName));break;case`delete`:n.decrementMdDir(I(e.docName));break;case`rename`:n.decrementMdDir(I(e.oldDocName)),n.incrementMdDir(I(e.newDocName));break;case`update`:case`conflict`:break;default:Oz(e)}if(t){Dz.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path,self:!0},`[file-watcher] Skipped self-write: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!0}),Vz(`self-write-skip`,e.kind,e.kind===`rename`?e.newPath:e.path);continue}Dz.debug({kind:e.kind,path:e.kind===`rename`?e.newPath:e.path},`[file-watcher] Dispatching: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!1});let i=e.kind===`rename`?e.newPath:e.path;Vz(`dispatched`,e.kind,i),await Zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":ds(i),"disk.path.role":gs(i)}},async()=>a(e))}for(let e of c)Dz.debug({kind:e.kind,path:e.path},`[file-watcher] Dispatching: ${e.kind}`),cB().add(1,{"disk.kind":e.kind,self:!1}),Vz(`dispatched`,e.kind,e.path),await Zo(`file_watcher.process_event`,{attributes:{"disk.kind":e.kind,"disk.path":ds(e.path),"disk.path.role":gs(e.path)}},async()=>a(e));for(let e of p){if(n){let r=oN(R(t,e.path));if(n.isExcluded(r)){Vz(`drop-filter-excluded`,e.type,e.path);continue}}let r=oN(R(t,e.path)),i=e.type===`delete`?{kind:`asset-delete`,path:e.path,relativePath:r}:{kind:`asset-create`,path:e.path,relativePath:r};Vz(`dispatched`,i.kind,e.path),await a(i)}for(let e of m){let i=oN(R(t,e.path));if(n?.isPathIgnored(i)){Vz(`drop-filter-excluded`,e.type,e.path);continue}if(Zx(i)||Qx(i)){Vz(`drop-reserved-doc`,e.type,e.path);continue}if(e.type===`delete`){let t={kind:`file-delete`,path:e.path,relativePath:i};rB(t,r),Vz(`dispatched`,t.kind,e.path),await a(t);continue}let o;try{o=Yl(e.path),o.isSymbolicLink()&&(o=ou(e.path))}catch(t){let n=Us(t);Vz(`drop-stat-failed`,e.type,e.path),n!==`ENOENT`&&Dz.warn({path:e.path,code:n},`file-event lstat failed for ${e.path} (${n})`);continue}if(!o.isFile())continue;let s=e.type===`create`?{kind:`file-create`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)}:{kind:`file-update`,path:e.path,relativePath:i,size:o.size,modifiedTs:o.mtime.getTime(),inode:Number(o.ino)};rB(s,r),Vz(`dispatched`,s.kind,e.path),await a(s)}}let sB=null;function cB(){return sB||=xs().createCounter(`ok.file_watcher.events`,{description:`Number of file-watcher events classified by kind`}),sB}let lB=null;function uB(){return lB||=xs().createCounter(`ok.file_watcher.drops`,{description:`File-watcher events dropped before dispatch, by bounded reason`}),lB}async function dB(e,t,n,r,i,a,o,s){let c;try{c=await import(`@parcel/watcher`)}catch(e){return Dz.debug({err:e instanceof Error?e.message:String(e)},`[file-watcher] @parcel/watcher import failed; falling back to chokidar`),null}try{let l=t?{ignore:t.getWatcherIgnoreGlobs()}:void 0;return await c.subscribe(e,async(c,l)=>{if(c){Dz.error({err:c},`parcel watcher callback error`);return}try{s?.(l.map(e=>e.path)),await oB(l.map(e=>({type:e.type,path:e.path})),e,t,n,r,i,a),o()}catch(e){Dz.error({err:e},`parcel batch error`)}},l)}catch(e){return Dz.warn({err:e},`@parcel/watcher subscribe failed, falling back to chokidar`),null}}function fB(e,t,n,r){let i=oN(R(e,n));if(i===``||i===`.`)return!1;let a;if(r)a=r.isDirectory();else try{a=Yl(n).isDirectory()}catch{return!1}if(a){let n=/^(\.[A-Za-z0-9_-]+)(\/skills(\/[^/]+)?)?$/.exec(i);return n&&n[1]!==`.ok`&&(n[2]!==void 0||B(L(e,i,`skills`)))?!1:t.isDirExcluded(i)}return t.isExcluded(i)}async function pB(e,t,n,r,i,a,o,s){let{watch:c}=await import(`./chokidar-dh8zokRd.mjs`),l=c(e,{ignoreInitial:!0,followSymlinks:!1,ignored:t?(n,r)=>fB(e,t,n,r):void 0});l.on(`error`,e=>Dz.error({err:e},`chokidar error`));let u=[],d=null;function f(c,l){u.push({type:c,path:l}),d||=setTimeout(()=>{let c=u;u=[],d=null,s?.(c.map(e=>e.path)),oB(c,e,t,n,r,i,a).then(o).catch(e=>Dz.error({err:e},`chokidar batch error`))},50)}return l.on(`add`,e=>f(`create`,e)),l.on(`change`,e=>f(`update`,e)),l.on(`unlink`,e=>f(`delete`,e)),l.on(`addDir`,e=>f(`create`,e)),l.on(`unlinkDir`,e=>f(`delete`,e)),await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};l.once(`ready`,n),setTimeout(n,1e4).unref()}),{unsubscribe:()=>(d&&(clearTimeout(d),d=null,u=[]),l.close())}}async function mB(e,t,n,r={}){let{onRawBatch:i}=r,a;try{a=H(e)}catch{a=e}let o=new Map,s=new Map,c=new Map,l=new Map,u=0,d=null,f=-1,p=()=>{u++};await nB(a,a,n,o,s,c,l),p();let m=setInterval(Pz,Mz),h=setInterval(Uz,6e4),g,_,v=process.env.OK_FILE_WATCHER_BACKEND===`chokidar`;try{let e=v||r.forceBackend===`chokidar`?null:await dB(a,n,o,s,t,c,p,i);if(e)g=e,_=`parcel`;else{if(r.forceBackend===`parcel`)throw Error(`@parcel/watcher unavailable (forced backend)`);g=await pB(a,n,o,s,t,c,p,i),_=`chokidar`}}catch(e){throw clearInterval(m),clearInterval(h),e}let y=g.unsubscribe.bind(g);return Dz.info({contentDir:a,backend:_},`watching for external .md changes`),{async unsubscribe(){return clearInterval(m),clearInterval(h),jz.clear(),Zz.clear(),Wz(),y()},getFileIndex(){return d&&f===u?d:(d=Az(o),f=u,d)},getAllFilesIndex(){return o},getFileIndexGeneration(){return u},getFolderIndex(){return s},getAliasMap(){return c},getFolderAliasIndex(){return l},mutateFileIndex(e){rB(e,o),p()},pruneFileIndexNowExcluded(){if(!n)return 0;let e=0;for(let[t,r]of o){let i=oN(R(a,r.canonicalPath));(r.kind===`file`?n.isPathIgnored(i):n.isExcluded(i))&&(o.delete(t),e++)}return e>0&&p(),e},pruneFolderIndexNowExcluded(){if(!n)return 0;let e=0;for(let t of s.keys())n.isDirExcluded(t)&&(s.delete(t),e++);return e},async rescanFromDisk(){await nB(a,a,n,o,s,c,l),p()}}}async function hB(e){if(!e)return{prunedFiles:0,prunedFolders:0};let t=e.pruneFileIndexNowExcluded(),n=e.pruneFolderIndexNowExcluded();return await e.rescanFromDisk(),{prunedFiles:t,prunedFolders:n}}function gB(e){try{return ou(z(e,ce)).isFile()}catch(e){let t=e?.code;if(t===`ENOENT`||t===`ENOTDIR`)return!1;throw e}}function _B(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=gB(t)}catch{e=!1}if(e)return{rootPath:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}async function vB(e,t){let{git:n}=Is(e),[r,i]=await Promise.allSettled([toe(n),Wb(n,[`diff`,`--name-only`,`HEAD..${t}`])]);if(i.status===`rejected`)throw i.reason;if(r.status===`rejected`)throw r.reason;let a=r.value,o=i.value,s=new Set(a);if(s.size===0||o.length===0)return{conflicts:!1,files:[]};let c=new Set;for(let e of o)s.has(e)&&c.add(e);return c.size===0?{conflicts:!1,files:[]}:{conflicts:!0,files:Array.from(c).sort()}}function yB(e,t){if(typeof e!=`string`)return!1;if(e.length===0)return t===`folder`;if(e.startsWith(`/`)||e.includes(`\\`)||/[\x00-\x1F\x7F]/.test(e))return!1;for(let t of e.split(`/`))if(t.length===0||t===`..`||t===`.git`)return!1;return!0}async function bB(e,t,n,r){let{git:i}=Is(e);await i.raw([`rev-parse`,`--git-dir`]);let a=(async()=>{try{let e=(await i.raw([`symbolic-ref`,`HEAD`])).trim(),t=/^refs\/heads\/(.+)$/.exec(e);return{detached:!1,currentBranch:t?t[1]:null,currentHeadSha:null}}catch{let e=(await i.raw([`rev-parse`,`--short=7`,`HEAD`])).trim();return e.length===0?{detached:!1,currentBranch:null,currentHeadSha:null}:{detached:!0,currentBranch:null,currentHeadSha:e}}})(),o=a.then(async e=>{if(r===`folder`&&n===``)return!0;let t=e.detached?`HEAD`:e.currentBranch;if(!t)return!1;try{return await i.raw([`cat-file`,`-e`,`${t}:${n}`]),!0}catch{return!1}}),s=i.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1),c=(async()=>{let e=`origin/${t}`;if(await i.raw([`rev-parse`,`--verify`,e]).then(()=>!0).catch(()=>!1))return r===`folder`&&n===``?!0:i.raw([`cat-file`,`-e`,`${e}:${n}`]).then(()=>!0).catch(()=>!1)})(),l=vB(e,t).catch(e=>(SB(e)||F(`git-branch-info`).warn({branch:t,err:e},`action=dirty-overlap-failed branch=${t} error=${VF(e)}`),{conflicts:!1,files:[]})),[u,d,f,p,m]=await Promise.all([a,o,s,l,c]);return u.detached?{detached:!0,currentBranch:null,currentHeadSha:u.currentHeadSha,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}:{detached:!1,currentBranch:u.currentBranch,currentHeadSha:null,shareTargetExists:d,dirtyConflicts:p,branchIsLocal:f,shareTargetOnOriginBranch:m}}const xB=`git-branch-info`;function SB(e){let t=e instanceof Error?e.message:String(e);return/unknown revision|bad revision|ambiguous argument/i.test(t)}const CB=F(`git-checkout`),wB=/'[^']+' is already (?:checked out|used by worktree) at '([^']+)'/;function TB(e){let t=(e instanceof Error?e.message:typeof e==`string`?e:``).match(wB);if(t===null)return{held:!1};let n=t[1];if(n===void 0||n.length===0)return{held:!1};let r;try{r=H(n)}catch{r=n}return{held:!0,path:r}}const EB=`git-checkout`,DB=ho;async function OB(e,t,n){if(n?.fastForward&&await kB(e,t)===`diverged`)return{ok:!1,reason:`ff-diverged`};let{git:r}=Is(e),i=await r.raw([`rev-parse`,`--verify`,`refs/heads/${t}`]).then(()=>!0).catch(()=>!1);if(!i)try{await r.raw([`fetch`,`origin`,t])}catch(e){return{ok:!1,reason:DB(e)?`branch-not-found`:`fetch-failed`}}let a=await vB(e,i?t:`origin/${t}`);if(a.conflicts)return{ok:!1,reason:`dirty-conflict`,files:a.files};try{return await r.raw([`checkout`,t]),{ok:!0}}catch(e){let n=TB(e);return n.held?(CB.warn({branch:t,heldAt:n.path},`reason=branch-in-other-worktree branch=${t} held_at=${n.path}`),{ok:!1,reason:`branch-in-other-worktree`,otherWorktreePath:n.path}):(CB.warn({branch:t,err:e},`action=checkout-failed branch=${t} error=${VF(e)}`),{ok:!1,reason:`checkout-failed`})}}async function kB(e,t){let{git:n}=Is(e,{timeoutMs:15e3}),r=e=>n.raw([`rev-parse`,`--verify`,e]).then(e=>e.trim()).catch(()=>null);try{await n.raw([`fetch`,`origin`,t])}catch(e){return CB.warn({branch:t,err:e},`action=ff-fetch-failed branch=${t} error=${VF(e)}`),`unavailable`}let i=await r(`refs/remotes/origin/${t}`);if(!i)return`unavailable`;let a=await r(`refs/heads/${t}`);if(!a||a===i)return`up-to-date`;let o=await n.raw([`merge-base`,a,i]).then(e=>e.trim()).catch(()=>``);if(o===a){try{await n.raw([`fetch`,`origin`,`${t}:${t}`])}catch(e){return CB.warn({branch:t,err:e},`action=ff-advance-failed branch=${t} error=${VF(e)}`),`unavailable`}return await r(`refs/heads/${t}`)===i?`advanced`:`unavailable`}return o===i?`up-to-date`:`diverged`}const AB=(e,t)=>{let n=Ml(`git`,[`config`,`--get`,t],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));return n.status!==0||!n.stdout?null:n.stdout.trim()||null};function jB(e){let t=Ml(`git`,[`rev-parse`,`--git-dir`],fN({cwd:e,encoding:`utf-8`,timeout:5e3})),n=Ml(`git`,[`rev-parse`,`--git-common-dir`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));return t.status!==0||n.status!==0?!1:z(e,t.stdout.trim())!==z(e,n.stdout.trim())}function MB(e){let t=Ml(`git`,[`config`,`--local`,`--get`,`extensions.worktreeConfig`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(t.status===0&&/^(true|yes|on|1)$/i.test(t.stdout.trim()))return;let n=Ml(`git`,[`config`,`--local`,`extensions.worktreeConfig`,`true`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(n.status!==0){let e=n.stderr?.trim()??``,t=n.error?` [${n.error.message}]`:``;throw Error(`failed to enable extensions.worktreeConfig: ${e}${t}`)}}async function NB(e,t,n,r=AB){let i=r(e,`user.name`),a=r(e,`user.email`);if(i&&a)return{name:i,email:a};if(t&&n){let e=await t.get(n);if(e){let t=e.name??e.login,n=e.email??`${e.login}@users.noreply.github.com`;if(t)return{name:t,email:n}}}return null}function PB(e,t,n){let r=`--local`;jB(e)&&(MB(e),r=`--worktree`);let i=(t,n)=>{let i=Ml(`git`,[`config`,r,t,n],fN({cwd:e,encoding:`utf-8`,timeout:5e3}));if(i.status!==0){let e=i.stderr?.trim()??``,n=i.error?` [${i.error.message}]`:``;throw Error(`git config ${r} ${t} failed: ${e}${n}`)}};i(`user.name`,t),i(`user.email`,n)}zo(),Ms();function FB(e){if(e===`null`||e===`file://`)return!0;try{let{hostname:t}=new URL(e);return t===`localhost`||t===`::1`||t===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)}catch{return!1}}function IB(e){return e?!!(e===`::1`||e.startsWith(`::ffff:127.`)||e.startsWith(`127.`)):!1}function LB(e){if(!e)return!1;if(e.startsWith(`[`)){let t=e.indexOf(`]`);if(t<0)return!1;let n=e.slice(1,t),r=e.slice(t+1);return r!==``&&!/^:\d+$/.test(r)?!1:n===`::1`}let t=e.lastIndexOf(`:`),n=t>=0?e.slice(0,t):e,r=t>=0?e.slice(t+1):null;return r!==null&&!/^\d+$/.test(r)?!1:!!(n===`localhost`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n))}function RB(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function zB(e,t){return e!==void 0&&RB(e)===t}const BB=[`x-forwarded-for`,`x-forwarded-proto`,`x-forwarded-host`,`forwarded`,`x-real-ip`,`x-client-ip`,`x-cluster-client-ip`,`cf-connecting-ip`,`fastly-client-ip`,`true-client-ip`];function VB(e){return BB.some(t=>e.headers[t]!==void 0)}const HB=`Add this host to server.bind or set server.externalUrl to it, then restart. Loopback (localhost/127.0.0.1/[::1]) is always admitted.`;var UB=class extends Error{};const WB=new Set([`0.0.0.0`,`::`,`localhost`,`::1`,`[::1]`]);function GB(e){let t=e.trim().toLowerCase();return t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t}function KB(e){let t=e.serverRuntime,n=t===void 0?[]:t.bind.map(GB).filter(e=>!WB.has(e)&&!e.startsWith(`127.`)),r;if(t?.externalUrlSource===`server`&&t.externalUrl!==void 0){let e=new URL(t.externalUrl);r={host:RB(e.host),protocol:e.protocol}}let i=t?.allowExternal===!0;return{allowExternal:i,bindLiterals:n,externalOrigin:r,tolerateForwardedHeaders:i&&r!==void 0}}function qB(e,t){return IB(e)?!0:t.allowExternal&&e!==void 0}function JB(e){if(e.startsWith(`[`)){let t=e.indexOf(`]`);return t<0?null:e.slice(1,t).toLowerCase()}let t=e.lastIndexOf(`:`);return(t>=0?e.slice(0,t):e).toLowerCase()}function YB(e,t){if(LB(e))return!0;if(e===void 0)return!1;if(t.bindLiterals.length>0){let n=JB(e);if(n!==null&&t.bindLiterals.includes(n))return!0}return t.externalOrigin!==void 0&&zB(e,t.externalOrigin.host)}function XB(e,t){if(FB(e))return!0;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!==`http:`&&n.protocol!==`https:`)return!1;if(t.externalOrigin!==void 0&&n.protocol===t.externalOrigin.protocol&&RB(n.host)===t.externalOrigin.host)return!0;if(t.bindLiterals.length>0){let e=GB(n.hostname);if(t.bindLiterals.includes(e))return!0}return!1}function ZB(e,t){return!t.tolerateForwardedHeaders&&VB(e)}const QB=new WeakMap;function $B(e,t){let n=e.socket?.remoteAddress,r={requestId:t.requestId,peerClass:n===void 0?`unknown`:IB(n)?`loopback`:`external`,actor:void 0};return QB.set(e,r),r}function eV(e){return QB.get(e)}let tV=null;Xo(()=>{tV=null});function nV(){return tV||=xs().createHistogram(`http.server.request.duration`,{description:`HTTP server request duration in seconds`,unit:`s`}),tV}function rV(e){let{log:t,ephemeral:n,table:r}=e,i=e.policy??KB({}),a=e=>YB(e,i);return async(e,o)=>{let s=e.url?.split(`?`)[0];if(!s)return!1;let c=r.resolve(s);if(!c)return!1;let l=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};dj({ts:Date.now(),url:s,method:e.method??``,ua:l(`user-agent`),origin:l(`origin`),referer:l(`referer`),host:l(`host`),remote:e.socket?.remoteAddress,secChUa:l(`sec-ch-ua`),secChUaMobile:l(`sec-ch-ua-mobile`),secChUaPlatform:l(`sec-ch-ua-platform`),secFetchSite:l(`sec-fetch-site`),secFetchDest:l(`sec-fetch-dest`),secFetchMode:l(`sec-fetch-mode`),secFetchUser:l(`sec-fetch-user`)});let u=e.method??`GET`,d=c.template,f=s.startsWith(`/api/`)?Gse(e):void 0;if($B(e,{requestId:f}),f!==void 0&&(Kse(e,f),typeof o.setHeader==`function`&&o.setHeader(oS,f),typeof o.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,t.info({event:`api.access`,requestId:f,method:u,route:d,status:o.statusCode,durationMs:Date.now()-e,...o.writableFinished?{}:{aborted:!0}},`${u} ${d} ${o.statusCode}`))};o.once(`finish`,r),o.once(`close`,r)}if(s.startsWith(`/api/`)){let t=e.headers.origin;if(t!==void 0&&!XB(t,i))return K(o,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`}),!0;if(typeof o.setHeader==`function`&&(t!==void 0&&(o.setHeader(`Access-Control-Allow-Origin`,t),o.setHeader(`Vary`,`Origin`)),o.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),o.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${oS}, ${bi.protocol}, ${bi.runtime}, ${bi.kind}`),o.setHeader(`Access-Control-Expose-Headers`,oS)),e.method===`OPTIONS`)return o.writeHead(204),o.end(),!0}if(r.isMutating(s)){let t=e.socket?.remoteAddress;if(t!==void 0&&!qB(t,i))return K(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`}),!0;if(!a(e.headers.host))return K(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`,detail:HB}),!0}if(s.startsWith(`/api/`)){let t=n?`api-ephemeral-gate`:`api-read-gate`,r=e.socket?.remoteAddress;if(r!==void 0&&!qB(r,i))return K(o,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:t}),!0;if(!a(e.headers.host))return K(o,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:t,detail:HB}),!0}if(!s.startsWith(`/api/`))return!1;let p=Lo.extract(Bo.active(),e.headers),m=es(),h=Date.now();return await Bo.with(p,()=>m.startActiveSpan(`HTTP ${u} ${d}`,{kind:Ro.SERVER,attributes:{[Ds]:u,[ws]:d,[Ts]:s,[Cs]:`http`,[Ss]:e.headers[`user-agent`]??``,"ok.request.id":f}},async t=>{try{let n=c.dispatch;n===void 0?K(o,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${u} ${s}`}):await n(e,o);let r=o.statusCode;t.setAttribute(js,r),r>=500&&t.setStatus({code:Io.ERROR,message:`status ${r}`})}catch(e){throw t.recordException(e),t.setStatus({code:Io.ERROR,message:e instanceof Error?e.message:String(e)}),!o.headersSent&&!o.writableEnded&&!o.destroyed&&K(o,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:d,cause:e}),t.setAttribute(js,o.statusCode),e}finally{t.end();let e=(Date.now()-h)/1e3;nV().record(e,{[Ds]:u,[ws]:d,[js]:o.statusCode})}})),!0}}function iV(e,t){return async(n,r,...i)=>{try{await e(n,r,...i)}catch(e){if(e instanceof Qr||e instanceof Error&&e.name===`BridgeMergeContentLossError`)throw e;K(r,500,`urn:ok:error:internal-server-error`,t.title??`Internal server error.`,{handler:t.handler,cause:e})}}}const aV=F(`asset-references`),oV=/<[\w:-]+\b[^>]*?\s+(?:href|src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)'|“([^”\n]*)”|([^\s"'=<>`]+))/gi;function sV(e){return e.startsWith(`#`)||e.startsWith(`//`)||e.startsWith(`data:`)||/^[a-z][a-z0-9+.-]*:/i.test(e)}function cV(e){let t=e.trim().replace(/^<(.+)>$/,`$1`),n=t.indexOf(`#`),r=n>=0?t.slice(0,n):t,i=r.indexOf(`?`);return i>=0?r.slice(0,i):r}function lV(e){let t=cV(e);return!t||sV(t)?!1:le.has(Il(t).slice(1).toLowerCase())}function uV(e){return e?[...new Set(_V(e).filter(lV))].sort().join(`\0`):``}function dV(e,t){return uV(e)!==uV(t)}function fV(e){let t=cV(e);try{return decodeURI(t)}catch{return t}}function pV(e){return Ae(Il(e).slice(1).toLowerCase())}function mV(e){return e instanceof Error&&`code`in e&&typeof e.code==`string`?e.code:null}function hV(e,t){for(let n of Pue(e,{nestedBracketLabels:!0}))n.href&&t.add(n.href);for(let n of Nue(e))t.add(n.target);for(let n of e.matchAll(oV)){let e=n[1]??n[2]??n[3]??n[4];e&&t.add(e)}}function gV(e,t){let n=e,r=``;for(;n.length>0;){if(t.inComment){let e=n.indexOf(`-->`);if(e===-1)return r;n=n.slice(e+3),t.inComment=!1;continue}let e=n.indexOf(`<!--`);if(e===-1)return r+n;r+=n.slice(0,e),n=n.slice(e+4),t.inComment=!0}return r}function _V(e){let t=new Set,n=Tr(),r={inComment:!1};for(let i of e.replaceAll(`\r
98
98
  `,`
99
99
  `).replaceAll(`\r`,`
100
100
  `).split(`
101
101
  `))n(i)||hV(gV(i,r).replace(/`[^`]*`/g,``),t);return[...t]}function vV(e){let t=fV(e.href);if(!t||sV(t))return null;let n=Il(t).slice(1).toLowerCase();if(!le.has(n))return null;let r=Di(t,e.fromDocName);if(!r)return null;let i=z(e.contentDir,r),a,o;try{if(a=Rl(H(i)),!lN(a,e.contentDir))return null;o=ou(a)}catch(t){let n=mV(t);return n!==`ENOENT`&&n!==`ENOTDIR`&&aV.warn({href:e.href,err:t},`unexpected error resolving asset`),null}return o.isFile()?{absolutePath:a,relativePath:yV(e.contentDir,a),stat:o}:null}function yV(e,t){let n=Rl(H(e));return Rl(t).slice(n.length+ +!n.endsWith(Vl)).split(Vl).join(`/`)}function bV(e){let t;try{t=Rl(H(e.contentDir))}catch(e){return aV.warn({err:e},`could not resolve content directory`),[]}let n=new Map;for(let[r,i]of e.fileIndex){let a=e.readMarkdown(i.canonicalPath);if(a!==null)for(let i of _V(a)){let a=vV({contentDir:t,fromDocName:r,href:i});if(!a||e.isExcluded?.(a.relativePath))continue;let o=pV(a.absolutePath),s=n.get(a.relativePath);if(s){s.referencedBy.includes(r)||s.referencedBy.push(r);continue}n.set(a.relativePath,{kind:`asset`,path:a.relativePath,assetExt:Il(a.relativePath).toLowerCase(),mediaKind:o,size:a.stat.size,modified:a.stat.mtime.toISOString(),referencedBy:[r]})}}return[...n.values()].sort((e,t)=>e.path.localeCompare(t.path))}function xV(e){let t=e.headers.accept;return typeof t==`string`&&t.includes(`application/x-ndjson`)}function SV(e){let{hocuspocus:t,contentDir:n,isSafeDocName:r,resolveAlias:i,resolveContentEntryPath:a,resolveDocPath:o,extractHeadings:s,getFileIndex:c,log:l,ready:u,contentFilter:d,safeSubdir:f,getShowAllMaxEntries:p,streamShowAllEntries:m,walkContentDirForShowAll:h,synthesizeShowAllAssetExt:g,getAllFilesIndex:_,getFolderIndex:v,getFolderAliasIndex:y,onReferencedAssetsCacheInvalidator:b}=e,x=new Map,S=null;function C(e){return[...e.entries()].map(([e,t])=>`${e}\0${t.canonicalPath}\0${t.size}\0${t.modified}\0${t.aliases.join(`\0`)}`).sort().join(`
102
- `)}function w(){S=null}b?.(w);function T(e){let t=e.getMap(`lifecycle`),n=t.get(`status`);if(typeof n!=`string`||n.length===0)return null;let r=t.get(`reason`);return{status:n,reason:typeof r==`string`?r:``}}let E=q(Zt,async(e,o)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!r(s)){K(o,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=i(s);if(Zx(c)||Qx(c)){K(o,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=t.documents.get(c);if(l){J(o,200,Pn,{docName:c,content:l.getText(`source`).toString(),lifecycle:T(l)},{handler:`document-read`});return}if(!B(a(n,`file`,c))){K(o,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let u=await t.openDirectConnection(c);try{let e=u.document;if(!e){K(o,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}J(o,200,Pn,{docName:c,content:e.getText(`source`).toString(),lifecycle:T(e)},{handler:`document-read`})}finally{await u.disconnect()}}catch(e){K(o,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),ee=q(Zt,async(e,t)=>{try{u&&await u.catch(e=>{l.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`dir`),a=r.searchParams.get(`showAll`)===`true`,o=r.searchParams.get(`showOk`)===`true`,s=r.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{f(n,i)}catch{K(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&d&&xV(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let r=pS(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=p(),r=m({contentDir:n,contentFilter:d,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,u=await r.next();for(;!u.done;)await a(`${JSON.stringify(u.value)}\n`),c+=1,u=await r.next();let{truncated:f}=u.value;f&&l.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:f,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?r(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):l.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&d){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,r=x.get(e);if(!r){let t=new AbortController,a=(async()=>{let e=[],r=p(),{truncated:a}=await h({contentDir:n,contentFilter:d,dirFilter:i,documents:e,maxEntries:r,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&l.info({handler:`document-list`,maxEntries:r,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();r={promise:a,controller:t,waiters:0};let c=r;x.set(e,c),a.finally(()=>{x.get(e)===c&&x.delete(e)})}let a=r;a.waiters+=1;let c=!1,u=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),x.get(e)===a&&x.delete(e)))};t.on(`close`,u);try{let{documents:e,truncated:n}=await a.promise;if(c)return;J(t,200,Sn,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,u)}return}let b=c(),w=_(),T=v?.()??new Map,E=[];for(let[e,t]of T)i&&!e.startsWith(`${i}/`)&&e!==i||E.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let ee=[];try{let e=C(b);S?.signature!==e&&(S={signature:e,assets:bV({contentDir:n,fileIndex:b,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:d?e=>d.isPathIgnored(e):void 0})}),ee=S?.assets??[]}catch(e){S=null,l.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let te=new Set;for(let e of ee)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(te.add(e.path),E.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of w){if(t.kind===`markdown`){if(i&&!e.startsWith(`${i}/`)&&e!==i)continue;let r=Kx(e);E.push({kind:`document`,docName:e,docExt:r,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let a of t.aliases){if(i&&!a.startsWith(`${i}/`)&&a!==i)continue;let o=oN(R(n,t.canonicalPath));E.push({kind:`document`,docName:a,docExt:r,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o})}continue}if((!i||e===i||e.startsWith(`${i}/`))&&!te.has(e)){let n=g(e);E.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let r of t.aliases){if(!(!i||r===i||r.startsWith(`${i}/`))||te.has(r))continue;let a=oN(R(n,t.canonicalPath)),o=g(r);E.push({kind:`file`,docName:r,path:r,docExt:`.${o}`,assetExt:o,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}let D=y?.()??new Map;if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[r,i]of t){let t=T.get(r),a=t?oN(R(n,t.canonicalPath)):r;for(let n of i)e(n)&&E.push({kind:`folder`,path:n,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:r,targetPath:a})}let r=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of T)r(e,r=>{E.push({kind:`folder`,path:r,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:oN(R(n,t.canonicalPath))})});for(let[e,t]of w)r(e,r=>{let i=oN(R(n,t.canonicalPath));if(t.kind===`markdown`)E.push({kind:`document`,docName:r,docExt:Kx(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i});else{let n=g(r);E.push({kind:`file`,docName:r,path:r,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}})}E.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),J(t,200,Sn,{documents:E},{handler:`document-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),te=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){K(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!r(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let i=o(n);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!B(i)){K(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}J(t,200,mn,{docName:n,headings:s(V(i,`utf-8`))},{handler:`page-headings`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),D={"/api/document":E,"/api/documents":ee,"/api/pages":q(Zt,async(e,t)=>{try{let e=c(),r=[];for(let[t,i]of e){let e=Kx(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let r=V(z(n,`${t}${e}`),`utf-8`);a=sk(r,t),o=lk(r)}catch(e){l.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}r.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}r.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,Xn,{pages:r},{handler:`pages`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":te};return{paths:Object.keys(D),table:{resolve(e){let t=D[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:w}}var CV=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}};const wV=/^\/[!#$&-;=?-\[\]_a-z~]*$/,TV=/\/\.\.?(?:[/?#]|$)/,EV=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,DV=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!EV.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new CV(`Invalid host header`);return e.href}else if(n.length===0)return r+`/`;else{if(n.charCodeAt(0)!==47)throw new CV(`Invalid URL`);return!wV.test(n)||TV.test(n)?new URL(r).href:r}},OV=e=>e instanceof CV?e:new CV(e.message,{cause:e}),kV=global.Request;var AV=class extends kV{constructor(e,t){if(typeof e==`object`&&UV in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[eH]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[UV]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const jV=e=>{let t=[],n=e.rawHeaders;for(let e=0,r=n.length;e<r;e+=2){let r=n[e];r.charCodeAt(0)!==58&&t.push([r,n[e+1]])}return new Headers(t)},MV=Symbol(`wrapBodyStream`),NV=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),PV=e=>e===null||NV.has(e),FV=Symbol(`bodyBufferedBeforeDisconnect`),IV=Symbol(`bodyBufferedLengthBeforeDisconnect`),LV=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),RV=e=>!(e instanceof ju)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&PV(e.readableEncoding),zV=e=>{if(e.readableDidRead||!RV(e))return;let t=e;t[IV]??=e.readableLength},BV=(e,t)=>{if(e.readableDidRead&&!t||!RV(e))return;let n=e;if(n[FV]!==void 0)return n[FV];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[IV]!==void 0&&e.readableLength!==n[IV])r=rH();else{let n=t??[],i=e.read();i!==null&&n.push(LV(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let o=e.headers[`content-length`];if(typeof o==`string`&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&a.length!==e&&(r=rH())}}return n[FV]=r,r},VV=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},HV=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new AV(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[MV]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=BV(r);if(e!==void 0){VV(t,e);return}}e||=xu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=BV(r);e===void 0?a.body=xu.toWeb(r):a.body=new ReadableStream({start(t){VV(t,e)}})}return new AV(t,a)},UV=Symbol(`getRequestCache`),WV=Symbol(`requestCache`),GV=Symbol(`incomingKey`),KV=Symbol(`urlKey`),qV=Symbol(`methodKey`),JV=Symbol(`headersKey`),YV=Symbol(`abortControllerKey`),XV=Symbol(`getAbortController`),ZV=Symbol(`abortRequest`),QV=Symbol(`bodyBuffer`),$V=Symbol(`bodyReadPromise`),eH=Symbol(`bodyConsumedDirectly`),tH=Symbol(`bodyLockReader`),nH=Symbol(`abortReason`),rH=()=>TypeError(`Body is unusable`),iH=()=>Promise.reject(rH()),aH=new TextDecoder,oH=e=>{if(e[eH])return iH();e[eH]=!0},sH=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),cH=e=>(e[JV]||=jV(e[GV])).get(`content-type`)||``,lH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,uH=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`PATCH`:case`POST`:case`PUT`:case`QUERY`:return e}let t=e.toUpperCase();switch(t){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`:return t;default:return e}},dH=e=>{if(!lH.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},fH=(e,t,n)=>{if(e[eH])return iH();let r=e.method;if(r===`GET`||r===`HEAD`)return e[UV]()[t]();let i=dH(r);if(i)return Promise.reject(i);if(e[WV]&&r!==`TRACE`)return e[WV][t]();let a=oH(e);if(a)return a;let o=pH(e);if(o){let t=Promise.resolve(n(o,e));return e[QV]=void 0,t}return hH(e).then(t=>{let r=n(t,e);return e[QV]=void 0,r})},pH=e=>{let t=e[GV];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},mH=(e,t)=>{if(t.errored)return t.errored;let n=e[nH];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},hH=e=>{if(e[QV])return Promise.resolve(e[QV]);if(e[$V])return e[$V];let t=e[GV];if(t.readableDidRead)return iH();let n=BV(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[QV]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,o=e=>{a||(a=!0,f(),e())},s=a=>{let s=t.errored??a;return!RV(t)||s&&s.code!==`ECONNRESET`?!1:(o(()=>{let o=BV(t,i);o instanceof Error?r(o):o===void 0?r(a??mH(e,t)):(e[QV]=o,n(o))}),!0)},c=e=>{i.push(LV(e,t.readableEncoding))},l=()=>{o(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[QV]=t,n(t)})},u=e=>{s(e)||o(()=>{r(e)})},d=()=>{if(t.readableEnded){l();return}s()||o(()=>{r(mH(e,t))})},f=()=>{t.off(`data`,c),t.off(`end`,l),t.off(`error`,u),t.off(`close`,d),e[$V]=void 0};t.on(`data`,c),t.on(`end`,l),t.on(`error`,u),t.on(`close`,d),queueMicrotask(()=>{a||(t.readableEnded?l():t.errored?u(t.errored):t.destroyed&&d())})});return e[$V]=r,r},gH={get method(){return this[qV]},get url(){return this[KV]},get headers(){return this[JV]||=jV(this[GV])},[ZV](e){this[nH]===void 0&&(this[nH]=e);let t=this[YV];t&&!t.signal.aborted&&t.abort(e)},[XV](){return this[YV]||=new AbortController,this[nH]!==void 0&&!this[YV].signal.aborted&&this[YV].abort(this[nH]),this[YV]},[UV](){let e=this[XV]();if(this[WV])return this[WV];let t=this.method;if(this[eH]&&!(t===`GET`||t===`HEAD`)){this[QV]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new AV(this[KV],n);return t===`TRACE`&&Object.defineProperty(r,`method`,{get(){return`TRACE`}}),this[WV]=r}return this[WV]=HV(this.method,this[KV],this.headers,this[GV],e)},get body(){if(!this[eH])return this[UV]().body;let e=this[UV]();return!this[tH]&&e.body&&(this[tH]=e.body.getReader()),e.body},get bodyUsed(){return this[eH]?!0:this[WV]?this[WV].bodyUsed:!1}};Object.defineProperty(gH,`signal`,{get(){return this[XV]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(gH,e,{get(){return this[UV]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(gH,e,{value:function(){if(this[eH]){if(e===`clone`)throw rH();return iH()}return this[UV]()[e]()}})}),Object.defineProperty(gH,`text`,{value:function(){return fH(this,`text`,e=>aH.decode(e))}}),Object.defineProperty(gH,`arrayBuffer`,{value:function(){return fH(this,`arrayBuffer`,e=>sH(e))}}),Object.defineProperty(gH,`blob`,{value:function(){return fH(this,`blob`,(e,t)=>{let n=cH(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(gH,`json`,{value:function(){return this[eH]?iH():this.text().then(JSON.parse)}}),Object.defineProperty(gH,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[WV]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(gH,AV.prototype);const _H=(e,t)=>{let n=Object.create(gH);n[GV]=e,n[qV]=uH(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof ju)throw new CV(`Absolute URL for :path is not allowed in HTTP/2`);try{n[KV]=new URL(r).href}catch(e){throw new CV(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof ju?e.authority:e.headers.host)||t;if(!i)throw new CV(`Missing host header`);let a;if(e instanceof ju){if(a=e.scheme,!(a===`http`||a===`https`))throw new CV(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[KV]=DV(a,i,r)}catch(e){throw e instanceof CV?e:new CV(`Invalid URL`,{cause:e})}return n},vH=`text/plain; charset=UTF-8`,yH=Symbol(`responseCache`),bH=Symbol(`getResponseCache`),xH=Symbol(`cache`),SH=global.Response;var CH=class e{#e;#t;[bH](){let e=this[xH],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[xH],this[yH]||=new SH(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof SH){let t=n[yH];if(t){this.#t=t,this[bH]();return}this.#t=n instanceof e?n.#t:n,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[xH]=[n?.status||200,t??null,r||n?.headers])}get headers(){let e=this[xH];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":vH}))),e[2]):this[bH]().headers}get status(){return this[xH]?.[0]??this[bH]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(CH.prototype,e,{get(){return this[bH]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(CH.prototype,e,{value:function(){return this[bH]()[e]()}})}),Object.defineProperty(CH.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[yH]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(CH,SH),Object.setPrototypeOf(CH.prototype,SH.prototype);const wH=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,TH=e=>e instanceof URL?e.href:wH.test(e)?e:new URL(e).href,EH=new Set([301,302,303,307,308]);Object.defineProperty(CH,`redirect`,{value:function(e,t=302){if(!EH.has(t))throw RangeError(`Invalid status code`);return new CH(null,{status:t,headers:{location:TH(e)}})},writable:!0,configurable:!0}),Object.defineProperty(CH,`json`,{value:function(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new CH(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function DH(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function OH(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 kH(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:OH(e.getReader(),t)}const AH=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},jH=Symbol(`outgoingEnded`),MH=Symbol(`incomingDraining`),NH=e=>{let t=e;if(e.destroyed||t[MH])return;if(t[MH]=!0,e instanceof ju){try{e.stream?.close?.(ine.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,500);a.unref?.();let o=e=>{n+=e.length,n>67108864&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},PH=(e,t,n,r)=>()=>{t.errored?(zV(t),e[ZV](t.errored.toString())):n.writableFinished||(zV(t),e[ZV](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{NH(t)})})},FH=e=>{if(!(xH in e))return!1;let t=e[xH][1];return t===null||typeof t==`string`||t instanceof Uint8Array},IH=()=>new Response(null,{status:400}),LH=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),RH=(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))},zH=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},BH=async(e,t)=>{let[n,r,i]=e[xH];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":vH,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":vH,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":vH,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":vH}),zH(t),await kH(r,t)?.catch(e=>RH(e,t))),t[jH]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=AH(i,r===null?void 0:vH);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=AH(e,r===null?void 0:vH)}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),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(zH(t),await kH(r,t)?.catch(e=>RH(e,t))),t[jH]?.()},VH=e=>typeof e.then==`function`,HH=async(e,t,n={})=>{if(VH(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(LH);if(xH in e)return BH(e,t);let r=AH(e.headers,e.body===null?void 0:vH);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 DH(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&&zH(t),await OH(n,t,o))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[jH]?.()},UH=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==AV&&(Object.defineProperty(global,`Request`,{value:AV}),Object.defineProperty(global,`Response`,{value:CH})),async(r,i)=>{let a,o,s=!1,c=!1,l=()=>{!o||c||(c=!0,i.on(`close`,PH(o,r,i,s)))};try{if(o=_H(r,t.hostname),s=n&&!(r.method===`GET`||r.method===`HEAD`),s&&(r[MV]=!0,r instanceof ju&&(i[jH]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),i.destroy()})})})),a=e(o,{incoming:r,outgoing:i}),!VH(a)&&FH(a))return s&&!r.readableEnded&&i.once(`finish`,()=>{r.readableEnded||NH(r)}),BH(a,i);l()}catch(e){if(a)return RH(e,i);if(t.errorHandler){if(l(),a=await t.errorHandler(o?e:OV(e)),!a)return}else a=o?LH(e):IH()}try{return await HH(a,i,t)}catch(e){return RH(e,i)}}};globalThis.CloseEvent,globalThis.ErrorEvent;const WH=new Response(null,{headers:{"x-hono-already-sent":`true`}});var GH=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},KH=Symbol(),qH=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),JH=e=>`headers`in e,YH=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(JH(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?XH(e,{all:n,dot:r}):{}};async function XH(e,t){let n=JH(e)?e.headers:e.raw.headers,r=qH(await e.arrayBuffer(),n.get(`Content-Type`)||``);JH(e)||(e.bodyCache.formData=r);let i=await r;return i?ZH(i,t):{}}function ZH(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?QH(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&($H(n,e,t),delete n[e])}),n}var QH=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},$H=(e,t,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},eU=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},tU=e=>{let{groups:t,path:n}=nU(e);return rU(eU(n),t)},nU=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},rU=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},iU={},aU=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return iU[r]||(n[2]?iU[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:iU[r]=[e,n[1],!0]),iU[r]}return null},oU=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},sU=e=>oU(e,decodeURI),cU=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return sU(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}else if(e===63||e===35)break}return t.slice(n,r)},lU=e=>{let t=cU(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},uU=(e,t,...n)=>(n.length&&(t=uU(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),dU=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},fU=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:oU(e,gU)):e,pU=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return fU(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=fU(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=fU(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},mU=pU,hU=(e,t)=>pU(e,t,!0),gU=decodeURIComponent,_U=e=>oU(e,gU),vU=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={}}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#i(t);return n&&/\%/.test(n)?_U(n):n}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?_U(t):t)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return mU(this.url,e)}queries(e){return hU(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return YH(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){this.#e[e]=t}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[KH](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},yU={Stringify:1,BeforeStream:2,Stream:3},bU=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},xU=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>xU(e,t,!1,r,i))).then(()=>i[0]));return n?bU(await o,a):o},SU=`text/plain; charset=UTF-8`,CU=(e,t)=>({"Content-Type":e,...t}),wU=(e,t)=>new Response(e,t),TU=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new vU(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=wU(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=wU(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=wU(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}return wU(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,CU(SU,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,CU(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,CU(`text/html; charset=UTF-8`,n));return typeof e==`object`?xU(e,yU.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>wU(),this.#c(this))},EU=[`get`,`post`,`put`,`delete`,`options`,`patch`],DU=`Can not add a route since the matcher is already built.`,OU=class extends Error{},kU=`__COMPOSED_HANDLER`,AU=e=>e.text(`404 Not Found`,404),jU=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},MU=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...EU,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??cU:lU}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=AU;errorHandler=jU;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===jU?r=e.handler:(r=async(n,r)=>(await GH([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[kU]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=uU(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=uU(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,uU(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=uU(this._basePath,t);let i={basePath:r===void 0?this._basePath:uU(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new TU(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=GH(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${uU(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},NU=[];function PU(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],NU];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var FU=`[^/]+`,IU=`.*`,LU=`(?:|/.*)`,RU=Symbol(),zU=new Set(`.\\+*[^]$()`);function BU(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===IU||e===LU?1:t===IU||t===LU?-1:e===FU?1:t===FU?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var VU=class e{#e;#t;#n=Object.create(null);insert(t,n,r,i,a){if(t.length===0){if(this.#e!==void 0)throw RU;if(a)return;this.#e=n;return}let[o,...s]=t,c=o===`*`?s.length===0?[``,``,IU]:[``,``,FU]:o===`/*`?[``,``,LU]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||FU;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))))throw RU;if(l=this.#n[n],!l){if(Object.keys(this.#n).some(e=>e!==IU&&e!==LU))throw RU;if(a)return;l=this.#n[n]=new e,t!==``&&(l.#t=i.varIndex++)}!a&&t!==``&&r.push([t,l.#t])}else if(l=this.#n[o],!l){if(Object.keys(this.#n).some(e=>e.length>1&&e!==IU&&e!==LU))throw RU;if(a)return;l=this.#n[o]=new e}l.insert(s,n,r,i,a)}buildRegExpStr(){let e=Object.keys(this.#n).sort(BU).map(e=>{let t=this.#n[e];return(typeof t.#t==`number`?`(${e})@${t.#t}`:zU.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#e==`number`&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},HU=class{#e={varIndex:0};#t=new VU;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#t.insert(a,t,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},UU=[/^$/,[],Object.create(null)],WU=Object.create(null);function GU(e){return WU[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function KU(){WU=Object.create(null)}function qU(e){let t=new HU,n=[];if(e.length===0)return UU;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),NU]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===RU?new OU(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function JU(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(GU(n).test(t))return[...e[n]]}}var YU=class{name=`RegExpRouter`;#e;#t;constructor(){this.#e={ALL:Object.create(null)},this.#t={ALL:Object.create(null)}}add(e,t,n){let r=this.#e,i=this.#t;if(!r||!i)throw Error(DU);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t.ALL).forEach(n=>{t[e][n]=[...t.ALL[n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=GU(t);e===`ALL`?Object.keys(r).forEach(e=>{r[e][t]||=JU(r[e],t)||JU(r.ALL,t)||[]}):r[e][t]||=JU(r[e],t)||JU(r.ALL,t)||[],Object.keys(r).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=dU(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===`ALL`||e===o)&&(i[o][c]||=[...JU(r[o],c)||JU(r.ALL,c)||[]],i[o][c].push([n,a-s+t+1]))})}}match=PU;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t)}),this.#e=this.#t=void 0,KU(),e}#n(e){let t=[],n=e===`ALL`;return[this.#e,this.#t].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==`ALL`&&t.push(...Object.keys(r.ALL).map(e=>[e,r.ALL[e]])):(n||=!0,t.push(...i))}),n?qU(t):null}},XU=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(DU);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof OU)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},ZU=Object.create(null),QU=e=>{for(let t in e)return!0;return!1},$U=class e{#e;#t;#n;#r=0;#i=ZU;constructor(e,t,n){if(this.#t=n||Object.create(null),this.#e=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#e=[n]}this.#n=[]}insert(t,n,r){this.#r=++this.#r;let i=this,a=tU(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=aU(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#t){i=i.#t[c],s&&o.push(s[1]);continue}i.#t[c]=new e,s&&(i.#n.push(s),o.push(s[1])),i=i.#t[c]}return i.#e.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#r}}),i}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL,c={};if(s!==void 0&&(s.params=Object.create(null),e.push(s),r!==ZU||i&&i!==ZU))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],n=c[s.score];s.params[t]=i?.[t]&&!n?i[t]:r[t]??i?.[t],c[s.score]=!0}}}search(e,t){let n=[];this.#i=ZU;let r=[this],i=eU(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r=0,f=p.#n.length;r<f;r++){let f=p.#n[r],m=p.#i===ZU?{}:{...p.#i};if(f===`*`){let t=p.#t[`*`];t&&(this.#a(n,t,e,p.#i),t.#i=m,d.push(t));continue}let[h,g,_]=f;if(!l&&!(_ instanceof RegExp))continue;let v=p.#t[h];if(_ instanceof RegExp){if(s===null){s=Array(o);let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let r=t.substring(s[c]),l=_.exec(r);if(l){if(m[g]=l[0],this.#a(n,v,e,p.#i,m),l[0].length===r.length&&v.#t[`*`]&&this.#a(n,v.#t[`*`],e,p.#i,m),QU(v.#t)){v.#i=m;let e=l[0].match(/\//)?.length??0;(a[e]||=[]).push(v)}continue}}(_===!0||_.test(l))&&(m[g]=l,u?(this.#a(n,v,e,m,p.#i),v.#t[`*`]&&this.#a(n,v.#t[`*`],e,m,p.#i)):(v.#i=m,d.push(v)))}}let f=a.shift();r=f?d.concat(f):d}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},eW=class{name=`TrieRouter`;#e;constructor(){this.#e=new $U}add(e,t,n){let r=dU(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#e.insert(e,r[t],n);return}this.#e.insert(e,t,n)}match(e,t){return this.#e.search(e,t)}},tW=class extends MU{constructor(e={}){super(e),this.router=e.router??new XU({routers:[new YU,new eW]})}};function nW(e,t,n,r){if(ZB(e,n))return K(t,403,`urn:ok:error:host-not-allowed`,"Proxied request refused: this server has not consented to external exposure. Set OK_PUBLIC_URL to the public origin and OK_ALLOW_EXTERNAL=1 (or server.publicUrl + server.allowExternal in config), or restart with `ok start --remote <url>`.",{handler:r}),!1;if(n.allowExternal){let i=Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host;if(!qB(e.socket.remoteAddress,n)||!YB(i,n))return K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:r}),!1}return!0}function rW(e,t){let n=e.filter(e=>!e.includes(`*`)&&e in t),r=e.filter(e=>e.endsWith(`/*`)).map(e=>e.slice(0,-1)),i=Object.keys(t).filter(e=>r.some(t=>e.startsWith(t))).map(e=>`${e} (under a native wildcard)`),a=[...n,...i];if(a.length>0)throw Error(`route(s) present in both the legacy dispatch record and a native route group: ${a.join(`, `)}`);let o=new Set,s=[];for(let t of e)o.has(t)&&s.push(t),o.add(t);let c=e.filter(e=>r.some(t=>e!==`${t}*`&&e.startsWith(t))).map(e=>`${e} (under a native wildcard)`),l=[...new Set([...s,...c])];if(l.length>0)throw Error(`route(s) claimed by more than one native route group: ${l.join(`, `)}`)}function iW(e,t,n,r){if(t.method!==`GET`&&t.method!==`HEAD`){K(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`health`,extraHeaders:{Allow:`GET, HEAD`}});return}let i={"Cache-Control":`no-store`,"X-Content-Type-Options":`nosniff`};if(e===`/healthz`){n.writeHead(200,{...i,"Content-Type":`text/plain; charset=utf-8`}),n.end(`ok`);return}let a=r?.readiness()??`ready`,o=a===`ready`;n.writeHead(o?200:503,{...i,"Content-Type":`application/json`}),n.end(JSON.stringify({ready:o,status:a,degraded:o?r?.degraded()??[]:[]}))}function aW(e){let t=new tW;t.onError((t,n)=>{let r=n.env.outgoing;return e.log.error({err:t},`Unhandled router handler error`),!r.headersSent&&!r.writableEnded&&!r.destroyed?K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`http-app`,cause:t}):r.writableEnded||r.end(),WH});for(let n of[`/healthz`,`/readyz`])t.all(n,t=>(iW(n,t.env.incoming,t.env.outgoing,e.health),WH));let n=e.ingressPolicy??KB({}),r=e.nativeApi;if(r!==void 0)for(let i of r.paths)t.all(i,async t=>{let i=t.env.incoming,a=t.env.outgoing;if(!nW(i,a,n,`native-api-surface`))return WH;try{await r.dispatch(i,a)||e.legacyDispatch(i,a)}catch(t){e.log.error({err:t},`Unhandled onRequest error`),!a.writableEnded&&!a.headersSent?K(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`native-api-catch`,cause:t}):a.writableEnded||a.end()}return WH});return t.all(`*`,t=>(e.legacyDispatch(t.env.incoming,t.env.outgoing),WH)),{requestListener:UH(t.fetch,{overrideGlobalObjects:!1,autoCleanupIncoming:!1})}}const oW=F(`suggest-links`),sW=/[\p{L}\p{N}]/u;var cW=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function lW(e){return e.replace(/\s+/g,` `).trim()}function uW(e,t,n){if(!lW(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
102
+ `)}function w(){S=null}b?.(w);function T(e){let t=e.getMap(`lifecycle`),n=t.get(`status`);if(typeof n!=`string`||n.length===0)return null;let r=t.get(`reason`);return{status:n,reason:typeof r==`string`?r:``}}let E=q(Zt,async(e,o)=>{try{let s=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!r(s)){K(o,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let c=i(s);if(Zx(c)||Qx(c)){K(o,400,`urn:ok:error:reserved-doc-name`,`'${c}' is a reserved document name.`,{handler:`document-read`});return}let l=t.documents.get(c);if(l){J(o,200,Pn,{docName:c,content:l.getText(`source`).toString(),lifecycle:T(l)},{handler:`document-read`});return}if(!B(a(n,`file`,c))){K(o,404,`urn:ok:error:doc-not-found`,`Document not found: ${c}.`,{handler:`document-read`});return}let u=await t.openDirectConnection(c);try{let e=u.document;if(!e){K(o,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}J(o,200,Pn,{docName:c,content:e.getText(`source`).toString(),lifecycle:T(e)},{handler:`document-read`})}finally{await u.disconnect()}}catch(e){K(o,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),ee=q(Zt,async(e,t)=>{try{u&&await u.catch(e=>{l.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`dir`),a=r.searchParams.get(`showAll`)===`true`,o=r.searchParams.get(`showOk`)===`true`,s=r.searchParams.get(`depth`)===`1`?1:1/0;if(i)try{f(n,i)}catch{K(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(a&&d&&xV(e)){let e=new AbortController;t.on(`close`,()=>{t.writableEnded||e.abort()}),t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let r=pS(t,`document-list`),a=async e=>{t.writableEnded||t.destroyed||t.write(e)||await new Promise(e=>{let n=()=>{t.off(`drain`,n),t.off(`close`,n),e()};t.once(`drain`,n),t.once(`close`,n)})};try{let t=p(),r=m({contentDir:n,contentFilter:d,dirFilter:i,maxEntries:t,maxDepth:s,showOk:o,signal:e.signal}),c=0,u=await r.next();for(;!u.done;)await a(`${JSON.stringify(u.value)}\n`),c+=1,u=await r.next();let{truncated:f}=u.value;f&&l.info({handler:`document-list`,maxEntries:t,count:c},`[document-list][showAll] stream truncated at entry cap`),await a(`${JSON.stringify({type:`complete`,truncated:f,count:c})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?r(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):l.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(a&&d){let e=`showAll:${s===1?`d1:`:``}${o?`ok:`:``}${i??``}`,r=x.get(e);if(!r){let t=new AbortController,a=(async()=>{let e=[],r=p(),{truncated:a}=await h({contentDir:n,contentFilter:d,dirFilter:i,documents:e,maxEntries:r,maxDepth:s,showOk:o,signal:t.signal});return e.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),a&&l.info({handler:`document-list`,maxEntries:r,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:a}})();r={promise:a,controller:t,waiters:0};let c=r;x.set(e,c),a.finally(()=>{x.get(e)===c&&x.delete(e)})}let a=r;a.waiters+=1;let c=!1,u=()=>{t.writableEnded||c||(c=!0,--a.waiters,a.waiters<=0&&(a.controller.abort(),x.get(e)===a&&x.delete(e)))};t.on(`close`,u);try{let{documents:e,truncated:n}=await a.promise;if(c)return;J(t,200,Sn,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(c)return;K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,u)}return}let b=c(),w=_(),T=v?.()??new Map,E=[];for(let[e,t]of T)i&&!e.startsWith(`${i}/`)&&e!==i||E.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let ee=[];try{let e=C(b);S?.signature!==e&&(S={signature:e,assets:bV({contentDir:n,fileIndex:b,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:d?e=>d.isPathIgnored(e):void 0})}),ee=S?.assets??[]}catch(e){S=null,l.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let te=new Set;for(let e of ee)i&&!e.path.startsWith(`${i}/`)&&e.path!==i||(te.add(e.path),E.push({kind:`asset`,docName:e.path,docExt:e.assetExt,path:e.path,assetExt:e.assetExt,mediaKind:e.mediaKind,referencedBy:e.referencedBy,size:e.size,modified:e.modified,isSymlink:!1,canonicalDocName:null,targetPath:null}));for(let[e,t]of w){if(t.kind===`markdown`){if(i&&!e.startsWith(`${i}/`)&&e!==i)continue;let r=Kx(e);E.push({kind:`document`,docName:e,docExt:r,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let a of t.aliases){if(i&&!a.startsWith(`${i}/`)&&a!==i)continue;let o=oN(R(n,t.canonicalPath));E.push({kind:`document`,docName:a,docExt:r,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:o})}continue}if((!i||e===i||e.startsWith(`${i}/`))&&!te.has(e)){let n=g(e);E.push({kind:`file`,docName:e,path:e,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null})}for(let r of t.aliases){if(!(!i||r===i||r.startsWith(`${i}/`))||te.has(r))continue;let a=oN(R(n,t.canonicalPath)),o=g(r);E.push({kind:`file`,docName:r,path:r,docExt:`.${o}`,assetExt:o,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}}let D=y?.()??new Map;if(D.size>0){let e=e=>!i||e===i||e.startsWith(`${i}/`),t=new Map;for(let[e,n]of D){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[r,i]of t){let t=T.get(r),a=t?oN(R(n,t.canonicalPath)):r;for(let n of i)e(n)&&E.push({kind:`folder`,path:n,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:r,targetPath:a})}let r=(n,r)=>{for(let i=n.indexOf(`/`);i!==-1;i=n.indexOf(`/`,i+1)){let a=t.get(n.slice(0,i));if(!a)continue;let o=n.slice(i);for(let t of a){let n=`${t}${o}`;e(n)&&r(n)}}};for(let[e,t]of T)r(e,r=>{E.push({kind:`folder`,path:r,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:oN(R(n,t.canonicalPath))})});for(let[e,t]of w)r(e,r=>{let i=oN(R(n,t.canonicalPath));if(t.kind===`markdown`)E.push({kind:`document`,docName:r,docExt:Kx(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i});else{let n=g(r);E.push({kind:`file`,docName:r,path:r,docExt:`.${n}`,assetExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}})}E.sort((e,t)=>{let n=e.kind===`folder`?e.path??``:e.docName??e.path??``,r=t.kind===`folder`?t.path??``:t.docName??t.path??``;return n.localeCompare(r)}),J(t,200,Sn,{documents:E},{handler:`document-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),te=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){K(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!r(n)){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let i=o(n);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!B(i)){K(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}J(t,200,mn,{docName:n,headings:s(V(i,`utf-8`))},{handler:`page-headings`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),D={"/api/document":E,"/api/documents":ee,"/api/pages":q(Zt,async(e,t)=>{try{let e=c(),r=[];for(let[t,i]of e){let e=Kx(t),a,o;if(i.title!==void 0)a=i.title,o=i.icon;else{a=t;try{let r=V(z(n,`${t}${e}`),`utf-8`);a=sk(r,t),o=lk(r)}catch(e){l.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}r.push({docName:t,title:a,docExt:e,size:i.size,modified:i.modified,icon:o})}r.sort((e,t)=>e.docName.localeCompare(t.docName)),J(t,200,Xn,{pages:r},{handler:`pages`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),"/api/page-headings":te};return{paths:Object.keys(D),table:{resolve(e){let t=D[e];return t?{template:e,dispatch:(e,n)=>t(e,n)}:null},isMutating:()=>!1},invalidateReferencedAssetsCache:w}}var CV=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}};const wV=/^\/[!#$&-;=?-\[\]_a-z~]*$/,TV=/\/\.\.?(?:[/?#]|$)/,EV=/^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/,DV=(e,t,n)=>{let r=`${e}://${t}${n}`;if(!EV.test(t)){let e=new URL(r);if(e.hostname.length!==t.length&&e.hostname!==(t.includes(`:`)?t.replace(/:\d+$/,``):t).toLowerCase())throw new CV(`Invalid host header`);return e.href}else if(n.length===0)return r+`/`;else{if(n.charCodeAt(0)!==47)throw new CV(`Invalid URL`);return!wV.test(n)||TV.test(n)?new URL(r).href:r}},OV=e=>e instanceof CV?e:new CV(e.message,{cause:e}),kV=global.Request;var AV=class extends kV{constructor(e,t){if(typeof e==`object`&&UV in e){let n=t!==void 0&&`body`in t&&t.body!=null;if(e[eH]&&!n)throw TypeError(`Cannot construct a Request with a Request object that has already been used.`);e=e[UV]()}t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}};const jV=e=>{let t=[],n=e.rawHeaders;for(let e=0,r=n.length;e<r;e+=2){let r=n[e];r.charCodeAt(0)!==58&&t.push([r,n[e+1]])}return new Headers(t)},MV=Symbol(`wrapBodyStream`),NV=new Set([`latin1`,`binary`,`hex`,`base64`,`base64url`]),PV=e=>e===null||NV.has(e),FV=Symbol(`bodyBufferedBeforeDisconnect`),IV=Symbol(`bodyBufferedLengthBeforeDisconnect`),LV=(e,t)=>Buffer.isBuffer(e)?e:Buffer.from(e,t??`utf8`),RV=e=>!(e instanceof ju)&&!!e.complete&&!!e.readableAborted&&typeof e.read==`function`&&PV(e.readableEncoding),zV=e=>{if(e.readableDidRead||!RV(e))return;let t=e;t[IV]??=e.readableLength},BV=(e,t)=>{if(e.readableDidRead&&!t||!RV(e))return;let n=e;if(n[FV]!==void 0)return n[FV];let r,i=e.errored;if(i&&i.code!==`ECONNRESET`)r=i;else if(n[IV]!==void 0&&e.readableLength!==n[IV])r=rH();else{let n=t??[],i=e.read();i!==null&&n.push(LV(i,e.readableEncoding));let a=n.length===1?n[0]:Buffer.concat(n);r=a;let o=e.headers[`content-length`];if(typeof o==`string`&&/^\d+$/.test(o)){let e=Number(o);Number.isSafeInteger(e)&&a.length!==e&&(r=rH())}}return n[FV]=r,r},VV=(e,t)=>{if(t instanceof Error){e.error(t);return}t.length>0&&e.enqueue(t),e.close()},HV=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new AV(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[MV]){let e;a.body=new ReadableStream({async pull(t){try{if(!e){let e=BV(r);if(e!==void 0){VV(t,e);return}}e||=xu.toWeb(r).getReader();let{done:n,value:i}=await e.read();n?t.close():t.enqueue(i)}catch(e){t.error(e)}}})}else{let e=BV(r);e===void 0?a.body=xu.toWeb(r):a.body=new ReadableStream({start(t){VV(t,e)}})}return new AV(t,a)},UV=Symbol(`getRequestCache`),WV=Symbol(`requestCache`),GV=Symbol(`incomingKey`),KV=Symbol(`urlKey`),qV=Symbol(`methodKey`),JV=Symbol(`headersKey`),YV=Symbol(`abortControllerKey`),XV=Symbol(`getAbortController`),ZV=Symbol(`abortRequest`),QV=Symbol(`bodyBuffer`),$V=Symbol(`bodyReadPromise`),eH=Symbol(`bodyConsumedDirectly`),tH=Symbol(`bodyLockReader`),nH=Symbol(`abortReason`),rH=()=>TypeError(`Body is unusable`),iH=()=>Promise.reject(rH()),aH=new TextDecoder,oH=e=>{if(e[eH])return iH();e[eH]=!0},sH=e=>e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),cH=e=>(e[JV]||=jV(e[GV])).get(`content-type`)||``,lH=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,uH=e=>{if(typeof e!=`string`||e.length===0)return`GET`;switch(e){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`PATCH`:case`POST`:case`PUT`:case`QUERY`:return e}let t=e.toUpperCase();switch(t){case`DELETE`:case`GET`:case`HEAD`:case`OPTIONS`:case`POST`:case`PUT`:return t;default:return e}},dH=e=>{if(!lH.test(e))return TypeError(`'${e}' is not a valid HTTP method.`);let t=e.toUpperCase();if(t===`CONNECT`||t===`TRACK`||t===`TRACE`&&e!==`TRACE`)return TypeError(`'${e}' HTTP method is unsupported.`)},fH=(e,t,n)=>{if(e[eH])return iH();let r=e.method;if(r===`GET`||r===`HEAD`)return e[UV]()[t]();let i=dH(r);if(i)return Promise.reject(i);if(e[WV]&&r!==`TRACE`)return e[WV][t]();let a=oH(e);if(a)return a;let o=pH(e);if(o){let t=Promise.resolve(n(o,e));return e[QV]=void 0,t}return hH(e).then(t=>{let r=n(t,e);return e[QV]=void 0,r})},pH=e=>{let t=e[GV];if(`rawBody`in t&&t.rawBody instanceof Buffer)return t.rawBody},mH=(e,t)=>{if(t.errored)return t.errored;let n=e[nH];return n===void 0?Error(`Client connection prematurely closed.`):n instanceof Error?n:Error(String(n))},hH=e=>{if(e[QV])return Promise.resolve(e[QV]);if(e[$V])return e[$V];let t=e[GV];if(t.readableDidRead)return iH();let n=BV(t);if(n!==void 0)return n instanceof Error?Promise.reject(n):(e[QV]=n,Promise.resolve(n));let r=new Promise((n,r)=>{let i=[],a=!1,o=e=>{a||(a=!0,f(),e())},s=a=>{let s=t.errored??a;return!RV(t)||s&&s.code!==`ECONNRESET`?!1:(o(()=>{let o=BV(t,i);o instanceof Error?r(o):o===void 0?r(a??mH(e,t)):(e[QV]=o,n(o))}),!0)},c=e=>{i.push(LV(e,t.readableEncoding))},l=()=>{o(()=>{let t=i.length===1?i[0]:Buffer.concat(i);e[QV]=t,n(t)})},u=e=>{s(e)||o(()=>{r(e)})},d=()=>{if(t.readableEnded){l();return}s()||o(()=>{r(mH(e,t))})},f=()=>{t.off(`data`,c),t.off(`end`,l),t.off(`error`,u),t.off(`close`,d),e[$V]=void 0};t.on(`data`,c),t.on(`end`,l),t.on(`error`,u),t.on(`close`,d),queueMicrotask(()=>{a||(t.readableEnded?l():t.errored?u(t.errored):t.destroyed&&d())})});return e[$V]=r,r},gH={get method(){return this[qV]},get url(){return this[KV]},get headers(){return this[JV]||=jV(this[GV])},[ZV](e){this[nH]===void 0&&(this[nH]=e);let t=this[YV];t&&!t.signal.aborted&&t.abort(e)},[XV](){return this[YV]||=new AbortController,this[nH]!==void 0&&!this[YV].signal.aborted&&this[YV].abort(this[nH]),this[YV]},[UV](){let e=this[XV]();if(this[WV])return this[WV];let t=this.method;if(this[eH]&&!(t===`GET`||t===`HEAD`)){this[QV]=void 0;let n={method:t===`TRACE`?`GET`:t,headers:this.headers,signal:e.signal};t!==`TRACE`&&(n.body=new ReadableStream({start(e){e.close()}}),n.duplex=`half`);let r=new AV(this[KV],n);return t===`TRACE`&&Object.defineProperty(r,`method`,{get(){return`TRACE`}}),this[WV]=r}return this[WV]=HV(this.method,this[KV],this.headers,this[GV],e)},get body(){if(!this[eH])return this[UV]().body;let e=this[UV]();return!this[tH]&&e.body&&(this[tH]=e.body.getReader()),e.body},get bodyUsed(){return this[eH]?!0:this[WV]?this[WV].bodyUsed:!1}};Object.defineProperty(gH,`signal`,{get(){return this[XV]().signal}}),[`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`keepalive`].forEach(e=>{Object.defineProperty(gH,e,{get(){return this[UV]()[e]}})}),[`clone`,`formData`].forEach(e=>{Object.defineProperty(gH,e,{value:function(){if(this[eH]){if(e===`clone`)throw rH();return iH()}return this[UV]()[e]()}})}),Object.defineProperty(gH,`text`,{value:function(){return fH(this,`text`,e=>aH.decode(e))}}),Object.defineProperty(gH,`arrayBuffer`,{value:function(){return fH(this,`arrayBuffer`,e=>sH(e))}}),Object.defineProperty(gH,`blob`,{value:function(){return fH(this,`blob`,(e,t)=>{let n=cH(t);return new Response(e,n?{headers:{"content-type":n}}:void 0).blob()})}}),Object.defineProperty(gH,`json`,{value:function(){return this[eH]?iH():this.text().then(JSON.parse)}}),Object.defineProperty(gH,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[WV]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(gH,AV.prototype);const _H=(e,t)=>{let n=Object.create(gH);n[GV]=e,n[qV]=uH(e.method);let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof ju)throw new CV(`Absolute URL for :path is not allowed in HTTP/2`);try{n[KV]=new URL(r).href}catch(e){throw new CV(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof ju?e.authority:e.headers.host)||t;if(!i)throw new CV(`Missing host header`);let a;if(e instanceof ju){if(a=e.scheme,!(a===`http`||a===`https`))throw new CV(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;try{n[KV]=DV(a,i,r)}catch(e){throw e instanceof CV?e:new CV(`Invalid URL`,{cause:e})}return n},vH=`text/plain; charset=UTF-8`,yH=Symbol(`responseCache`),bH=Symbol(`getResponseCache`),xH=Symbol(`cache`),SH=global.Response;var CH=class e{#e;#t;[bH](){let e=this[xH],t=e&&e[2]instanceof Headers?e[2]:void 0;return delete this[xH],this[yH]||=new SH(this.#e,t?{status:this.#t?.status,statusText:this.#t?.statusText,headers:t}:this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof SH){let t=n[yH];if(t){this.#t=t,this[bH]();return}this.#t=n instanceof e?n.#t:n,r=new Headers(n.headers)}else this.#t=n;(t==null||typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[xH]=[n?.status||200,t??null,r||n?.headers])}get headers(){let e=this[xH];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||(e[1]===null?void 0:{"content-type":vH}))),e[2]):this[bH]().headers}get status(){return this[xH]?.[0]??this[bH]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(CH.prototype,e,{get(){return this[bH]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(CH.prototype,e,{value:function(){return this[bH]()[e]()}})}),Object.defineProperty(CH.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[yH]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(CH,SH),Object.setPrototypeOf(CH.prototype,SH.prototype);const wH=/^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/,TH=e=>e instanceof URL?e.href:wH.test(e)?e:new URL(e).href,EH=new Set([301,302,303,307,308]);Object.defineProperty(CH,`redirect`,{value:function(e,t=302){if(!EH.has(t))throw RangeError(`Invalid status code`);return new CH(null,{status:t,headers:{location:TH(e)}})},writable:!0,configurable:!0}),Object.defineProperty(CH,`json`,{value:function(e,t){let n=JSON.stringify(e);if(n===void 0)throw TypeError(`The data is not JSON serializable`);let r=t?.headers,i;return r?(i=new Headers(r),i.has(`content-type`)||i.set(`content-type`,`application/json`)):i={"content-type":`application/json`},new CH(n,{status:t?.status??200,statusText:t?.statusText,headers:i})},writable:!0,configurable:!0});async function DH(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function OH(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 kH(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:OH(e.getReader(),t)}const AH=(e,t)=>{let n={};if(e instanceof Headers||(e=new Headers(e??void 0)),e.has(`set-cookie`)){let t=[];for(let[r,i]of e)r===`set-cookie`?t.push(i):n[r]=i;t.length>0&&(n[`set-cookie`]=t)}else for(let[t,r]of e)n[t]=r;return t&&(n[`content-type`]??=t),n},jH=Symbol(`outgoingEnded`),MH=Symbol(`incomingDraining`),NH=e=>{let t=e;if(e.destroyed||t[MH])return;if(t[MH]=!0,e instanceof ju){try{e.stream?.close?.(ine.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,500);a.unref?.();let o=e=>{n+=e.length,n>67108864&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},PH=(e,t,n,r)=>()=>{t.errored?(zV(t),e[ZV](t.errored.toString())):n.writableFinished||(zV(t),e[ZV](`Client connection prematurely closed.`)),r&&!t.readableEnded&&setTimeout(()=>{t.readableEnded||setTimeout(()=>{NH(t)})})},FH=e=>{if(!(xH in e))return!1;let t=e[xH][1];return t===null||typeof t==`string`||t instanceof Uint8Array},IH=()=>new Response(null,{status:400}),LH=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),RH=(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))},zH=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},BH=async(e,t)=>{let[n,r,i]=e[xH];if(!i){r===null?(t.writeHead(n),t.end()):typeof r==`string`?(t.writeHead(n,{"Content-Type":vH,"Content-Length":Buffer.byteLength(r)}),t.end(r)):r instanceof Uint8Array?(t.writeHead(n,{"Content-Type":vH,"Content-Length":r.byteLength}),t.end(r)):r instanceof Blob?(t.writeHead(n,{"Content-Type":vH,"Content-Length":r.size}),t.end(new Uint8Array(await r.arrayBuffer()))):(t.writeHead(n,{"Content-Type":vH}),zH(t),await kH(r,t)?.catch(e=>RH(e,t))),t[jH]?.();return}let a=!1;if(i instanceof Headers)a=i.has(`content-length`),i=AH(i,r===null?void 0:vH);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=AH(e,r===null?void 0:vH)}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),r==null?t.end():typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(zH(t),await kH(r,t)?.catch(e=>RH(e,t))),t[jH]?.()},VH=e=>typeof e.then==`function`,HH=async(e,t,n={})=>{if(VH(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(LH);if(xH in e)return BH(e,t);let r=AH(e.headers,e.body===null?void 0:vH);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 DH(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&&zH(t),await OH(n,t,o))}else r[`x-hono-already-sent`]||(t.writeHead(e.status,r),t.end());t[jH]?.()},UH=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==AV&&(Object.defineProperty(global,`Request`,{value:AV}),Object.defineProperty(global,`Response`,{value:CH})),async(r,i)=>{let a,o,s=!1,c=!1,l=()=>{!o||c||(c=!0,i.on(`close`,PH(o,r,i,s)))};try{if(o=_H(r,t.hostname),s=n&&!(r.method===`GET`||r.method===`HEAD`),s&&(r[MV]=!0,r instanceof ju&&(i[jH]=()=>{r.readableEnded||setTimeout(()=>{r.readableEnded||setTimeout(()=>{r.destroy(),i.destroy()})})})),a=e(o,{incoming:r,outgoing:i}),!VH(a)&&FH(a))return s&&!r.readableEnded&&i.once(`finish`,()=>{r.readableEnded||NH(r)}),BH(a,i);l()}catch(e){if(a)return RH(e,i);if(t.errorHandler){if(l(),a=await t.errorHandler(o?e:OV(e)),!a)return}else a=o?LH(e):IH()}try{return await HH(a,i,t)}catch(e){return RH(e,i)}}};globalThis.CloseEvent,globalThis.ErrorEvent;const WH=new Response(null,{headers:{"x-hono-already-sent":`true`}});var GH=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},KH=Symbol(),qH=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,e=>e.toLowerCase())}}).formData(),JH=e=>`headers`in e,YH=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=(JH(e)?e.headers:e.raw.headers).get(`Content-Type`)?.split(`;`)[0].trim().toLowerCase();return i===`multipart/form-data`||i===`application/x-www-form-urlencoded`?XH(e,{all:n,dot:r}):{}};async function XH(e,t){let n=JH(e)?e.headers:e.raw.headers,r=qH(await e.arrayBuffer(),n.get(`Content-Type`)||``);JH(e)||(e.bodyCache.formData=r);let i=await r;return i?ZH(i,t):{}}function ZH(e,t){let n=Object.create(null);return e.forEach((e,r)=>{t.all||r.endsWith(`[]`)?QH(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{e.includes(`.`)&&($H(n,e,t),delete n[e])}),n}var QH=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},$H=(e,t,n)=>{if(/(?:^|\.)__proto__\./.test(t))return;let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},eU=e=>{let t=e.split(`/`);return t[0]===``&&t.shift(),t},tU=e=>{let{groups:t,path:n}=nU(e);return rU(eU(n),t)},nU=e=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(e,n)=>{let r=`@${n}`;return t.push([r,e]),r}),{groups:t,path:e}},rU=(e,t)=>{for(let n=t.length-1;n>=0;n--){let[r]=t[n];for(let i=e.length-1;i>=0;i--)if(e[i].includes(r)){e[i]=e[i].replace(r,t[n][1]);break}}return e},iU={},aU=(e,t)=>{if(e===`*`)return`*`;let n=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(n){let r=`${e}#${t}`;return iU[r]||(n[2]?iU[r]=t&&t[0]!==`:`&&t[0]!==`*`?[r,n[1],RegExp(`^${n[2]}(?=/${t})`)]:[e,n[1],RegExp(`^${n[2]}$`)]:iU[r]=[e,n[1],!0]),iU[r]}return null},oU=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,e=>{try{return t(e)}catch{return e}})}},sU=e=>oU(e,decodeURI),cU=e=>{let t=e.url,n=t.indexOf(`/`,t.indexOf(`:`)+4),r=n;for(;r<t.length;r++){let e=t.charCodeAt(r);if(e===37){let e=t.indexOf(`?`,r),i=t.indexOf(`#`,r),a=e===-1?i===-1?void 0:i:i===-1?e:Math.min(e,i),o=t.slice(n,a);return sU(o.includes(`%25`)?o.replace(/%25/g,`%2525`):o)}else if(e===63||e===35)break}return t.slice(n,r)},lU=e=>{let t=cU(e);return t.length>1&&t.at(-1)===`/`?t.slice(0,-1):t},uU=(e,t,...n)=>(n.length&&(t=uU(t,...n)),`${e?.[0]===`/`?``:`/`}${e}${t===`/`?``:`${e?.at(-1)===`/`?``:`/`}${t?.[0]===`/`?t.slice(1):t}`}`),dU=e=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(`:`))return null;let t=e.split(`/`),n=[],r=``;return t.forEach(e=>{if(e!==``&&!/\:/.test(e))r+=`/`+e;else if(/\:/.test(e))if(/\?/.test(e)){n.length===0&&r===``?n.push(`/`):n.push(r);let t=e.replace(`?`,``);r+=`/`+t,n.push(r)}else r+=`/`+e}),n.filter((e,t,n)=>n.indexOf(e)===t)},fU=e=>/[%+]/.test(e)?(e.indexOf(`+`)!==-1&&(e=e.replace(/\+/g,` `)),e.indexOf(`%`)===-1?e:oU(e,gU)):e,pU=(e,t,n)=>{let r;if(!n&&t&&!/[%+]/.test(t)){let n=e.indexOf(`?`,8);if(n===-1)return;for(e.startsWith(t,n+1)||(n=e.indexOf(`&${t}`,n+1));n!==-1;){let r=e.charCodeAt(n+t.length+1);if(r===61){let r=n+t.length+2,i=e.indexOf(`&`,r);return fU(e.slice(r,i===-1?void 0:i))}else if(r==38||isNaN(r))return``;n=e.indexOf(`&${t}`,n+1)}if(r=/[%+]/.test(e),!r)return}let i={};r??=/[%+]/.test(e);let a=e.indexOf(`?`,8);for(;a!==-1;){let t=e.indexOf(`&`,a+1),o=e.indexOf(`=`,a);o>t&&t!==-1&&(o=-1);let s=e.slice(a+1,o===-1?t===-1?void 0:t:o);if(r&&(s=fU(s)),a=t,s===``)continue;let c;o===-1?c=``:(c=e.slice(o+1,t===-1?void 0:t),r&&(c=fU(c))),n?(i[s]&&Array.isArray(i[s])||(i[s]=[]),i[s].push(c)):i[s]??=c}return t?i[t]:i},mU=pU,hU=(e,t)=>pU(e,t,!0),gU=decodeURIComponent,_U=e=>oU(e,gU),vU=class{raw;#e;#t;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#t=n,this.#e={}}param(e){return e?this.#n(e):this.#r()}#n(e){let t=this.#t[0][this.routeIndex][1][e],n=this.#i(t);return n&&/\%/.test(n)?_U(n):n}#r(){let e={},t=Object.keys(this.#t[0][this.routeIndex][1]);for(let n of t){let t=this.#i(this.#t[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?_U(t):t)}return e}#i(e){return this.#t[1]?this.#t[1][e]:e}query(e){return mU(this.url,e)}queries(e){return hU(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return YH(this,e)}#a=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#a(`text`).then(e=>JSON.parse(e))}text(){return this.#a(`text`)}arrayBuffer(){return this.#a(`arrayBuffer`)}bytes(){return this.#a(`arrayBuffer`).then(e=>new Uint8Array(e))}blob(){return this.#a(`blob`)}formData(){return this.#a(`formData`)}addValidatedData(e,t){this.#e[e]=t}valid(e){return this.#e[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[KH](){return this.#t}get matchedRoutes(){return this.#t[0].map(([[,e]])=>e)}get routePath(){return this.#t[0].map(([[,e]])=>e)[this.routeIndex].path}},yU={Stringify:1,BeforeStream:2,Stream:3},bU=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},xU=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>xU(e,t,!1,r,i))).then(()=>i[0]));return n?bU(await o,a):o},SU=`text/plain; charset=UTF-8`,CU=(e,t)=>({"Content-Type":e,...t}),wU=(e,t)=>new Response(e,t),TU=class{#e;#t;env={};#n;finalized=!1;error;#r;#i;#a;#o;#s;#c;#l;#u;#d;constructor(e,t){this.#e=e,t&&(this.#i=t.executionCtx,this.env=t.env,this.#c=t.notFoundHandler,this.#d=t.path,this.#u=t.matchResult)}get req(){return this.#t??=new vU(this.#e,this.#d,this.#u),this.#t}get event(){if(this.#i&&`respondWith`in this.#i)return this.#i;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#i)return this.#i;throw Error(`This context has no ExecutionContext`)}get res(){return this.#a||=wU(null,{headers:this.#l??=new Headers})}set res(e){if(this.#a&&e){e=wU(e.body,e);for(let[t,n]of this.#a.headers.entries())if(t!==`content-type`)if(t===`set-cookie`){let t=this.#a.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}this.#a=e,this.finalized=!0}render=(...e)=>(this.#s??=e=>this.html(e),this.#s(...e));setLayout=e=>this.#o=e;getLayout=()=>this.#o;setRenderer=e=>{this.#s=e};header=(e,t,n)=>{this.finalized&&(this.#a=wU(this.#a.body,this.#a));let r=this.#a?this.#a.headers:this.#l??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#r=e};set=(e,t)=>{this.#n??=new Map,this.#n.set(e,t)};get=e=>this.#n?this.#n.get(e):void 0;get var(){return this.#n?Object.fromEntries(this.#n):{}}#f(e,t,n){let r=this.#a?new Headers(this.#a.headers):this.#l??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}return wU(e,{status:typeof t==`number`?t:t?.status??this.#r,headers:r})}newResponse=(...e)=>this.#f(...e);body=(e,t,n)=>this.#f(e,t,n);text=(e,t,n)=>!this.#l&&!this.#r&&!t&&!n&&!this.finalized?new Response(e):this.#f(e,t,CU(SU,n));json=(e,t,n)=>this.#f(JSON.stringify(e),t,CU(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#f(e,t,CU(`text/html; charset=UTF-8`,n));return typeof e==`object`?xU(e,yU.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#c??=()=>wU(),this.#c(this))},EU=[`get`,`post`,`put`,`delete`,`options`,`patch`],DU=`Can not add a route since the matcher is already built.`,OU=class extends Error{},kU=`__COMPOSED_HANDLER`,AU=e=>e.text(`404 Not Found`,404),jU=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},MU=class e{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#e=`/`;routes=[];constructor(e={}){[...EU,`all`].forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#e=t:this.#r(e,this.#e,t),n.forEach(t=>{this.#r(e,this.#e,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#e=r;for(let t of[e].flat())n.map(e=>{this.#r(t.toUpperCase(),this.#e,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#e=e:(this.#e=`*`,t.unshift(e)),t.forEach(e=>{this.#r(`ALL`,this.#e,e)}),this);let{strict:t,...n}=e;Object.assign(this,n),this.getPath=t??!0?e.getPath??cU:lU}#t(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#n=this.#n,t.routes=this.routes,t}#n=AU;errorHandler=jU;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===jU?r=e.handler:(r=async(n,r)=>(await GH([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[kU]=e.handler),n.#r(e.method,e.path,r,e.basePath)}),this}basePath(e){let t=this.#t();return t._basePath=uU(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#n=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};return r||=(()=>{let t=uU(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=this.getPath(e).slice(n)||`/`,new Request(t,e)}})(),this.#r(`ALL`,uU(e,`*`),async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()}),this}#r(e,t,n,r){e=e.toUpperCase(),t=uU(this._basePath,t);let i={basePath:r===void 0?this._basePath:uU(this._basePath,r),path:t,method:e,handler:n};this.router.add(e,t,[n,i]),this.routes.push(i)}#i(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#a(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#a(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new TU(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#n});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#n(o)})}catch(e){return this.#i(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#n(o))).catch(e=>this.#i(e,o)):e??this.#n(o)}let s=GH(a[0],this.errorHandler,this.#n);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#i(e,o)}})()}fetch=(e,...t)=>this.#a(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${uU(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#a(e.request,e,void 0,e.request.method))})}},NU=[];function PU(e,t){let n=this.buildAllMatchers(),r=((e,t)=>{let r=n[e]||n.ALL,i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],NU];let o=a.indexOf(``,1);return[r[1][o],a]});return this.match=r,r(e,t)}var FU=`[^/]+`,IU=`.*`,LU=`(?:|/.*)`,RU=Symbol(),zU=new Set(`.\\+*[^]$()`);function BU(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===IU||e===LU?1:t===IU||t===LU?-1:e===FU?1:t===FU?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var VU=class e{#e;#t;#n=Object.create(null);insert(t,n,r,i,a){if(t.length===0){if(this.#e!==void 0)throw RU;if(a)return;this.#e=n;return}let[o,...s]=t,c=o===`*`?s.length===0?[``,``,IU]:[``,``,FU]:o===`/*`?[``,``,LU]:o.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),l;if(c){let t=c[1],n=c[2]||FU;if(t&&c[2]&&(n===`.*`||(n=n.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(n))))throw RU;if(l=this.#n[n],!l){if(Object.keys(this.#n).some(e=>e!==IU&&e!==LU))throw RU;if(a)return;l=this.#n[n]=new e,t!==``&&(l.#t=i.varIndex++)}!a&&t!==``&&r.push([t,l.#t])}else if(l=this.#n[o],!l){if(Object.keys(this.#n).some(e=>e.length>1&&e!==IU&&e!==LU))throw RU;if(a)return;l=this.#n[o]=new e}l.insert(s,n,r,i,a)}buildRegExpStr(){let e=Object.keys(this.#n).sort(BU).map(e=>{let t=this.#n[e];return(typeof t.#t==`number`?`(${e})@${t.#t}`:zU.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#e==`number`&&e.unshift(`#${this.#e}`),e.length===0?``:e.length===1?e[0]:`(?:`+e.join(`|`)+`)`}},HU=class{#e={varIndex:0};#t=new VU;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#t.insert(a,t,r,this.#e,n),r}buildRegExp(){let e=this.#t.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},UU=[/^$/,[],Object.create(null)],WU=Object.create(null);function GU(e){return WU[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function KU(){WU=Object.create(null)}function qU(e){let t=new HU,n=[];if(e.length===0)return UU;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),NU]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===RU?new OU(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function JU(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(GU(n).test(t))return[...e[n]]}}var YU=class{name=`RegExpRouter`;#e;#t;constructor(){this.#e={ALL:Object.create(null)},this.#t={ALL:Object.create(null)}}add(e,t,n){let r=this.#e,i=this.#t;if(!r||!i)throw Error(DU);r[e]||[r,i].forEach(t=>{t[e]=Object.create(null),Object.keys(t.ALL).forEach(n=>{t[e][n]=[...t.ALL[n]]})}),t===`/*`&&(t=`*`);let a=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let o=GU(t);e===`ALL`?Object.keys(r).forEach(e=>{r[e][t]||=JU(r[e],t)||JU(r.ALL,t)||[]}):r[e][t]||=JU(r[e],t)||JU(r.ALL,t)||[],Object.keys(r).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(r[t]).forEach(e=>{o.test(e)&&r[t][e].push([n,a])})}),Object.keys(i).forEach(t=>{(e===`ALL`||e===t)&&Object.keys(i[t]).forEach(e=>o.test(e)&&i[t][e].push([n,a]))});return}let o=dU(t)||[t];for(let t=0,s=o.length;t<s;t++){let c=o[t];Object.keys(i).forEach(o=>{(e===`ALL`||e===o)&&(i[o][c]||=[...JU(r[o],c)||JU(r.ALL,c)||[]],i[o][c].push([n,a-s+t+1]))})}}match=PU;buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#t).concat(Object.keys(this.#e)).forEach(t=>{e[t]||=this.#n(t)}),this.#e=this.#t=void 0,KU(),e}#n(e){let t=[],n=e===`ALL`;return[this.#e,this.#t].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==`ALL`&&t.push(...Object.keys(r.ALL).map(e=>[e,r.ALL[e]])):(n||=!0,t.push(...i))}),n?qU(t):null}},XU=class{name=`SmartRouter`;#e=[];#t=[];constructor(e){this.#e=e.routers}add(e,t,n){if(!this.#t)throw Error(DU);this.#t.push([e,t,n])}match(e,t){if(!this.#t)throw Error(`Fatal error`);let n=this.#e,r=this.#t,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof OU)continue;throw e}this.match=i.match.bind(i),this.#e=[i],this.#t=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#t||this.#e.length!==1)throw Error(`No active router has been determined yet.`);return this.#e[0]}},ZU=Object.create(null),QU=e=>{for(let t in e)return!0;return!1},$U=class e{#e;#t;#n;#r=0;#i=ZU;constructor(e,t,n){if(this.#t=n||Object.create(null),this.#e=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#e=[n]}this.#n=[]}insert(t,n,r){this.#r=++this.#r;let i=this,a=tU(n),o=[];for(let t=0,n=a.length;t<n;t++){let n=a[t],r=a[t+1],s=aU(n,r),c=Array.isArray(s)?s[0]:n;if(c in i.#t){i=i.#t[c],s&&o.push(s[1]);continue}i.#t[c]=new e,s&&(i.#n.push(s),o.push(s[1])),i=i.#t[c]}return i.#e.push({[t]:{handler:r,possibleKeys:o.filter((e,t,n)=>n.indexOf(e)===t),score:this.#r}}),i}#a(e,t,n,r,i){for(let a=0,o=t.#e.length;a<o;a++){let o=t.#e[a],s=o[n]||o.ALL,c={};if(s!==void 0&&(s.params=Object.create(null),e.push(s),r!==ZU||i&&i!==ZU))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],n=c[s.score];s.params[t]=i?.[t]&&!n?i[t]:r[t]??i?.[t],c[s.score]=!0}}}search(e,t){let n=[];this.#i=ZU;let r=[this],i=eU(t),a=[],o=i.length,s=null;for(let c=0;c<o;c++){let l=i[c],u=c===o-1,d=[];for(let f=0,p=r.length;f<p;f++){let p=r[f],m=p.#t[l];m&&(m.#i=p.#i,u?(m.#t[`*`]&&this.#a(n,m.#t[`*`],e,p.#i),this.#a(n,m,e,p.#i)):d.push(m));for(let r=0,f=p.#n.length;r<f;r++){let f=p.#n[r],m=p.#i===ZU?{}:{...p.#i};if(f===`*`){let t=p.#t[`*`];t&&(this.#a(n,t,e,p.#i),t.#i=m,d.push(t));continue}let[h,g,_]=f;if(!l&&!(_ instanceof RegExp))continue;let v=p.#t[h];if(_ instanceof RegExp){if(s===null){s=Array(o);let e=+(t[0]===`/`);for(let t=0;t<o;t++)s[t]=e,e+=i[t].length+1}let r=t.substring(s[c]),l=_.exec(r);if(l){if(m[g]=l[0],this.#a(n,v,e,p.#i,m),l[0].length===r.length&&v.#t[`*`]&&this.#a(n,v.#t[`*`],e,p.#i,m),QU(v.#t)){v.#i=m;let e=l[0].match(/\//)?.length??0;(a[e]||=[]).push(v)}continue}}(_===!0||_.test(l))&&(m[g]=l,u?(this.#a(n,v,e,m,p.#i),v.#t[`*`]&&this.#a(n,v.#t[`*`],e,m,p.#i)):(v.#i=m,d.push(v)))}}let f=a.shift();r=f?d.concat(f):d}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},eW=class{name=`TrieRouter`;#e;constructor(){this.#e=new $U}add(e,t,n){let r=dU(t);if(r){for(let t=0,i=r.length;t<i;t++)this.#e.insert(e,r[t],n);return}this.#e.insert(e,t,n)}match(e,t){return this.#e.search(e,t)}},tW=class extends MU{constructor(e={}){super(e),this.router=e.router??new XU({routers:[new YU,new eW]})}};function nW(e,t,n,r){if(ZB(e,n))return K(t,403,`urn:ok:error:host-not-allowed`,"Proxied request refused: this server has not consented to external exposure. Set OK_EXTERNAL_URL to the public origin and OK_ALLOW_EXTERNAL=1 (or server.externalUrl + server.allowExternal in config), or restart with `ok start --remote <url>`.",{handler:r}),!1;if(n.allowExternal){let i=Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host;if(!qB(e.socket.remoteAddress,n)||!YB(i,n))return K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:r}),!1}return!0}function rW(e,t){let n=e.filter(e=>!e.includes(`*`)&&e in t),r=e.filter(e=>e.endsWith(`/*`)).map(e=>e.slice(0,-1)),i=Object.keys(t).filter(e=>r.some(t=>e.startsWith(t))).map(e=>`${e} (under a native wildcard)`),a=[...n,...i];if(a.length>0)throw Error(`route(s) present in both the legacy dispatch record and a native route group: ${a.join(`, `)}`);let o=new Set,s=[];for(let t of e)o.has(t)&&s.push(t),o.add(t);let c=e.filter(e=>r.some(t=>e!==`${t}*`&&e.startsWith(t))).map(e=>`${e} (under a native wildcard)`),l=[...new Set([...s,...c])];if(l.length>0)throw Error(`route(s) claimed by more than one native route group: ${l.join(`, `)}`)}function iW(e,t,n,r){if(t.method!==`GET`&&t.method!==`HEAD`){K(n,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`health`,extraHeaders:{Allow:`GET, HEAD`}});return}let i={"Cache-Control":`no-store`,"X-Content-Type-Options":`nosniff`};if(e===`/healthz`){n.writeHead(200,{...i,"Content-Type":`text/plain; charset=utf-8`}),n.end(`ok`);return}let a=r?.readiness()??`ready`,o=a===`ready`;n.writeHead(o?200:503,{...i,"Content-Type":`application/json`}),n.end(JSON.stringify({ready:o,status:a,degraded:o?r?.degraded()??[]:[]}))}function aW(e){let t=new tW;t.onError((t,n)=>{let r=n.env.outgoing;return e.log.error({err:t},`Unhandled router handler error`),!r.headersSent&&!r.writableEnded&&!r.destroyed?K(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`http-app`,cause:t}):r.writableEnded||r.end(),WH});for(let n of[`/healthz`,`/readyz`])t.all(n,t=>(iW(n,t.env.incoming,t.env.outgoing,e.health),WH));let n=e.ingressPolicy??KB({}),r=e.nativeApi;if(r!==void 0)for(let i of r.paths)t.all(i,async t=>{let i=t.env.incoming,a=t.env.outgoing;if(!nW(i,a,n,`native-api-surface`))return WH;try{await r.dispatch(i,a)||e.legacyDispatch(i,a)}catch(t){e.log.error({err:t},`Unhandled onRequest error`),!a.writableEnded&&!a.headersSent?K(a,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`native-api-catch`,cause:t}):a.writableEnded||a.end()}return WH});return t.all(`*`,t=>(e.legacyDispatch(t.env.incoming,t.env.outgoing),WH)),{requestListener:UH(t.fetch,{overrideGlobalObjects:!1,autoCleanupIncoming:!1})}}const oW=F(`suggest-links`),sW=/[\p{L}\p{N}]/u;var cW=class extends Error{constructor(e){super(`Document not found: ${e}`),this.name=`SuggestLinksTargetNotFoundError`}};function lW(e){return e.replace(/\s+/g,` `).trim()}function uW(e,t,n){if(!lW(e))return null;let r=Math.max(e.lastIndexOf(`.`,t-1),e.lastIndexOf(`?`,t-1),e.lastIndexOf(`!`,t-1),e.lastIndexOf(`
103
103
  `,t-1)),i=[e.indexOf(`.`,n),e.indexOf(`?`,n),e.indexOf(`!`,n),e.indexOf(`
104
104
  `,n)].filter(e=>e>=0),a=r>=0?r+1:Math.max(0,t-60),o=i.length>0?Math.min(...i)+1:Math.min(e.length,n+60),s=a>0?`…`:``,c=o<e.length?`…`:``,l=lW(e.slice(a,o));return l?`${s}${l}${c}`:null}function dW(e){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(!t)return null;let n=t[1],r=n[0];return r!=="`"&&r!==`~`?null:{char:r,length:n.length}}function fW(e,t){let n=e.trimStart();if(e.length-n.length>3)return!1;let r=0;for(;n[r]===t.char;)r+=1;return r<t.length?!1:n.slice(r).trim().length===0}function pW(e){let t=/^\s{0,3}(?:#{1,6}\s+|>\s+|(?:[-+*]|\d+[.)])\s+)/.exec(e);return t?t[0].length:0}function mW(e,t){let n=0;for(;e[t+n]==="`";)n++;if(n===0)return null;let r=t+n,i=r;for(;i<e.length;){if(e[i]!=="`"){i+=1;continue}let t=0;for(;e[i+t]==="`";)t+=1;if(t===n)return{text:e.slice(r,i),nextIndex:i+n};i+=t}return{text:e.slice(t,r),nextIndex:r}}function hW(e,t){let n=jM(e,t);if(!n)return null;let r=n.alias??n.target,i=n.alias?n.aliasRaw:n.targetRaw,a=n.alias&&n.aliasRaw?n.end-n.start-2-n.aliasRaw.length:2,o=i?.indexOf(r)??0;return{target:n.target,alias:n.alias,anchor:n.anchor,label:r,labelStart:t+a+Math.max(o,0),nextIndex:n.end}}function gW(e,t){let n=MM(e,t);return!n||n.image?null:{text:n.label,href:n.href,nextIndex:n.end}}function _W(e,t){let n=MM(e,t);return n?.image?{alt:n.label,nextIndex:n.end}:null}function vW(e){return!e||!sW.test(e)}function yW(e,t,n){return vW(e[t-1])&&vW(e[n])}function bW(e){let t=[],n=new Set;for(let r of e.matchLabels){let e=r.trim();if(!e)continue;let i=e.toLocaleLowerCase();n.has(i)||(n.add(i),t.push({raw:e,lower:i,length:e.length}))}return t.sort((e,t)=>t.length===e.length?e.raw.localeCompare(t.raw):t.length-e.length)}function xW(e,t){let n=e.toLocaleLowerCase(),r=[];for(let i of t){let t=0;for(;t<=n.length-i.length;){let a=n.indexOf(i.lower,t);if(a===-1)break;let o=a+i.length;yW(e,a,o)&&r.push({start:a,end:o}),t=a+1}}r.sort((e,t)=>{if(e.start!==t.start)return e.start-t.start;let n=e.end-e.start,r=t.end-t.start;return r===n?e.end-t.end:r-n});let i=[],a=null;for(let e of r)a&&e.start<a.end||(i.push(e),a=e);return i}function SW(e,t){let n=[];for(let r=0;r<t.length;r+=1)n.push(e+r);return n}function CW(e,t){let n=e.trim();return n?n===t||Er(n)===t:!1}function wW(e,t,n,r,i){let a=``,o=[],s=``,c=[];function l(){s&&(o.push({flatStart:a.length,text:s,sourceOffsets:c}),a+=s,s=``,c=[])}function u(e,t){s+=e,c.push(t)}function d(e){l(),a+=e}function f(e,t){l(),e&&(o.push({flatStart:a.length,text:e,sourceOffsets:t}),a+=e)}let p=pW(e);for(;p<e.length;){if(e[p]===`\\`&&p+1<e.length){u(e[p+1]??``,t+p+1),p+=2;continue}if(e[p]==="`"){let t=mW(e,p);if(t){d(t.text),p=t.nextIndex;continue}}if(e[p]===`!`&&e[p+1]===`[`){let t=_W(e,p);if(t){d(t.alt),p=t.nextIndex;continue}}if(e[p]===`[`&&e[p+1]===`[`){let n=hW(e,p);if(n){let e=n.label;CW(n.target,r)?d(e):f(e,SW(t+n.labelStart,e)),p=n.nextIndex;continue}}if(e[p]===`[`&&e[p-1]!==`!`){let i=gW(e,p);if(i){Na(i.href,n)?.docName===r?d(i.text):f(i.text,SW(t+p+1,i.text)),p=i.nextIndex;continue}}u(e[p]??``,t+p),p+=1}l();let m=[];for(let e of o){let t=xW(e.text,i);for(let n of t){let t=e.flatStart+n.start,r=e.flatStart+n.end,i=uW(a,t,r)??e.text.slice(n.start,n.end),o=e.sourceOffsets[n.start];typeof o==`number`&&m.push({excerpt:i,offset:o})}}return m}function TW(e,t,n,r){let{frontmatter:i,body:a}=jt(e),o=i.length,s=[],c=null,l=0,u=0;for(;u<=a.length;){let e=a[u];if(!(u===a.length||e===`
105
105
  `||e===`\r`)){u+=1;continue}let i=a.slice(l,u);if(c)fW(i,c)&&(c=null);else{let e=dW(i);e?c=e:s.push(...wW(i,o+l,t,n,r))}if(u===a.length)break;if(e===`\r`&&a[u+1]===`
@@ -208,7 +208,7 @@ last-spawn-error.log
208
208
  # artifact — keep it out of git so teammates don't collide under auto-sync.
209
209
  ${Sa.join(`
210
210
  `)}
211
- `;function YW(e){return HW(L(e,`.gitignore`),JW,`.gitignore`)}const XW={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function ZW(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function QW(e){return e.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if(t.startsWith(`#`)){let n=t[1]===`x`||t[1]===`X`;return ZW(Number.parseInt(t.slice(n?2:1),n?16:10))??e}return XW[t.toLowerCase()]??e})}function $W(e){return e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8288&&e<=8292||e>=8294&&e<=8297||e===65279}function eG(e){return e<=31||e>=127&&e<=159}function tG(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;$W(e)||(t+=eG(e)?` `:n)}return t}function nG(e,t){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``).trimEnd()}…`}function rG(e,t){return nG(tG(QW(e)).replace(/\s+/g,` `).trim(),t)}function iG(e){return e.trim().toLowerCase().split(/\s+/)}function aG(e){return e.replace(/[A-Z]+/g,e=>e.toLowerCase())}function oG(e){return e===32||e===9||e===10||e===12||e===13}const sG=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function cG(e,t){let n=t;for(;n<e.length;){let t=e.charCodeAt(n);if(!(t>=97&&t<=122||t>=48&&t<=57||t===45))break;n++}return{name:e.slice(t,n),end:n}}function lG(e,t,n,r){let i=t.length,a=n;for(;a<i;){let n=t.charCodeAt(a);if(oG(n)||n===47){a++;continue}if(n===62)return a+1;let o=a;for(;a<i&&(n=t.charCodeAt(a),!(oG(n)||n===61||n===62||n===47));)a++;let s=t.slice(o,a);for(;a<i&&oG(t.charCodeAt(a));)a++;let c=``;if(a<i&&t.charCodeAt(a)===61){for(a++;a<i&&oG(t.charCodeAt(a));)a++;if(a<i){let r=t.charCodeAt(a);if(r===34||r===39){a++;let n=t.indexOf(r===34?`"`:`'`,a);c=e.slice(a,n===-1?i:n),a=n===-1?i:n+1}else{let r=a;for(;a<i&&(n=t.charCodeAt(a),!(oG(n)||n===62));)a++;c=e.slice(r,a)}}}r&&s&&!r.has(s)&&r.set(s,c)}return i}function uG(e,t,n){let r=`</${t}`,i=n;for(;i<e.length;){let t=e.indexOf(r,i);if(t===-1)return null;let n=t+r.length,a=n<e.length?e.charCodeAt(n):-1;if(a===62||a===47||a===-1||oG(a)){let r=e.indexOf(`>`,n);return{textEnd:t,end:r===-1?e.length:r+1}}i=t+1}return null}function dG(e){let t=``,n=new Map,r,i=-1;try{let a=aG(e),o=a.length,s=0;for(;s<o;){let c=a.indexOf(`<`,s);if(c===-1)break;let l=c+1<o?a.charCodeAt(c+1):-1;if(l===33){if(a.startsWith(`<!--`,c)){let e=a.indexOf(`-->`,c+2);if(e===-1)break;s=e+3}else{let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1}continue}if(l===63){let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1;continue}if(l===47){let{name:e,end:t}=cG(a,c+2);if(e===`head`){if(t<o){let e=a.indexOf(`>`,t);e!==-1&&(i=e+1)}break}let n=a.indexOf(`>`,t);if(n===-1)break;s=n+1;continue}if(!(l>=97&&l<=122)){s=c+1;continue}let{name:u,end:d}=cG(a,c+1);if(u===`body`){if(d<o){let e=a.charCodeAt(d);(e===62||e===47||oG(e))&&(i=d+1)}break}if(u===`title`){let n=lG(e,a,d,null),r=uG(a,`title`,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.textEnd),s=r.end;continue}if(sG.has(u)){let t=uG(a,u,lG(e,a,d,null));if(t===null)break;s=t.end;continue}if(u===`meta`){let t=new Map;s=lG(e,a,d,t);let r=t.get(`content`);if(r){let e=t.get(`property`),i=t.get(`name`);e?n.set(e.toLowerCase(),r):i&&n.set(i.toLowerCase(),r)}continue}if(u===`link`){let t=new Map;if(s=lG(e,a,d,t),r===void 0){let e=t.get(`href`),n=t.get(`rel`);e&&n&&iG(n).includes(`icon`)&&(r=e)}continue}s=lG(e,a,d,null)}}catch{}return{rawTitle:t,metaContent:n,faviconHref:r,headEndOffset:i}}function fG(e){let{rawTitle:t,metaContent:n,faviconHref:r}=dG(e),i=rG(n.get(`og:title`)??t,200),a=rG(n.get(`og:description`)??n.get(`description`)??``,500),o=rG(n.get(`og:site_name`)??``,100),s={};return i&&(s.title=i),a&&(s.description=a),o&&(s.siteName=o),r&&(s.faviconHref=r),s}function pG(e){return dG(e).headEndOffset}function mG(e){let t;try{t=new URL(e).hostname}catch{return e}return t.startsWith(`www.`)&&t.slice(4).includes(`.`)&&(t=t.slice(4)),t}var hG=t(n(((e,t)=>{(function(e){let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:new RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,`toString`,{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}else if(t=e.match(r.twoOctet))return(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})();else if(t=e.match(r.threeOctet))return(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})();else return null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new e([65216,0,0,0,0,0,0,0]),10],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new e([100,65435,0,0,0,0,0,0]),96],[new e([100,65435,1,0,0,0,0,0]),48]],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new e([24320,0,0,0,0,0,0,0]),16],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32],[new e([16383,0,0,0,0,0,0,0]),20]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,`toString`,{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)}))(),1);function gG(e){let t=e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;try{if(hG.default.IPv4.isValid(t))return hG.default.IPv4.parse(t);if(hG.default.IPv6.isValid(t))return hG.default.IPv6.parse(t)}catch{return null}return null}function _G(e){let t=gG(e);return t!==null&&t.range()===`unicast`}function vG(e){let t=gG(e);return t===null?{kind:`hostname`}:{kind:`ip-literal`,allowed:t.range()===`unicast`,canonical:t.toString(),family:t.kind()===`ipv6`?6:4}}const yG=F(`link-preview.guarded-fetch`),bG=async e=>(await ane(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function xG(e,t){let n=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${n}${e.pathname}${e.search}`}async function SG(e,t,n){let r;try{r=new URL(e)}catch{return{ok:!1,reason:`fetch-error`}}if(r.protocol!==`http:`&&r.protocol!==`https:`)return{ok:!1,reason:`bad-scheme`};let i=vG(r.hostname);if(i.kind===`ip-literal`){if(!i.allowed)return{ok:!1,reason:`private-ip`};let e=i.family===6?`[${i.canonical}]`:i.canonical;return{ok:!0,target:{requestUrl:xG(r,e),pinnedAddress:void 0,serverName:void 0,logicalUrl:r.toString()}}}let a;try{a=await t(r.hostname)}catch{return{ok:!1,reason:`dns-failure`}}if(a.length===0)return{ok:!1,reason:`dns-failure`};for(let e of a)if(!n(e.address))return{ok:!1,reason:`private-ip`};let o=a[0];return{ok:!0,target:{requestUrl:xG(r,r.hostname),pinnedAddress:{address:o.address,family:o.family===6||o.address.includes(`:`)?6:4},serverName:r.hostname,logicalUrl:r.toString()}}}function CG(e){return(t,n,r)=>{n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}function wG(e){return e===301||e===302||e===303||e===307||e===308}function TG(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function EG(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function DG(e){try{e.destroy()}catch{}}function OG(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=e.requestUrl.startsWith(`https:`),o={method:`GET`,agent:!1,signal:t,headers:{"User-Agent":`OpenKnowledge-LinkPreview/1.x`,Accept:`text/html`,"Accept-Encoding":`identity`}};e.pinnedAddress&&(o.lookup=CG(e.pinnedAddress)),a&&e.serverName&&(o.servername=e.serverName);try{let n=(a?one:rne)(e.requestUrl,o,e=>{e.on(`error`,()=>{}),i({ok:!0,response:e})});n.on(`error`,e=>i({ok:!1,reason:EG(e,t)})),n.end()}catch(e){i({ok:!1,reason:EG(e,t)})}})}function kG(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?cne():e===`deflate`?lne():e===`br`?sne():null}function AG(){let e=``;return t=>{let n=e.length;e+=Buffer.from(t).toString(`latin1`);let r=pG(e);return r===-1?-1:r-n}}function jG(e,t,n,r){let i=kG((e.headers[`content-encoding`]??``).trim().toLowerCase());if(i===null)return DG(e),Promise.resolve({ok:!1,reason:`fetch-error`});let a=i===`identity`?e:e.pipe(i);return new Promise(i=>{let o=[],s=r?AG():null,c=0,l=!1,u=()=>{n.removeEventListener(`abort`,f),DG(e),a!==e&&a.destroy()},d=e=>{l||(l=!0,u(),i(e))},f=()=>d({ok:!1,reason:`timeout`});n.addEventListener(`abort`,f,{once:!0}),a!==e&&e.on(`error`,e=>d({ok:!1,reason:EG(e,n)})),a.on(`data`,e=>{if(s){let n=s(e);if(n!==-1){if(c+n>t){d({ok:!1,reason:`oversized`});return}o.push(e.subarray(0,n)),d({ok:!0,body:new Uint8Array(Buffer.concat(o))});return}}if(c+=e.byteLength,c>t){d({ok:!1,reason:`oversized`});return}o.push(e)}),a.on(`end`,()=>d({ok:!0,body:new Uint8Array(Buffer.concat(o))})),a.on(`error`,e=>d({ok:!1,reason:EG(e,n)}))})}function MG(e){return yG.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function NG(e,t={}){let n=t.allowContentType??(e=>e===`text/html`),r=t.maxBytes??524288,i=t.timeoutMs??5e3,a=t.maxRedirects??3,o=t.resolve??bG,s=t.isAddressAllowed??_G,c=AbortSignal.timeout(i),l=e,u=0;for(;;){let e=await SG(l,o,s);if(!e.ok)return MG(e.reason);let{target:t}=e,i=await OG(t,c);if(!i.ok)return MG(i.reason);let d=i.response;if(wG(d.statusCode??0)){let e=d.headers.location;if(DG(d),e===void 0)return MG(`fetch-error`);if(u>=a)return MG(`redirect-limit`);u+=1;try{l=new URL(e,t.logicalUrl).toString()}catch{return MG(`fetch-error`)}continue}let f=TG(d.headers[`content-type`]);if(!n(f))return DG(d),MG(`non-html`);let p=await jG(d,r,c,f===`text/html`);return p.ok?{ok:!0,body:p.body,contentType:f,finalUrl:t.logicalUrl}:MG(p.reason)}}function PG(e){let t=e;return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?`image/png`:t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?`image/jpeg`:t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97?`image/gif`:t.length>=2&&t[0]===66&&t[1]===77?`image/bmp`:t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?`image/webp`:t.length>=4&&t[0]===0&&t[1]===0&&t[2]===1&&t[3]===0?`image/x-icon`:null}function FG(e){return e.startsWith(`image/`)}function IG(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function LG(e,t){let n=await t(e,{allowContentType:FG,maxBytes:102400,timeoutMs:2500});if(!n.ok)return;let r=PG(n.body);if(r)return`data:${r};base64,${Buffer.from(n.body).toString(`base64`)}`}async function RG(e){let t=fG(e.html),n=IG(t.faviconHref,e.finalUrl),r=n?await LG(n,e.fetch??NG):void 0;return{domain:mG(e.requestUrl),...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.siteName===void 0?{}:{siteName:t.siteName},...r===void 0?{}:{faviconDataUri:r}}}const zG=F(`link-preview.cache`);function BG(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function VG(e){return Cu(`sha256`).update(e,`utf-8`).digest(`hex`)}var HG=class{cacheDir;metaDir;manifestPath;maxEntries;successTtlMs;negativeTtlMs;now;entries=new Map;payloads=new Map;persistedKeys=new Set;inFlight=new Map;dirty=!1;persisting=!1;persistPending=!1;constructor(e){this.cacheDir=e.cacheDir,this.metaDir=e.cacheDir?L(e.cacheDir,`meta`):null,this.manifestPath=e.cacheDir?L(e.cacheDir,`manifest.json`):null,this.maxEntries=e.maxEntries??256,this.successTtlMs=e.successTtlMs??6048e5,this.negativeTtlMs=e.negativeTtlMs??36e5,this.now=e.now??Date.now}async init(){if(!this.cacheDir||!this.manifestPath||!this.metaDir)return;let e=null;try{B(this.manifestPath)&&(e=JSON.parse(await _u(this.manifestPath,`utf-8`)))}catch(e){zG.warn({err:e},`[link-preview] unreadable cache manifest — starting empty`);return}if(!e||e.schemaVersion!==1||!e.entries)return;let t=this.now();for(let[n,r]of Object.entries(e.entries))if(!(!r||r.status!==`ok`&&r.status!==`negative`)&&!(typeof r.expiresAt!=`number`||t>=r.expiresAt)){if(r.status===`ok`){let e=await this.readBlob(n);if(!e)continue;this.payloads.set(n,e),this.persistedKeys.add(n)}this.entries.set(n,r)}}async load(e,t){let n=BG(e);if(n===null)return t();let r=this.getFresh(n);if(r)return r;let i=this.inFlight.get(n);if(i)return i;let a=(async()=>{let e=await t();return this.record(n,e),e})().finally(()=>{this.inFlight.delete(n)});return this.inFlight.set(n,a),a}getFresh(e){let t=this.entries.get(e);if(!t)return;if(this.now()>=t.expiresAt){this.drop(e),this.dirty=!0;return}if(this.entries.delete(e),this.entries.set(e,t),t.status===`negative`)return{ok:!1,reason:t.reason??`error`};let n=this.payloads.get(e);if(!n){this.drop(e),this.dirty=!0;return}return{ok:!0,metadata:n}}record(e,t){let n=this.now();this.persistedKeys.delete(e),this.entries.delete(e),this.payloads.delete(e),t.ok?(this.entries.set(e,{status:`ok`,fetchedAt:n,expiresAt:n+this.successTtlMs}),this.payloads.set(e,t.metadata)):this.entries.set(e,{status:`negative`,fetchedAt:n,expiresAt:n+this.negativeTtlMs,reason:t.reason}),this.dirty=!0,this.evict()}evict(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.drop(e),this.dirty=!0}}drop(e){this.entries.delete(e),this.payloads.delete(e),this.persistedKeys.delete(e)}async persist(){if(this.cacheDir){if(this.persisting){this.persistPending=!0;return}this.persisting=!0;try{do this.persistPending=!1,await this.writeToDisk();while(this.persistPending&&this.dirty)}finally{this.persisting=!1}}}async writeToDisk(){if(!(!this.cacheDir||!this.manifestPath||!this.metaDir)&&this.dirty)try{await ts(this.metaDir,{recursive:!0});let e=new Set;for(let[t,n]of this.entries){if(n.status!==`ok`||(e.add(VG(t)),this.persistedKeys.has(t)))continue;let r=this.payloads.get(t);r&&(await Qo(L(this.metaDir,`${VG(t)}.json`),JSON.stringify(r)),this.persistedKeys.add(t))}let t={schemaVersion:1,entries:Object.fromEntries(this.entries)},n=`${this.manifestPath}.tmp`;await Qo(n,JSON.stringify(t)),await _s(n,this.manifestPath);for(let t of tu(this.metaDir)){if(!t.endsWith(`.json`))continue;let n=t.slice(0,-5);e.has(n)||is(L(this.metaDir,t))}this.dirty=!1}catch(e){zG.warn({err:e},`[link-preview] failed to persist cache`)}}clearMemory(){this.entries.clear(),this.payloads.clear(),this.persistedKeys.clear(),this.inFlight.clear(),this.dirty=!1}async wipe(){if(this.clearMemory(),this.cacheDir)try{ps(this.cacheDir,{recursive:!0,force:!0})}catch(e){zG.warn({err:e},`[link-preview] failed to wipe cache`)}}get size(){return this.entries.size}async readBlob(e){if(!this.metaDir)return null;let t=L(this.metaDir,`${VG(e)}.json`);try{if(!B(t))return null;let e=si.safeParse(JSON.parse(await _u(t,`utf-8`)));return e.success?e.data:null}catch(e){return zG.warn({err:e},`[link-preview] unreadable cache blob — treating as miss`),null}}};function UG(e){if(!e||e===`null`)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)}function WG(e){return e?e.split(`;`,1)[0]?.trim().toLowerCase()===`application/json`:!1}function GG(e){return UG(e.origin)?WG(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}const KG=F(`local-op-security`),qG=FE,JG=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function YG(e){return!e||typeof e!=`string`||JG.some(t=>t.test(e))?!1:qG.some(t=>t.test(e))}function XG(e){return e===`~`?uu():e.startsWith(`~/`)?L(uu(),e.slice(2)):e}function ZG(e,t){let n=I(e);for(;n!==t&&n!==I(n);){let e;try{e=Yl(n)}catch(e){let t=Us(e);return KG.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return KG.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=I(n)}return!1}function QG(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=H(t)}catch(e){let n=Us(e);return KG.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=z(XG(e)),i=[],a=r;for(;;){let e=null;try{e=Yl(a)}catch(e){let t=Us(e);if(t!==`ENOENT`)return KG.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=H(a)}catch(n){let i=Us(n);if(e.isSymbolicLink())return KG.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(ZG(a,t))return KG.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;KG.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return KG.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:L(r,...i),s=R(n,o);return s===``||!s.startsWith(`..`)&&!Ll(s)}let r=I(a);if(r===a)return!1;i.unshift(Pl(a)),a=r}}function $G(e){return QG(e,uu())}function eK(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function tK(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.publicOrigin!==void 0&&e.protocol===t.publicOrigin.protocol&&nK(e.host)===t.publicOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function nK(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function rK(e,t,n){let r=n.policy??KB({});return!eK(e)&&!qB(e.socket.remoteAddress,r)?(K(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):tK(e,r)?!0:(K(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function iK(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function aK(e){let[t,...n]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let r=[...n,...e.trailingArgs],i=!1,a=!1,o=``,s=[],c={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(c.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(Fl));let l=jl(t,r,fN({stdio:e.stdinData===void 0?[`ignore`,`pipe`,`pipe`]:[`pipe`,`pipe`,`pipe`],cwd:e.cwd,env:c}));e.stdinData!==void 0&&l.stdin&&(l.stdin.on(`error`,()=>{}),l.stdin.write(e.stdinData),l.stdin.end());let u=setTimeout(()=>{i=!0,l.kill(`SIGTERM`)},e.timeoutMs),d=t=>{if(!t.trim())return;let n=null;try{let e=JSON.parse(t);n=e&&typeof e==`object`?e:null}catch{n=null}e.onLine({raw:t,parsed:n})};return l.stdout?.on(`data`,e=>{o+=e.toString(`utf-8`);let t=o.split(`
211
+ `;function YW(e){return HW(L(e,`.gitignore`),JW,`.gitignore`)}const XW={amp:`&`,lt:`<`,gt:`>`,quot:`"`,apos:`'`,nbsp:` `,copy:`©`,reg:`®`,trade:`™`,mdash:`—`,ndash:`–`,hellip:`…`,lsquo:`‘`,rsquo:`’`,ldquo:`“`,rdquo:`”`};function ZW(e){return!Number.isInteger(e)||e<0||e>1114111||e>=55296&&e<=57343?null:String.fromCodePoint(e)}function QW(e){return e.replace(/&(#[xX][0-9a-fA-F]+|#\d+|[a-zA-Z][a-zA-Z0-9]*);/g,(e,t)=>{if(t.startsWith(`#`)){let n=t[1]===`x`||t[1]===`X`;return ZW(Number.parseInt(t.slice(n?2:1),n?16:10))??e}return XW[t.toLowerCase()]??e})}function $W(e){return e===1564||e>=8203&&e<=8207||e===8232||e===8233||e>=8234&&e<=8238||e>=8288&&e<=8292||e>=8294&&e<=8297||e===65279}function eG(e){return e<=31||e>=127&&e<=159}function tG(e){let t=``;for(let n of e){let e=n.codePointAt(0)??0;$W(e)||(t+=eG(e)?` `:n)}return t}function nG(e,t){let n=Array.from(e);return n.length<=t?e:`${n.slice(0,t-1).join(``).trimEnd()}…`}function rG(e,t){return nG(tG(QW(e)).replace(/\s+/g,` `).trim(),t)}function iG(e){return e.trim().toLowerCase().split(/\s+/)}function aG(e){return e.replace(/[A-Z]+/g,e=>e.toLowerCase())}function oG(e){return e===32||e===9||e===10||e===12||e===13}const sG=new Set([`script`,`style`,`template`,`textarea`,`iframe`,`xmp`,`noembed`,`noframes`,`plaintext`]);function cG(e,t){let n=t;for(;n<e.length;){let t=e.charCodeAt(n);if(!(t>=97&&t<=122||t>=48&&t<=57||t===45))break;n++}return{name:e.slice(t,n),end:n}}function lG(e,t,n,r){let i=t.length,a=n;for(;a<i;){let n=t.charCodeAt(a);if(oG(n)||n===47){a++;continue}if(n===62)return a+1;let o=a;for(;a<i&&(n=t.charCodeAt(a),!(oG(n)||n===61||n===62||n===47));)a++;let s=t.slice(o,a);for(;a<i&&oG(t.charCodeAt(a));)a++;let c=``;if(a<i&&t.charCodeAt(a)===61){for(a++;a<i&&oG(t.charCodeAt(a));)a++;if(a<i){let r=t.charCodeAt(a);if(r===34||r===39){a++;let n=t.indexOf(r===34?`"`:`'`,a);c=e.slice(a,n===-1?i:n),a=n===-1?i:n+1}else{let r=a;for(;a<i&&(n=t.charCodeAt(a),!(oG(n)||n===62));)a++;c=e.slice(r,a)}}}r&&s&&!r.has(s)&&r.set(s,c)}return i}function uG(e,t,n){let r=`</${t}`,i=n;for(;i<e.length;){let t=e.indexOf(r,i);if(t===-1)return null;let n=t+r.length,a=n<e.length?e.charCodeAt(n):-1;if(a===62||a===47||a===-1||oG(a)){let r=e.indexOf(`>`,n);return{textEnd:t,end:r===-1?e.length:r+1}}i=t+1}return null}function dG(e){let t=``,n=new Map,r,i=-1;try{let a=aG(e),o=a.length,s=0;for(;s<o;){let c=a.indexOf(`<`,s);if(c===-1)break;let l=c+1<o?a.charCodeAt(c+1):-1;if(l===33){if(a.startsWith(`<!--`,c)){let e=a.indexOf(`-->`,c+2);if(e===-1)break;s=e+3}else{let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1}continue}if(l===63){let e=a.indexOf(`>`,c+2);if(e===-1)break;s=e+1;continue}if(l===47){let{name:e,end:t}=cG(a,c+2);if(e===`head`){if(t<o){let e=a.indexOf(`>`,t);e!==-1&&(i=e+1)}break}let n=a.indexOf(`>`,t);if(n===-1)break;s=n+1;continue}if(!(l>=97&&l<=122)){s=c+1;continue}let{name:u,end:d}=cG(a,c+1);if(u===`body`){if(d<o){let e=a.charCodeAt(d);(e===62||e===47||oG(e))&&(i=d+1)}break}if(u===`title`){let n=lG(e,a,d,null),r=uG(a,`title`,n);if(r===null){t+=e.slice(n);break}t+=e.slice(n,r.textEnd),s=r.end;continue}if(sG.has(u)){let t=uG(a,u,lG(e,a,d,null));if(t===null)break;s=t.end;continue}if(u===`meta`){let t=new Map;s=lG(e,a,d,t);let r=t.get(`content`);if(r){let e=t.get(`property`),i=t.get(`name`);e?n.set(e.toLowerCase(),r):i&&n.set(i.toLowerCase(),r)}continue}if(u===`link`){let t=new Map;if(s=lG(e,a,d,t),r===void 0){let e=t.get(`href`),n=t.get(`rel`);e&&n&&iG(n).includes(`icon`)&&(r=e)}continue}s=lG(e,a,d,null)}}catch{}return{rawTitle:t,metaContent:n,faviconHref:r,headEndOffset:i}}function fG(e){let{rawTitle:t,metaContent:n,faviconHref:r}=dG(e),i=rG(n.get(`og:title`)??t,200),a=rG(n.get(`og:description`)??n.get(`description`)??``,500),o=rG(n.get(`og:site_name`)??``,100),s={};return i&&(s.title=i),a&&(s.description=a),o&&(s.siteName=o),r&&(s.faviconHref=r),s}function pG(e){return dG(e).headEndOffset}function mG(e){let t;try{t=new URL(e).hostname}catch{return e}return t.startsWith(`www.`)&&t.slice(4).includes(`.`)&&(t=t.slice(4)),t}var hG=t(n(((e,t)=>{(function(e){let n=`(0?\\d+|0x[a-f0-9]+)`,r={fourOctet:RegExp(`^${n}\\.${n}\\.${n}\\.${n}$`,`i`),threeOctet:RegExp(`^${n}\\.${n}\\.${n}$`,`i`),twoOctet:RegExp(`^${n}\\.${n}$`,`i`),longValue:RegExp(`^${n}$`,`i`)},i=RegExp(`^0[0-7]+$`,`i`),a=RegExp(`^0x[a-f0-9]+$`,`i`),o=`%[0-9a-z]{1,}`,s=`(?:[0-9a-f]+::?)+`,c={zoneIndex:new RegExp(o,`i`),native:RegExp(`^(::)?(${s})?([0-9a-f]+)?(::)?(${o})?$`,`i`),deprecatedTransitional:RegExp(`^(?:::)(${n}\\.${n}\\.${n}\\.${n}(${o})?)$`,`i`),transitional:RegExp(`^((?:${s})|(?:::)(?:${s})?)${n}\\.${n}\\.${n}\\.${n}(${o})?$`,`i`)};function l(e,t){if(e.indexOf(`::`)!==e.lastIndexOf(`::`))return null;let n=0,r=-1,i=(e.match(c.zoneIndex)||[])[0],a,o;for(i&&(i=i.substring(1),e=e.replace(/%.+$/,``));(r=e.indexOf(`:`,r+1))>=0;)n++;if(e.substr(0,2)===`::`&&n--,e.substr(-2,2)===`::`&&n--,n>t)return null;for(o=t-n,a=`:`;o--;)a+=`0:`;return e=e.replace(`::`,a),e[0]===`:`&&(e=e.slice(1)),e[e.length-1]===`:`&&(e=e.slice(0,-1)),t=(function(){let t=e.split(`:`),n=[];for(let e=0;e<t.length;e++)n.push(parseInt(t[e],16));return n})(),{parts:t,zoneId:i}}function u(e,t,n,r){if(e.length!==t.length)throw Error(`ipaddr: cannot match CIDR for objects with different lengths`);let i=0,a;for(;r>0;){if(a=n-r,a<0&&(a=0),e[i]>>a!==t[i]>>a)return!1;r-=n,i+=1}return!0}function d(e){if(a.test(e))return parseInt(e,16);if(e[0]===`0`&&!isNaN(parseInt(e[1],10))){if(i.test(e))return parseInt(e,8);throw Error(`ipaddr: cannot parse ${e} as octal`)}return parseInt(e,10)}function f(e,t){for(;e.length<t;)e=`0${e}`;return e}let p={};p.IPv4=(function(){function e(e){if(e.length!==4)throw Error(`ipaddr: ipv4 octet count should be 4`);let t,n;for(t=0;t<e.length;t++)if(n=e[t],!(0<=n&&n<=255))throw Error(`ipaddr: ipv4 octet should fit in 8 bits`);this.octets=e}return e.prototype.SpecialRanges={unspecified:[[new e([0,0,0,0]),8]],broadcast:[[new e([255,255,255,255]),32]],multicast:[[new e([224,0,0,0]),4]],linkLocal:[[new e([169,254,0,0]),16]],loopback:[[new e([127,0,0,0]),8]],carrierGradeNat:[[new e([100,64,0,0]),10]],private:[[new e([10,0,0,0]),8],[new e([172,16,0,0]),12],[new e([192,168,0,0]),16]],reserved:[[new e([192,0,0,0]),24],[new e([192,0,2,0]),24],[new e([192,88,99,0]),24],[new e([198,18,0,0]),15],[new e([198,51,100,0]),24],[new e([203,0,113,0]),24],[new e([240,0,0,0]),4]],as112:[[new e([192,175,48,0]),24],[new e([192,31,196,0]),24]],amt:[[new e([192,52,193,0]),24]]},e.prototype.kind=function(){return`ipv4`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv4`)throw Error(`ipaddr: cannot match ipv4 address with non-ipv4 one`);return u(this.octets,e.octets,8,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:8,128:7,192:6,224:5,240:4,248:3,252:2,254:1,255:0},r,i,a;for(r=3;r>=0;--r)if(i=this.octets[r],i in n){if(a=n[i],t&&a!==0)return null;a!==8&&(t=!0),e+=a}else return null;return 32-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){return this.octets.slice(0)},e.prototype.toIPv4MappedAddress=function(){return p.IPv6.parse(`::ffff:${this.toString()}`)},e.prototype.toNormalizedString=function(){return this.toString()},e.prototype.toString=function(){return this.octets.join(`.`)},e})(),p.IPv4.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<4;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.isIPv4=function(e){return this.parser(e)!==null},p.IPv4.isValid=function(e){try{return new this(this.parser(e)),!0}catch{return!1}},p.IPv4.isValidCIDR=function(e){try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv4.isValidFourPartDecimal=function(e){return!!(p.IPv4.isValid(e)&&e.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/))},p.IPv4.isValidCIDRFourPartDecimal=function(e){let t=e.match(/^(.+)\/(\d+)$/);return!p.IPv4.isValidCIDR(e)||!t?!1:p.IPv4.isValidFourPartDecimal(t[1])},p.IPv4.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<4;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch{throw Error(`ipaddr: the address does not have IPv4 CIDR format`)}},p.IPv4.parse=function(e){let t=this.parser(e);if(t===null)throw Error(`ipaddr: string is not formatted like an IPv4 Address`);return new this(t)},p.IPv4.parseCIDR=function(e){let t;if(t=e.match(/^(.+)\/(\d+)$/)){let e=parseInt(t[2]);if(e>=0&&e<=32){let n=[this.parse(t[1]),e];return Object.defineProperty(n,`toString`,{value:function(){return this.join(`/`)}}),n}}throw Error(`ipaddr: string is not formatted like an IPv4 CIDR range`)},p.IPv4.parser=function(e){let t,n,i;if(t=e.match(r.fourOctet))return(function(){let e=t.slice(1,6),r=[];for(let t=0;t<e.length;t++)n=e[t],r.push(d(n));return r})();if(t=e.match(r.longValue)){if(i=d(t[1]),i>4294967295||i<0)throw Error(`ipaddr: address outside defined range`);return(function(){let e=[],t;for(t=0;t<=24;t+=8)e.push(i>>t&255);return e})().reverse()}else if(t=e.match(r.twoOctet))return(function(){let e=t.slice(1,4),n=[];if(i=d(e[1]),i>16777215||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(i>>16&255),n.push(i>>8&255),n.push(i&255),n})();else if(t=e.match(r.threeOctet))return(function(){let e=t.slice(1,5),n=[];if(i=d(e[2]),i>65535||i<0)throw Error(`ipaddr: address outside defined range`);return n.push(d(e[0])),n.push(d(e[1])),n.push(i>>8&255),n.push(i&255),n})();else return null},p.IPv4.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>32)throw Error(`ipaddr: invalid IPv4 prefix length`);let t=[0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<4&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.IPv6=(function(){function e(e,t){let n,r;if(e.length===16)for(this.parts=[],n=0;n<=14;n+=2)this.parts.push(e[n]<<8|e[n+1]);else if(e.length===8)this.parts=e;else throw Error(`ipaddr: ipv6 part count should be 8 or 16`);for(n=0;n<this.parts.length;n++)if(r=this.parts[n],!(0<=r&&r<=65535))throw Error(`ipaddr: ipv6 part should fit in 16 bits`);t&&(this.zoneId=t)}return e.prototype.SpecialRanges={unspecified:[new e([0,0,0,0,0,0,0,0]),128],linkLocal:[new e([65152,0,0,0,0,0,0,0]),10],multicast:[new e([65280,0,0,0,0,0,0,0]),8],loopback:[new e([0,0,0,0,0,0,0,1]),128],uniqueLocal:[new e([64512,0,0,0,0,0,0,0]),7],ipv4Mapped:[new e([0,0,0,0,0,65535,0,0]),96],deprecatedSiteLocal:[new e([65216,0,0,0,0,0,0,0]),10],discard:[new e([256,0,0,0,0,0,0,0]),64],rfc6145:[new e([0,0,0,0,65535,0,0,0]),96],rfc6052:[[new e([100,65435,0,0,0,0,0,0]),96],[new e([100,65435,1,0,0,0,0,0]),48]],"6to4":[new e([8194,0,0,0,0,0,0,0]),16],teredo:[new e([8193,0,0,0,0,0,0,0]),32],benchmarking:[new e([8193,2,0,0,0,0,0,0]),48],amt:[new e([8193,3,0,0,0,0,0,0]),32],as112v6:[[new e([8193,4,274,0,0,0,0,0]),48],[new e([9760,79,32768,0,0,0,0,0]),48]],deprecatedOrchid:[new e([8193,16,0,0,0,0,0,0]),28],orchid2:[new e([8193,32,0,0,0,0,0,0]),28],droneRemoteIdProtocolEntityTags:[new e([8193,48,0,0,0,0,0,0]),28],segmentRouting:[new e([24320,0,0,0,0,0,0,0]),16],reserved:[[new e([8193,0,0,0,0,0,0,0]),23],[new e([8193,3512,0,0,0,0,0,0]),32],[new e([16383,0,0,0,0,0,0,0]),20]]},e.prototype.isIPv4MappedAddress=function(){return this.range()===`ipv4Mapped`},e.prototype.kind=function(){return`ipv6`},e.prototype.match=function(e,t){let n;if(t===void 0&&(n=e,e=n[0],t=n[1]),e.kind()!==`ipv6`)throw Error(`ipaddr: cannot match ipv6 address with non-ipv6 one`);return u(this.parts,e.parts,16,t)},e.prototype.prefixLengthFromSubnetMask=function(){let e=0,t=!1,n={0:16,32768:15,49152:14,57344:13,61440:12,63488:11,64512:10,65024:9,65280:8,65408:7,65472:6,65504:5,65520:4,65528:3,65532:2,65534:1,65535:0},r,i;for(let a=7;a>=0;--a)if(r=this.parts[a],r in n){if(i=n[r],t&&i!==0)return null;i!==16&&(t=!0),e+=i}else return null;return 128-e},e.prototype.range=function(){return p.subnetMatch(this,this.SpecialRanges)},e.prototype.toByteArray=function(){let e,t=[],n=this.parts;for(let r=0;r<n.length;r++)e=n[r],t.push(e>>8),t.push(e&255);return t},e.prototype.toFixedLengthString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(f(this.parts[t].toString(16),4));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toIPv4Address=function(){if(!this.isIPv4MappedAddress())throw Error(`ipaddr: trying to convert a generic ipv6 address to ipv4`);let e=this.parts.slice(-2),t=e[0],n=e[1];return new p.IPv4([t>>8,t&255,n>>8,n&255])},e.prototype.toNormalizedString=function(){let e=(function(){let e=[];for(let t=0;t<this.parts.length;t++)e.push(this.parts[t].toString(16));return e}).call(this).join(`:`),t=``;return this.zoneId&&(t=`%${this.zoneId}`),e+t},e.prototype.toRFC5952String=function(){let e=/((^|:)(0(:|$)){2,})/g,t=this.toNormalizedString(),n=0,r=-1,i;for(;i=e.exec(t);)i[0].length>r&&(n=i.index,r=i[0].length);return r<0?t:`${t.substring(0,n)}::${t.substring(n+r)}`},e.prototype.toString=function(){return this.toRFC5952String()},e})(),p.IPv6.broadcastAddressFromCIDR=function(e){try{let t=this.parseCIDR(e),n=t[0].toByteArray(),r=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],a=0;for(;a<16;)i.push(parseInt(n[a],10)|parseInt(r[a],10)^255),a++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.isIPv6=function(e){return this.parser(e)!==null},p.IPv6.isValid=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{let t=this.parser(e);return new this(t.parts,t.zoneId),!0}catch{return!1}},p.IPv6.isValidCIDR=function(e){if(typeof e==`string`&&e.indexOf(`:`)===-1)return!1;try{return this.parseCIDR(e),!0}catch{return!1}},p.IPv6.networkAddressFromCIDR=function(e){let t,n,r,i,a;try{for(t=this.parseCIDR(e),r=t[0].toByteArray(),a=this.subnetMaskFromPrefixLength(t[1]).toByteArray(),i=[],n=0;n<16;)i.push(parseInt(r[n],10)&parseInt(a[n],10)),n++;return new this(i)}catch(e){throw Error(`ipaddr: the address does not have IPv6 CIDR format (${e})`)}},p.IPv6.parse=function(e){let t=this.parser(e);if(t.parts===null)throw Error(`ipaddr: string is not formatted like an IPv6 Address`);return new this(t.parts,t.zoneId)},p.IPv6.parseCIDR=function(e){let t,n,r;if((n=e.match(/^(.+)\/(\d+)$/))&&(t=parseInt(n[2]),t>=0&&t<=128))return r=[this.parse(n[1]),t],Object.defineProperty(r,`toString`,{value:function(){return this.join(`/`)}}),r;throw Error(`ipaddr: string is not formatted like an IPv6 CIDR range`)},p.IPv6.parser=function(e){let t,n,r,i,a,o;if(r=e.match(c.deprecatedTransitional))return this.parser(`::ffff:${r[1]}`);if(c.native.test(e))return l(e,8);if((r=e.match(c.transitional))&&(o=r[6]||``,t=r[1],r[1].endsWith(`::`)||(t=t.slice(0,-1)),t=l(t+o,6),t.parts)){for(a=[parseInt(r[2]),parseInt(r[3]),parseInt(r[4]),parseInt(r[5])],n=0;n<a.length;n++)if(i=a[n],!(0<=i&&i<=255))return null;return t.parts.push(a[0]<<8|a[1]),t.parts.push(a[2]<<8|a[3]),{parts:t.parts,zoneId:t.zoneId}}return null},p.IPv6.subnetMaskFromPrefixLength=function(e){if(e=parseInt(e),e<0||e>128)throw Error(`ipaddr: invalid IPv6 prefix length`);let t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=Math.floor(e/8);for(;n<r;)t[n]=255,n++;return r<16&&(t[r]=2**(e%8)-1<<8-e%8),new this(t)},p.fromByteArray=function(e){let t=e.length;if(t===4)return new p.IPv4(e);if(t===16)return new p.IPv6(e);throw Error(`ipaddr: the binary input is neither an IPv6 nor IPv4 address`)},p.isValid=function(e){return p.IPv6.isValid(e)||p.IPv4.isValid(e)},p.isValidCIDR=function(e){return p.IPv6.isValidCIDR(e)||p.IPv4.isValidCIDR(e)},p.parse=function(e){if(p.IPv6.isValid(e))return p.IPv6.parse(e);if(p.IPv4.isValid(e))return p.IPv4.parse(e);throw Error(`ipaddr: the address has neither IPv6 nor IPv4 format`)},p.parseCIDR=function(e){try{return p.IPv6.parseCIDR(e)}catch{try{return p.IPv4.parseCIDR(e)}catch{throw Error(`ipaddr: the address has neither IPv6 nor IPv4 CIDR format`)}}},p.process=function(e){let t=this.parse(e);return t.kind()===`ipv6`&&t.isIPv4MappedAddress()?t.toIPv4Address():t},p.subnetMatch=function(e,t,n){let r,i,a,o;for(i in n??=`unicast`,t)if(Object.prototype.hasOwnProperty.call(t,i)){for(a=t[i],a[0]&&!(a[0]instanceof Array)&&(a=[a]),r=0;r<a.length;r++)if(o=a[r],e.kind()===o[0].kind()&&e.match.apply(e,o))return i}return n},t!==void 0&&t.exports?t.exports=p:e.ipaddr=p})(e)}))(),1);function gG(e){let t=e.length>=2&&e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;try{if(hG.default.IPv4.isValid(t))return hG.default.IPv4.parse(t);if(hG.default.IPv6.isValid(t))return hG.default.IPv6.parse(t)}catch{return null}return null}function _G(e){let t=gG(e);return t!==null&&t.range()===`unicast`}function vG(e){let t=gG(e);return t===null?{kind:`hostname`}:{kind:`ip-literal`,allowed:t.range()===`unicast`,canonical:t.toString(),family:t.kind()===`ipv6`?6:4}}const yG=F(`link-preview.guarded-fetch`),bG=async e=>(await ane(e,{all:!0,family:0})).map(e=>({address:e.address,family:e.family===6?6:4}));function xG(e,t){let n=e.port?`:${e.port}`:``;return`${e.protocol}//${t}${n}${e.pathname}${e.search}`}async function SG(e,t,n){let r;try{r=new URL(e)}catch{return{ok:!1,reason:`fetch-error`}}if(r.protocol!==`http:`&&r.protocol!==`https:`)return{ok:!1,reason:`bad-scheme`};let i=vG(r.hostname);if(i.kind===`ip-literal`){if(!i.allowed)return{ok:!1,reason:`private-ip`};let e=i.family===6?`[${i.canonical}]`:i.canonical;return{ok:!0,target:{requestUrl:xG(r,e),pinnedAddress:void 0,serverName:void 0,logicalUrl:r.toString()}}}let a;try{a=await t(r.hostname)}catch{return{ok:!1,reason:`dns-failure`}}if(a.length===0)return{ok:!1,reason:`dns-failure`};for(let e of a)if(!n(e.address))return{ok:!1,reason:`private-ip`};let o=a[0];return{ok:!0,target:{requestUrl:xG(r,r.hostname),pinnedAddress:{address:o.address,family:o.family===6||o.address.includes(`:`)?6:4},serverName:r.hostname,logicalUrl:r.toString()}}}function CG(e){return(t,n,r)=>{n.all?r(null,[{address:e.address,family:e.family}]):r(null,e.address,e.family)}}function wG(e){return e===301||e===302||e===303||e===307||e===308}function TG(e){return e?(e.split(`;`,1)[0]??``).trim().toLowerCase():``}function EG(e,t){return t.aborted||e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`)?`timeout`:`fetch-error`}function DG(e){try{e.destroy()}catch{}}function OG(e,t){return new Promise(n=>{let r=!1,i=e=>{r||(r=!0,n(e))},a=e.requestUrl.startsWith(`https:`),o={method:`GET`,agent:!1,signal:t,headers:{"User-Agent":`OpenKnowledge-LinkPreview/1.x`,Accept:`text/html`,"Accept-Encoding":`identity`}};e.pinnedAddress&&(o.lookup=CG(e.pinnedAddress)),a&&e.serverName&&(o.servername=e.serverName);try{let n=(a?one:rne)(e.requestUrl,o,e=>{e.on(`error`,()=>{}),i({ok:!0,response:e})});n.on(`error`,e=>i({ok:!1,reason:EG(e,t)})),n.end()}catch(e){i({ok:!1,reason:EG(e,t)})}})}function kG(e){return e===``||e===`identity`?`identity`:e===`gzip`||e===`x-gzip`?cne():e===`deflate`?lne():e===`br`?sne():null}function AG(){let e=``;return t=>{let n=e.length;e+=Buffer.from(t).toString(`latin1`);let r=pG(e);return r===-1?-1:r-n}}function jG(e,t,n,r){let i=kG((e.headers[`content-encoding`]??``).trim().toLowerCase());if(i===null)return DG(e),Promise.resolve({ok:!1,reason:`fetch-error`});let a=i===`identity`?e:e.pipe(i);return new Promise(i=>{let o=[],s=r?AG():null,c=0,l=!1,u=()=>{n.removeEventListener(`abort`,f),DG(e),a!==e&&a.destroy()},d=e=>{l||(l=!0,u(),i(e))},f=()=>d({ok:!1,reason:`timeout`});n.addEventListener(`abort`,f,{once:!0}),a!==e&&e.on(`error`,e=>d({ok:!1,reason:EG(e,n)})),a.on(`data`,e=>{if(s){let n=s(e);if(n!==-1){if(c+n>t){d({ok:!1,reason:`oversized`});return}o.push(e.subarray(0,n)),d({ok:!0,body:new Uint8Array(Buffer.concat(o))});return}}if(c+=e.byteLength,c>t){d({ok:!1,reason:`oversized`});return}o.push(e)}),a.on(`end`,()=>d({ok:!0,body:new Uint8Array(Buffer.concat(o))})),a.on(`error`,e=>d({ok:!1,reason:EG(e,n)}))})}function MG(e){return yG.debug({reason:e},`link-preview guarded fetch rejected`),{ok:!1,reason:e}}async function NG(e,t={}){let n=t.allowContentType??(e=>e===`text/html`),r=t.maxBytes??524288,i=t.timeoutMs??5e3,a=t.maxRedirects??3,o=t.resolve??bG,s=t.isAddressAllowed??_G,c=AbortSignal.timeout(i),l=e,u=0;for(;;){let e=await SG(l,o,s);if(!e.ok)return MG(e.reason);let{target:t}=e,i=await OG(t,c);if(!i.ok)return MG(i.reason);let d=i.response;if(wG(d.statusCode??0)){let e=d.headers.location;if(DG(d),e===void 0)return MG(`fetch-error`);if(u>=a)return MG(`redirect-limit`);u+=1;try{l=new URL(e,t.logicalUrl).toString()}catch{return MG(`fetch-error`)}continue}let f=TG(d.headers[`content-type`]);if(!n(f))return DG(d),MG(`non-html`);let p=await jG(d,r,c,f===`text/html`);return p.ok?{ok:!0,body:p.body,contentType:f,finalUrl:t.logicalUrl}:MG(p.reason)}}function PG(e){let t=e;return t.length>=8&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71&&t[4]===13&&t[5]===10&&t[6]===26&&t[7]===10?`image/png`:t.length>=3&&t[0]===255&&t[1]===216&&t[2]===255?`image/jpeg`:t.length>=6&&t[0]===71&&t[1]===73&&t[2]===70&&t[3]===56&&(t[4]===55||t[4]===57)&&t[5]===97?`image/gif`:t.length>=2&&t[0]===66&&t[1]===77?`image/bmp`:t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?`image/webp`:t.length>=4&&t[0]===0&&t[1]===0&&t[2]===1&&t[3]===0?`image/x-icon`:null}function FG(e){return e.startsWith(`image/`)}function IG(e,t){try{return new URL(e??`/favicon.ico`,t).toString()}catch{return null}}async function LG(e,t){let n=await t(e,{allowContentType:FG,maxBytes:102400,timeoutMs:2500});if(!n.ok)return;let r=PG(n.body);if(r)return`data:${r};base64,${Buffer.from(n.body).toString(`base64`)}`}async function RG(e){let t=fG(e.html),n=IG(t.faviconHref,e.finalUrl),r=n?await LG(n,e.fetch??NG):void 0;return{domain:mG(e.requestUrl),...t.title===void 0?{}:{title:t.title},...t.description===void 0?{}:{description:t.description},...t.siteName===void 0?{}:{siteName:t.siteName},...r===void 0?{}:{faviconDataUri:r}}}const zG=F(`link-preview.cache`);function BG(e){try{let t=new URL(e);return t.hash=``,t.username=``,t.password=``,t.toString()}catch{return null}}function VG(e){return Cu(`sha256`).update(e,`utf-8`).digest(`hex`)}var HG=class{cacheDir;metaDir;manifestPath;maxEntries;successTtlMs;negativeTtlMs;now;entries=new Map;payloads=new Map;persistedKeys=new Set;inFlight=new Map;dirty=!1;persisting=!1;persistPending=!1;constructor(e){this.cacheDir=e.cacheDir,this.metaDir=e.cacheDir?L(e.cacheDir,`meta`):null,this.manifestPath=e.cacheDir?L(e.cacheDir,`manifest.json`):null,this.maxEntries=e.maxEntries??256,this.successTtlMs=e.successTtlMs??6048e5,this.negativeTtlMs=e.negativeTtlMs??36e5,this.now=e.now??Date.now}async init(){if(!this.cacheDir||!this.manifestPath||!this.metaDir)return;let e=null;try{B(this.manifestPath)&&(e=JSON.parse(await _u(this.manifestPath,`utf-8`)))}catch(e){zG.warn({err:e},`[link-preview] unreadable cache manifest — starting empty`);return}if(!e||e.schemaVersion!==1||!e.entries)return;let t=this.now();for(let[n,r]of Object.entries(e.entries))if(!(!r||r.status!==`ok`&&r.status!==`negative`)&&!(typeof r.expiresAt!=`number`||t>=r.expiresAt)){if(r.status===`ok`){let e=await this.readBlob(n);if(!e)continue;this.payloads.set(n,e),this.persistedKeys.add(n)}this.entries.set(n,r)}}async load(e,t){let n=BG(e);if(n===null)return t();let r=this.getFresh(n);if(r)return r;let i=this.inFlight.get(n);if(i)return i;let a=(async()=>{let e=await t();return this.record(n,e),e})().finally(()=>{this.inFlight.delete(n)});return this.inFlight.set(n,a),a}getFresh(e){let t=this.entries.get(e);if(!t)return;if(this.now()>=t.expiresAt){this.drop(e),this.dirty=!0;return}if(this.entries.delete(e),this.entries.set(e,t),t.status===`negative`)return{ok:!1,reason:t.reason??`error`};let n=this.payloads.get(e);if(!n){this.drop(e),this.dirty=!0;return}return{ok:!0,metadata:n}}record(e,t){let n=this.now();this.persistedKeys.delete(e),this.entries.delete(e),this.payloads.delete(e),t.ok?(this.entries.set(e,{status:`ok`,fetchedAt:n,expiresAt:n+this.successTtlMs}),this.payloads.set(e,t.metadata)):this.entries.set(e,{status:`negative`,fetchedAt:n,expiresAt:n+this.negativeTtlMs,reason:t.reason}),this.dirty=!0,this.evict()}evict(){for(;this.entries.size>this.maxEntries;){let e=this.entries.keys().next().value;if(e===void 0)break;this.drop(e),this.dirty=!0}}drop(e){this.entries.delete(e),this.payloads.delete(e),this.persistedKeys.delete(e)}async persist(){if(this.cacheDir){if(this.persisting){this.persistPending=!0;return}this.persisting=!0;try{do this.persistPending=!1,await this.writeToDisk();while(this.persistPending&&this.dirty)}finally{this.persisting=!1}}}async writeToDisk(){if(!(!this.cacheDir||!this.manifestPath||!this.metaDir)&&this.dirty)try{await ts(this.metaDir,{recursive:!0});let e=new Set;for(let[t,n]of this.entries){if(n.status!==`ok`||(e.add(VG(t)),this.persistedKeys.has(t)))continue;let r=this.payloads.get(t);r&&(await Qo(L(this.metaDir,`${VG(t)}.json`),JSON.stringify(r)),this.persistedKeys.add(t))}let t={schemaVersion:1,entries:Object.fromEntries(this.entries)},n=`${this.manifestPath}.tmp`;await Qo(n,JSON.stringify(t)),await _s(n,this.manifestPath);for(let t of tu(this.metaDir)){if(!t.endsWith(`.json`))continue;let n=t.slice(0,-5);e.has(n)||is(L(this.metaDir,t))}this.dirty=!1}catch(e){zG.warn({err:e},`[link-preview] failed to persist cache`)}}clearMemory(){this.entries.clear(),this.payloads.clear(),this.persistedKeys.clear(),this.inFlight.clear(),this.dirty=!1}async wipe(){if(this.clearMemory(),this.cacheDir)try{ps(this.cacheDir,{recursive:!0,force:!0})}catch(e){zG.warn({err:e},`[link-preview] failed to wipe cache`)}}get size(){return this.entries.size}async readBlob(e){if(!this.metaDir)return null;let t=L(this.metaDir,`${VG(e)}.json`);try{if(!B(t))return null;let e=si.safeParse(JSON.parse(await _u(t,`utf-8`)));return e.success?e.data:null}catch(e){return zG.warn({err:e},`[link-preview] unreadable cache blob — treating as miss`),null}}};function UG(e){if(!e||e===`null`)return!1;let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;let n=t.hostname;return n===`localhost`||n===`[::1]`||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(n)}function WG(e){return e?e.split(`;`,1)[0]?.trim().toLowerCase()===`application/json`:!1}function GG(e){return UG(e.origin)?WG(e.contentType)?{ok:!0}:{ok:!1,reason:`content-type`}:{ok:!1,reason:`origin`}}const KG=F(`local-op-security`),qG=FE,JG=[/^file:\/\//i,/^javascript:/i,/^ext::/i,/^data:/i,/^vbscript:/i];function YG(e){return!e||typeof e!=`string`||JG.some(t=>t.test(e))?!1:qG.some(t=>t.test(e))}function XG(e){return e===`~`?uu():e.startsWith(`~/`)?L(uu(),e.slice(2)):e}function ZG(e,t){let n=I(e);for(;n!==t&&n!==I(n);){let e;try{e=Yl(n)}catch(e){let t=Us(e);return KG.warn({path:n,code:t??`unknown`},`ancestorChainHasSymlink: lstat failed on ${n} (${t??`unknown`}); treating as symlink (fail-closed)`),!0}if(e.isSymbolicLink())return KG.warn({path:n},`ancestorChainHasSymlink: symlink detected at ${n}`),!0;n=I(n)}return!1}function QG(e,t){if(!e||typeof e!=`string`||e.includes(`\0`))return!1;let n;try{n=H(t)}catch(e){let n=Us(e);return KG.warn({path:t,code:n??`unknown`},`realpath failed on home dir ${t} (${n??`unknown`}); rejecting all paths`),!1}let r=z(XG(e)),i=[],a=r;for(;;){let e=null;try{e=Yl(a)}catch(e){let t=Us(e);if(t!==`ENOENT`)return KG.warn({path:a,code:t??`unknown`},`lstat error at ${a} (${t??`unknown`}); rejecting`),!1}if(e!==null){let r;try{r=H(a)}catch(n){let i=Us(n);if(e.isSymbolicLink())return KG.warn({path:a,code:i??`unknown`},`realpath failed on symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1;if(i===`EPERM`||i===`EACCES`){if(ZG(a,t))return KG.warn({path:a},`EPERM accept-branch refused at ${a}: symlinked ancestor in chain; rejecting`),!1;KG.warn({path:a,code:i??`unknown`},`realpath denied on non-symlink leaf at ${a} (${i??`unknown`}); trusting lexical path (TCC-class)`),r=a}else return KG.warn({path:a,code:i??`unknown`},`realpath failed on non-symlink leaf at ${a} (${i??`unknown`}); rejecting`),!1}let o=i.length===0?r:L(r,...i),s=R(n,o);return s===``||!s.startsWith(`..`)&&!Ll(s)}let r=I(a);if(r===a)return!1;i.unshift(Pl(a)),a=r}}function $G(e){return QG(e,uu())}function eK(e){let t=e.socket.remoteAddress;return t===`127.0.0.1`||t===`::1`||t===`::ffff:127.0.0.1`}function tK(e,t){let n=e.headers.origin;if(!n)return!0;try{let e=new URL(n),{hostname:r}=e;if(r===`127.0.0.1`||r===`localhost`||r===`[::1]`||r===`::1`)return!0;if(t===void 0)return!1;if(t.externalOrigin!==void 0&&e.protocol===t.externalOrigin.protocol&&nK(e.host)===t.externalOrigin.host)return!0;if(e.protocol!==`http:`&&e.protocol!==`https:`)return!1;let i=r.startsWith(`[`)?r.slice(1,-1):r;return t.bindLiterals.includes(i.toLowerCase())}catch{return!1}}function nK(e){return e.replace(/:(443|80)$/,``).toLowerCase()}function rK(e,t,n){let r=n.policy??KB({});return!eK(e)&&!qB(e.socket.remoteAddress,r)?(K(t,403,`urn:ok:error:loopback-required`,`Local-op endpoints require a loopback connection.`,{handler:n.handler}),!1):tK(e,r)?!0:(K(t,403,`urn:ok:error:invalid-origin`,`Origin header is not a permitted loopback origin.`,{handler:n.handler}),!1)}function iK(){let e=new Set;return{tryAcquire(t){return e.has(t)?!1:(e.add(t),!0)},release(t){e.delete(t)}}}function aK(e){let[t,...n]=e.cliArgs;if(!t)return{done:Promise.resolve({code:-1,stderr:`no command provided`,timedOut:!1,cancelled:!1}),cancel:()=>{}};let r=[...n,...e.trailingArgs],i=!1,a=!1,o=``,s=[],c={...process.env};e.extraPathDirs&&e.extraPathDirs.length>0&&(c.PATH=[...e.extraPathDirs,process.env.PATH??``].filter(Boolean).join(Fl));let l=jl(t,r,fN({stdio:e.stdinData===void 0?[`ignore`,`pipe`,`pipe`]:[`pipe`,`pipe`,`pipe`],cwd:e.cwd,env:c}));e.stdinData!==void 0&&l.stdin&&(l.stdin.on(`error`,()=>{}),l.stdin.write(e.stdinData),l.stdin.end());let u=setTimeout(()=>{i=!0,l.kill(`SIGTERM`)},e.timeoutMs),d=t=>{if(!t.trim())return;let n=null;try{let e=JSON.parse(t);n=e&&typeof e==`object`?e:null}catch{n=null}e.onLine({raw:t,parsed:n})};return l.stdout?.on(`data`,e=>{o+=e.toString(`utf-8`);let t=o.split(`
212
212
  `);o=t.pop()??``;for(let e of t)d(e)}),l.stderr?.on(`data`,t=>{s.push(t),e.onStderr?.(t)}),{done:new Promise(e=>{l.on(`close`,t=>{clearTimeout(u),o.trim()&&d(o),o=``,e({code:t,stderr:Buffer.concat(s).toString(`utf-8`).trim(),timedOut:i,cancelled:a})}),l.on(`error`,t=>{clearTimeout(u),s.push(Buffer.from(t.message,`utf-8`)),e({code:-1,stderr:Buffer.concat(s).toString(`utf-8`).trim(),timedOut:i,cancelled:a})})}),cancel:()=>{if(!a&&(a=!0,!l.killed))try{l.kill(`SIGTERM`)}catch{}}}}function oK(e){let t=e.type;return t===`verification`?typeof e.user_code==`string`&&typeof e.verification_uri==`string`&&typeof e.expires_in==`number`?{type:`verification`,user_code:e.user_code,verification_uri:e.verification_uri,expires_in:e.expires_in}:null:t===`complete`?{type:`complete`,host:typeof e.host==`string`?e.host:``,login:typeof e.login==`string`?e.login:``,name:typeof e.name==`string`?e.name:void 0,email:typeof e.email==`string`?e.email:void 0,avatarUrl:typeof e.avatarUrl==`string`?e.avatarUrl:void 0}:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function sK(e){let t=e.host??`github.com`,n=e.timeoutMs??6e5,r=!1,i=aK({cliArgs:e.cliArgs,trailingArgs:[`auth`,`login`,`--json`,`--host`,t],timeoutMs:n,onLine:({parsed:t})=>{if(!t)return;let n=oK(t);n&&((n.type===`complete`||n.type===`error`)&&(r=!0),e.onEvent(n))}});return{done:i.done.then(n=>{r||(n.code===0?e.onEvent({type:`complete`,host:t,login:``}):e.onEvent({type:`error`,message:n.timedOut?`Sign-in timed out`:`auth login exited with code ${n.code??-1}`}))}),cancel:i.cancel}}async function cK(e){let t=e.host??`github.com`,n=null,r=await aK({cliArgs:e.cliArgs,trailingArgs:[`auth`,`pat`,`--json`,`--host`,t,`--token-stdin`],stdinData:e.token,timeoutMs:e.timeoutMs??3e4,onLine:({parsed:e})=>{e&&(e.type===`complete`?n={ok:!0,host:typeof e.host==`string`?e.host:t,login:typeof e.login==`string`?e.login:``}:e.type===`error`&&(n={ok:!1,host:t,error:typeof e.message==`string`?e.message:`Token validation failed`}))}}).done;return n||{ok:!1,host:t,error:r.timedOut?`Token validation timed out.`:`Token validation failed.`}}const lK=3e4;async function uK(e){let t=e.host??`github.com`,n=[],r=await aK({cliArgs:e.cliArgs,trailingArgs:[`auth`,`status`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??lK,onLine:({parsed:e})=>{e&&n.push(e)}}).done;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.type!==`status`)continue;let i=typeof r.host==`string`?r.host:t;if(r.authenticated===!0&&typeof r.login==`string`){let e=r.tier===`A`||r.tier===`B`||r.tier===`C`?r.tier:void 0;return{authenticated:!0,host:i,login:r.login,tier:e,name:typeof r.name==`string`?r.name:void 0,email:typeof r.email==`string`?r.email:void 0}}return{authenticated:!1,host:i,error:typeof r.error==`string`?r.error:void 0}}return{authenticated:!1,host:t,error:r.timedOut?`auth status timed out`:r.code===0?void 0:r.stderr||`auth status exited with code ${r.code??-1}`}}async function dK(e){let t=e.host??`github.com`,n=[],r=await aK({cliArgs:e.cliArgs,trailingArgs:[`auth`,`repos`,`--json`,`--host`,t],timeoutMs:e.timeoutMs??lK,onLine:({parsed:e})=>{e&&n.push(e)}}).done;if(r.timedOut)return{ok:!1,error:`auth repos timed out`};if(r.code!==0)return{ok:!1,error:r.stderr||`auth repos exited with code ${r.code??-1}`};for(let e=n.length-1;e>=0;e--){let r=n[e];if(r.type!==`repos`||!Array.isArray(r.repos))continue;let i=[];for(let e of r.repos){if(!e||typeof e!=`object`)continue;let t=e;typeof t.full_name!=`string`||typeof t.clone_url!=`string`||i.push({full_name:t.full_name,clone_url:t.clone_url,private:t.private===!0})}return{ok:!0,host:typeof r.host==`string`?r.host:t,repos:i}}return{ok:!1,error:`auth repos returned no data`}}const fK=`Clone subprocess reported an error.`;function pK(e){let t=tI(e).trim().slice(0,500);return t.length===0?{title:fK,detail:``}:/repository not found|returned error:\s*404/i.test(t)?{title:`Can't access this repository. It may be private, or you may not have access.`,detail:t}:/permission denied|access denied|returned error:\s*403/i.test(t)?{title:`You don't have access to this repository.`,detail:t}:/authentication failed/i.test(t)?{title:`GitHub authentication failed. Try signing in again.`,detail:t}:{title:fK,detail:t}}const mK=`2.31.0`,hK=5e3;var gK=class extends Error{code=`GIT_NOT_AVAILABLE`;platform;guidance;constructor(e,t,n){super(PK(t),n),this.name=`GitNotAvailableError`,this.platform=e,this.guidance=t}},_K=class extends Error{code=`GIT_TOO_OLD`;platform;detected;required;resolvedPath;guidance;constructor(e,t,n,r,i,a){super(FK(t,n,r,i),a),this.name=`GitTooOldError`,this.platform=e,this.detected=t,this.required=n,this.resolvedPath=r,this.guidance=i}};function vK(){let e=bK(`git`);if(e.kind===`ok`)return{ok:!0,version:e.version,resolvedPath:e.resolvedPath,source:`PATH`};for(let e of TK(process.platform)){if(!B(e))continue;let t=bK(e);if(t.kind===`ok`)return{ok:!0,version:t.version,resolvedPath:e,source:`fallback`}}throw new gK(process.platform,EK(process.platform))}function yK(){let e=vK();if(IK(e.version,`2.31.0`)<0)throw new _K(process.platform,e.version,mK,e.resolvedPath,EK(process.platform));return e}function bK(e){let t=Ml(e,[`--version`],fN({encoding:`utf-8`,timeout:hK,env:{...process.env,LANG:`C`,LC_ALL:`C`}}));if(t.error)return`signal`in t&&t.signal===`SIGTERM`?{kind:`fail`,reason:`timeout`}:{kind:`fail`,reason:`enoent`};if(t.status!==0)return{kind:`fail`,reason:`nonzero`};let n=xK(typeof t.stdout==`string`?t.stdout:``);return n===null?{kind:`fail`,reason:`unparseable`}:{kind:`ok`,version:n,resolvedPath:e===`git`?wK(`git`)??e:e}}function xK(e){let t=e.match(/git version (\d+)\.(\d+)\.(\d+)/);return t?`${t[1]}.${t[2]}.${t[3]}`:null}const SK=/^[a-zA-Z0-9_.-]+$/,CK=new Map;function wK(e){if(!SK.test(e))return null;let t=CK.get(e);if(t!==void 0)return t;let n;if(process.platform===`win32`){let t=Ml(`where`,[e],fN({encoding:`utf-8`,timeout:hK}));n=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}else{let t=Ml(`/bin/sh`,[`-c`,`command -v ${e}`],fN({encoding:`utf-8`,timeout:hK}));n=t.status===0&&(typeof t.stdout==`string`?t.stdout:``).trim().split(/\r?\n/)[0]||null}return n!==null&&CK.set(e,n),n}function TK(e){switch(e){case`darwin`:return[`/opt/homebrew/bin/git`,`/usr/local/bin/git`,`/Library/Developer/CommandLineTools/usr/bin/git`,`/usr/bin/git`];case`win32`:return[`C:\\Program Files\\Git\\cmd\\git.exe`,`C:\\Program Files (x86)\\Git\\cmd\\git.exe`,L(uu(),`scoop`,`apps`,`git`,`current`,`cmd`,`git.exe`)];default:return[`/usr/bin/git`,`/usr/local/bin/git`,L(uu(),`.local`,`bin`,`git`),`/snap/bin/git`]}}function EK(e){switch(e){case`darwin`:{let e=[];return AK()&&e.push({label:`Install with Homebrew (recommended; no admin needed)`,command:`brew install git`,requiresAdmin:!1}),e.push({label:`Install Xcode Command Line Tools`,command:`xcode-select --install`,requiresAdmin:!0}),{product:`Git`,url:`https://git-scm.com/download/mac`,options:e}}case`win32`:{let e=[];return jK()&&e.push({label:`Install with winget`,command:`winget install --id Git.Git -e --source winget`,requiresAdmin:!0}),MK()&&e.push({label:`Install with Scoop (no admin)`,command:`scoop install git`,requiresAdmin:!1}),NK()&&e.push({label:`Install with Chocolatey`,command:`choco install git -y`,requiresAdmin:!0}),e.push({label:`Download the official installer`,command:`Open https://gitforwindows.org/ in your browser`,requiresAdmin:!1}),{product:`Git for Windows`,url:`https://gitforwindows.org/`,options:e}}default:return{product:`Git`,url:`https://git-scm.com/download/linux`,options:DK()}}}function DK(){switch(OK()){case`debian`:return[{label:`Install with apt`,command:`sudo apt install git`,requiresAdmin:!0}];case`fedora`:return[{label:`Install with dnf`,command:`sudo dnf install git`,requiresAdmin:!0}];case`arch`:return[{label:`Install with pacman`,command:`sudo pacman -S git`,requiresAdmin:!0}];case`opensuse`:return[{label:`Install with zypper`,command:`sudo zypper install git`,requiresAdmin:!0}];case`alpine`:return[{label:`Install with apk`,command:`sudo apk add git`,requiresAdmin:!0}];default:return[{label:`Use your distribution's package manager`,command:`apt / dnf / pacman / zypper / apk install git (one of these will fit your system)`,requiresAdmin:!0}]}}function OK(e){let t=e;if(t===void 0)try{t=V(`/etc/os-release`,`utf-8`)}catch{return`unknown`}let n=[/^ID=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``),...(/^ID_LIKE=(.+)$/m.exec(t)?.[1]?.replace(/["']/g,``)??``).split(/\s+/)].filter(e=>!!e);return n.some(e=>/^(debian|ubuntu|mint|pop)$/i.test(e))?`debian`:n.some(e=>/^(fedora|rhel|centos|alma|rocky)$/i.test(e))?`fedora`:n.some(e=>/^(arch|manjaro|endeavouros)$/i.test(e))?`arch`:n.some(e=>/^opensuse/i.test(e))||n.includes(`suse`)?`opensuse`:n.some(e=>/^alpine$/i.test(e))?`alpine`:`unknown`}function kK(e){return wK(e)!==null}function AK(){return kK(`brew`)}function jK(){return kK(`winget`)}function MK(){return kK(`scoop`)}function NK(){return kK(`choco`)}function PK(e){let t=[];if(t.push(`OpenKnowledge needs ${e.product} to track changes to your knowledge base, but it isn't installed (or isn't on PATH).`),t.push(``),e.options.length>0){t.push(`Install ${e.product}:`);for(let n of e.options){let e=n.requiresAdmin?` (admin required)`:``;t.push(` • ${n.label}${e}`),t.push(` ${n.command}`)}t.push(``)}return t.push(`Or download from: ${e.url}`),t.push(``),t.push(`After installing, re-run OpenKnowledge.`),t.push("Run `ok diagnose health --check git` to verify your installation."),t.join(`
213
213
  `)}function FK(e,t,n,r){let i=[];if(i.push(`OpenKnowledge requires ${r.product} ${t} or newer (detected ${e} at ${n}).`),i.push(``),r.options.length>0){i.push(`Update ${r.product}:`);for(let e of r.options){let t=e.requiresAdmin?` (admin required)`:``;i.push(` • ${e.label}${t}`),i.push(` ${e.command}`)}i.push(``)}return i.push(`Or download from: ${r.url}`),i.push(``),i.push(`After updating, re-run OpenKnowledge.`),i.push("Run `ok diagnose health --check git` to verify your installation."),i.join(`
214
214
  `)}function IK(e,t){let n=e.split(`.`).map(e=>Number.parseInt(e,10)||0),r=t.split(`.`).map(e=>Number.parseInt(e,10)||0);for(let e=0;e<3;e++){let t=n[e]??0,i=r[e]??0;if(t!==i)return t-i}return 0}const LK=`ok.preflight.git.fail`;function RK(e){let t=e instanceof _K?`too_old`:`not_available`,n=e instanceof _K?e.detected:``;Go(LK,{attributes:{"ok.platform":e.platform,"ok.preflight.git.reason":t,"ok.preflight.git.detected_version":n}},()=>{})}const zK=F(`clone-flow`);function BK(e,t){return YG(e)?$G(t)?{ok:!0}:{ok:!1,reason:`invalid-dir`}:{ok:!1,reason:`invalid-url`}}function VK(e){let t=e.type;return t===`progress`?typeof e.phase==`string`&&typeof e.pct==`number`?{type:`progress`,phase:e.phase,pct:e.pct}:null:t===`complete`?typeof e.dir==`string`?{type:`complete`,dir:e.dir}:null:t===`branch-fallback`?typeof e.branch==`string`&&e.branch.length>0?{type:`branch-fallback`,branch:e.branch}:null:t===`error`?{type:`error`,message:typeof e.message==`string`?e.message:`Unknown error`}:null}function HK(e){let t=XG(e.dir),n=e.timeoutMs??6e5,r;try{r=yK()}catch(t){t instanceof gK||t instanceof _K?(RK(t),zK.warn({event:`git_preflight_fail`,platform:t.platform,reason:t instanceof _K?`too_old`:`not_available`,detectedVersion:t instanceof _K?t.detected:``},t instanceof _K?`git binary too old`:`git binary not found`)):zK.error({event:`clone_preflight_unexpected_error`,err:t},`unexpected error during clone preflight`);let n=t instanceof Error?t.message:String(t);return{done:Promise.resolve().then(()=>{e.onEvent({type:`error`,message:n})}),cancel:()=>{}}}let i=Ll(r.resolvedPath)?[I(r.resolvedPath)]:[],a=!1,o=typeof e.branch==`string`&&e.branch.length>0?[`-b`,e.branch]:[],s=aK({cliArgs:e.cliArgs,trailingArgs:[`clone`,`--json`,...o,e.url,t],extraPathDirs:i,timeoutMs:n,onLine:({parsed:t})=>{if(!t)return;let n=VK(t);n&&((n.type===`complete`||n.type===`error`)&&(a=!0),e.onEvent(n))}});return{done:s.done.then(n=>{if(!a){if(n.timedOut){e.onEvent({type:`error`,message:`Clone timed out after 10 minutes`});return}if(n.code!==0){let t=n.stderr?` — ${n.stderr}`:``;e.onEvent({type:`error`,message:`Clone process exited with code ${n.code??-1}${t}`});return}e.onEvent({type:`complete`,dir:t})}}),cancel:s.cancel}}const UK=Au(Al);async function WK(e,t,n){let{stdout:r}=await UK(e,t,{encoding:`utf-8`,timeout:n,windowsHide:!0});return r}const GK=[`/opt/homebrew/bin/gh`,`/usr/local/bin/gh`,`/opt/local/bin/gh`,`/snap/bin/gh`,`/usr/bin/gh`];async function KK(e={}){let t=e._exec??WK,n=e._fileExists??B,r=[`gh`,...GK.filter(n)];for(let e of r)try{return await t(e,[`--version`],5e3),e}catch{}return null}async function qK(e,t,n=WK){try{return(await n(e,[`api`,`--hostname`,t,`user`,`--jq`,`.login`],1e4)).trim()}catch(e){return F(`gh-login`).warn({err:e},`post-login username lookup failed`),``}}let JK,YK;async function XK(){return JK||(YK??=KK().then(e=>(YK=void 0,e!==null&&(JK=e),e)),YK)}const ZK=/one-time code:\s*([A-Za-z0-9-]+)/i,QK=/(https?:\/\/\S+?\/login\/device)\b/i;function $K(e){let t=e.timeoutMs??6e5,n=!1,r=!1,i=``,a=aK({cliArgs:[e.ghPath],trailingArgs:[`auth`,`login`,`--hostname`,e.host,`--web`,`--git-protocol`,`https`,`--skip-ssh-key`],timeoutMs:t,onLine:()=>{},onStderr:t=>{if(i+=t.toString(`utf-8`),n)return;let r=i.match(ZK)?.[1],a=i.match(QK)?.[1];r&&a&&(n=!0,e.onEvent({type:`verification`,user_code:r,verification_uri:a,expires_in:900}))}}),o=setTimeout(()=>{n||(r=!0,e.onEvent({type:`error`,message:`Could not start the browser sign-in — try updating the GitHub CLI (gh), or use a personal access token instead`}),a.cancel())},e.verificationDeadlineMs??3e4);return o.unref?.(),{done:a.done.then(async t=>{if(clearTimeout(o),!r)if(t.code===0){let t=await qK(e.ghPath,e.host);e.onEvent({type:`complete`,host:e.host,login:t})}else e.onEvent({type:`error`,message:t.timedOut?`gh sign-in timed out — please try again`:`gh sign-in failed — please try again`})}),cancel:a.cancel}}const eq=new WeakMap;function tq(e,t){let n=oN(R(e,t));return n.length===0||n===`..`||n.startsWith(`../`)||Ll(n)?null:n}function nq(e,t){let n=[...e];for(let[r,i]of t)for(let t of n)t===i?e.add(r):t.startsWith(`${i}/`)&&e.add(`${r}${t.slice(i.length)}`)}function rq(e,t){if(!e)return null;let n=e.getFileIndexGeneration(),r=eq.get(e);if(r?.contentDir===t&&r.generation===n)return r.inventory;let i=iq(e.getAllFilesIndex(),e.getFolderAliasIndex(),t);return eq.set(e,{contentDir:t,generation:n,inventory:i}),i}function iq(e,t,n){let r=new Set,i=new Set;for(let[t,a]of e){let e=a.kind===`markdown`?r:i;e.add(t);for(let t of a.aliases)e.add(t);let o=tq(n,a.canonicalPath);o&&e.add(a.kind===`markdown`?Vx(o):o)}return nq(r,t),nq(i,t),{documentTargets:[...r],fileTargets:[...i]}}const aq=F(`managed-artifact-persistence`);function oq(e){return e.homedirOverride??uu()}function sq(e){let t=In(e);return t===null||t.kind!==`skill`||t.scope!==`project`?null:{docKey:`${sr}/${t.name}`,subject:`skill-edit: ${t.name}/SKILL.md`}}function cq(e){if(!In(e))return{managed:!1};let t=sq(e);return t?{managed:!0,versioned:!0,docKey:t.docKey,filePath:`${t.docKey}/SKILL.md`}:{managed:!0,versioned:!1}}function lq(e){return fL(oq(e))}function uq(e){return B(`${e}.md`)?`${e}.md`:B(`${e}.mdx`)?`${e}.mdx`:`${e}.md`}function dq(e,t,n){if(!Wa.test(t)||t.length>64)throw Error(`managedSkillBundleDir: invalid skill name: ${JSON.stringify(t)}`);let r=e===`global`?oq(n):n.projectDir;if(e!==`global`)return z(r,`.ok`,`skills`,t);let i=xL(r,t),a=z(r,`.ok`,`skills`,t);return i??(B(z(a,`SKILL.md`))?a:z(r,gL(r,`global`),t))}function fq(e,t){let n=vn(e);if(n!==null){let e=Ez(n.name,null);return e===null?null:I(e)}let r=In(e);return r===null||r.kind!==`skill`?null:dq(r.scope,r.name,t)}function pq(e,t){let n=vn(e);if(n!==null){let t=Ez(n.name,n.rel);if(t===null)throw Error(`managedArtifactAbsPath: external skill not registered: ${e}`);return n.rel===null?t:uq(t)}let r=In(e);if(r===null||r.kind!==`skill`)throw Error(`managedArtifactAbsPath: not a managed skill doc name: ${e}`);let i=dq(r.scope,r.name,t),a;if(r.rel===null)a=z(i,`SKILL.md`);else{let t=r.rel.split(`/`).filter(e=>e!==``&&e!==`.`);if(t.length===0||t.some(e=>e===`..`))throw Error(`managedArtifactAbsPath: invalid skill file path for ${e}`);a=uq(z(i,...t))}if(!a.startsWith(i+Vl))throw Error(`managedArtifactAbsPath: path escape for ${e}`);return a}function mq(e,t){let n=z(e);for(let e of fL(oq(t))){let t=z(e);if(!n.startsWith(t+Vl))continue;let r=n.slice(t.length+1).split(Vl),i=r[0];if(i&&Wa.test(i)&&i.length<=64&&r.length>=2){let e=r.slice(1);if(e.length===1&&e[0]===`SKILL.md`)return`${Et}global/${i}`;let t=e[e.length-1]??``;if(/\.mdx?$/i.test(t)&&!e.includes(`..`))return`${Et}global/${i}/${e.join(`/`).replace(/\.mdx?$/i,``)}`}return null}return null}function hq(e,t,n){let r=In(t);if(r?.kind===`skill`&&r.scope===`project`||t.startsWith(`__template__/`))return;let i=vn(t);if(i&&Ez(i.name,i.rel)===null||e.getXmlFragment(`default`).length>0)return;let a=pq(t,n);if(!B(a))return;let o;try{o=V(a,`utf-8`)}catch(e){aq.warn({documentName:t,err:e},`load: could not read; seeding empty`);return}e.transact(()=>{dz(e,o,void 0,t),e.getMap(`lifecycle`).set(Zr,crypto.randomUUID())},uz),n.setReconciledBase(t,o),n.lkgCache.set(t,o)}async function gq(e,t,n){try{let r=e.replace(/[^A-Za-z0-9._-]+/g,`__`),i=z(oq(n),`.ok`,`edit-backups`,`discarded`,r);await ts(i,{recursive:!0}),await Yo(z(i,`${new Date().toISOString().replace(/[:.]/g,`-`)}.md`),t,{fs:$o});let a=tu(i).sort();for(let e of a.slice(0,Math.max(0,a.length-5)))try{is(z(i,e))}catch{}}catch(t){aq.warn({documentName:e,err:t},`discarded-edit stash failed`)}}async function _q(e,t,n){if(t.rel===null)try{if(!B(e))return;let r=z(oq(n),`.ok`,`edit-backups`,t.name),i=z(r,`SKILL.md.bak`);if(B(i))return;await ts(r,{recursive:!0}),await Yo(i,V(e,`utf-8`),{fs:$o})}catch(e){aq.warn({name:t.name,err:e},`external-skill backup failed`)}}async function vq(e,t,n,r){let i=In(t);if(i?.kind===`skill`&&i.scope===`project`||t.startsWith(`__template__/`))return`no-op`;let a=vn(t);if(a&&Ez(a.name,a.rel)===null||n===uz)return`no-op`;let o=e.getText(`source`).toString(),s=r.lkgCache.get(t);if(o===s)return`no-op`;let c=fq(t,r);if(c!==null&&!B(c))return aq.warn({documentName:t,containerDir:c},`store: artifact container is gone (deleted or moved); dropping the write rather than resurrecting it`),`no-op`;let l=pq(t,r);try{return await ts(z(l,`..`),{recursive:!0}),a&&await _q(l,a,r),await qo(`${l}.lock`,async()=>{if(B(l)){let n=null;try{n=V(l,`utf-8`)}catch(e){e.code!==`ENOENT`&&aq.warn({documentName:t,err:e},`store: pre-write disk read failed (non-ENOENT); proceeding to write`),n=null}if(n!==null&&n!==s&&n!==o){Yoe();let i=r.beforeReconcileDivergence?.(e,t,o,n);return await gq(t,o,r),e.transact(()=>{dz(e,n,void 0,t,void 0,i)},uz),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`reconciled`}}return await Yo(l,o,{fs:$o}),r.lkgCache.set(t,o),r.setReconciledBase(t,o),`persisted`})}catch(e){return e instanceof ss?(aq.warn({documentName:t},`store: file lock timeout; skipping write`),`write-failed`):(aq.warn({documentName:t,err:e},`store: write failed`),`write-failed`)}}function yq(e,t,n,r){if(!e)return`no-op`;let i=r.lkgCache.get(t);return i!==void 0&&i===n?`no-op`:(e.transact(()=>{dz(e,n,void 0,t)},uz),r.setReconciledBase(t,n),r.lkgCache.set(t,n),`applied`)}const bq=F(`managed-rename`);function xq(e){return dO(e)}function Sq(e){return z(xq(e),`managed-rename.json`)}function Cq(e){let t={version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:e.affectedDocs,createdAt:e.createdAt??new Date().toISOString(),snapshots:e.snapshots};return e.pathSnapshots&&e.pathSnapshots.length>0&&(t.pathSnapshots=e.pathSnapshots),e.cleanupPaths&&e.cleanupPaths.length>0&&(t.cleanupPaths=e.cleanupPaths),t}function wq(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.docName==`string`&&typeof t.content==`string`}function Tq(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.path==`string`&&typeof t.content==`string`}function Eq(e){return typeof e==`string`&&e.length>0}function Dq(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.from==`string`&&typeof t.to==`string`}function Oq(e){if(typeof e.fromPath!=`string`||e.fromPath.length===0)throw Error(`Managed rename journal v2 is missing fromPath`);if(typeof e.toPath!=`string`||e.toPath.length===0)throw Error(`Managed rename journal v2 is missing toPath`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v2 is missing createdAt`);let t=e.affectedDocs,n=e.pathSnapshots,r=e.cleanupPaths,i=Array.isArray(n)&&n.length>0,a=Array.isArray(r)&&r.length>0;if(!Array.isArray(t)||!t.every(Dq)||t.length===0&&!i&&!a)throw Error(`Managed rename journal v2 has invalid affectedDocs`);if(!Array.isArray(e.snapshots)||t.length>0&&e.snapshots.length===0||!e.snapshots.every(wq))throw Error(`Managed rename journal v2 has invalid snapshots`);if(n!==void 0&&(!Array.isArray(n)||!n.every(Tq)))throw Error(`Managed rename journal v2 has invalid pathSnapshots`);if(r!==void 0&&(!Array.isArray(r)||!r.every(Eq)))throw Error(`Managed rename journal v2 has invalid cleanupPaths`);for(let n of t)if(!e.snapshots.some(e=>e.docName===n.from))throw Error(`Managed rename journal v2 is missing snapshot for affected doc: ${n.from}`);return{version:2,fromPath:e.fromPath,toPath:e.toPath,affectedDocs:t,createdAt:e.createdAt,snapshots:e.snapshots,...i?{pathSnapshots:n}:{},...a?{cleanupPaths:r}:{}}}function kq(e){if(typeof e.sourceDocName!=`string`||e.sourceDocName.length===0)throw Error(`Managed rename journal v1 is missing sourceDocName`);if(typeof e.destinationDocName!=`string`||e.destinationDocName.length===0)throw Error(`Managed rename journal v1 is missing destinationDocName`);if(typeof e.createdAt!=`string`||e.createdAt.length===0)throw Error(`Managed rename journal v1 is missing createdAt`);if(!Array.isArray(e.snapshots)||e.snapshots.length===0||!e.snapshots.every(wq))throw Error(`Managed rename journal v1 has invalid snapshots`);if(!e.snapshots.some(t=>t.docName===e.sourceDocName))throw Error(`Managed rename journal v1 must include the source document snapshot`);return{version:1,sourceDocName:e.sourceDocName,destinationDocName:e.destinationDocName,createdAt:e.createdAt,snapshots:e.snapshots}}function Aq(e){if(!e||typeof e!=`object`)throw Error(`Managed rename journal must be an object`);let t=e;if(t.version===2)return Oq(t);if(t.version===1)return kq(t);throw Error(`Unsupported managed rename journal version: ${String(t.version)}`)}function jq(e){let t=Sq(e);if(!B(t))return null;try{let e=V(t,`utf-8`);return Aq(JSON.parse(e))}catch(e){throw Error(`Managed rename journal at ${t} is corrupt: ${e instanceof Error?e.message:String(e)}`)}}function Mq(e,t){let n=Sq(e);ls(I(n),{recursive:!0});let r=`${n}.tmp`;vs(r,JSON.stringify(t,null,2),`utf-8`),ns(r,n)}function Nq(e){ps(Sq(e),{force:!0})}async function Pq(e,t,n){Mq(e,t);let r=await n();return Nq(e),r}function Fq(e){return[e.destinationDocName]}function Iq(e){return e.affectedDocs.map(e=>e.to)}function Lq(e,t){let n=z(e),r=z(n,t);if(t.includes(`\0`)||r===n||!r.startsWith(`${n}${Vl}`))throw Error(`Invalid recovery path: ${t}`);return r}function Rq(e,t){let n=z(t),r=`${n}${Vl}`,i=I(e);for(;i.startsWith(r)&&i!==n;){let e;try{e=tu(i)}catch(e){bq.warn({path:i,err:e},`pruneEmptyAncestors: cannot read ${i}`);return}if(e.length>0)return;try{us(i)}catch(e){bq.warn({path:i,err:e},`pruneEmptyAncestors: cannot rmdir ${i}`);return}i=I(i)}}function zq(e,t=e){let n=jq(t);if(!n)return{recovered:!1,journal:null,restoredDocNames:[]};let r=new Set,i=new Set,a=[];for(let t of n.snapshots)try{let n=cN(t.docName,e);ls(I(n),{recursive:!0}),vs(n,t.content,`utf-8`),r.add(t.docName)}catch(e){a.push({docName:t.docName,cause:e}),bq.warn({docName:t.docName,err:e},`Failed to restore ${t.docName}`)}if(a.length>0){let e=a.map(e=>e.docName).join(`, `);bq.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let t=a.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to restore: ${e}`)}if(n.version===2){let t=[];for(let r of n.pathSnapshots??[])try{let t=Lq(e,r.path);ls(I(t),{recursive:!0}),vs(t,r.content,`utf-8`),i.add(r.path)}catch(e){t.push({path:r.path,cause:e}),bq.warn({path:r.path,err:e},`Failed to restore path ${r.path}`)}if(t.length>0){let e=t.map(e=>e.path).join(`, `);bq.warn({failed:e},`Recovery incomplete; keeping journal for retry (${e})`);let n=t.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(n,`Managed rename recovery incomplete; failed to restore paths: ${e}`)}}let o=n.version===2?Iq(n):Fq(n),s=[];for(let t of o){if(r.has(t))continue;let n=cN(t,e);try{ps(n,{force:!0}),Rq(n,e)}catch(e){B(n)&&bq.warn({destination:t},`Both source and destination files exist after partial recovery for ${t}`),bq.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination ${t}`),s.push({destination:t,cause:e})}}if(n.version===2)for(let t of n.cleanupPaths??[]){if(i.has(t))continue;let n=null;try{n=Lq(e,t),ps(n,{force:!0}),Rq(n,e)}catch(e){n&&B(n)&&bq.warn({destination:t},`Both source and destination paths exist after partial recovery for ${t}`),bq.warn({destination:t,err:e},`Recovery incomplete; failed to clean destination path ${t}`),s.push({destination:t,cause:e})}}if(s.length>0){let e=s.map(e=>e.destination).join(`, `),t=s.map(e=>e.cause instanceof Error?e.cause:Error(String(e.cause)));throw AggregateError(t,`Managed rename recovery incomplete; failed to clean destinations: ${e}`)}return Nq(t),{recovered:!0,journal:n,restoredDocNames:[...r].sort((e,t)=>e.localeCompare(t))}}const Bq=F(`rename-log`);let Vq=null;function Hq(){return Vq||=xs().createUpDownCounter(`rename.log_entries_total`,{description:`Live rename-log entry count after each append / GC pass`}),Vq}let Uq=null;function Wq(){return Uq||=xs().createCounter(`rename.log_gc_dropped_total`,{description:`Cumulative count of rename-log entries dropped by reachability GC`}),Uq}const Gq=5*1024*1024,Kq=4*1024;function qq(){return{byTo:new Map,byFrom:new Map}}function Jq(e){return z(e,`renames.jsonl`)}function Yq(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||typeof t.from!=`string`||t.from.length===0||typeof t.to!=`string`||t.to.length===0||t.from===t.to||typeof t.at!=`string`||t.at.length===0||typeof t.commitSha!=`string`||t.commitSha!==``&&!/^[0-9a-f]{40}$/.test(t.commitSha)||typeof t.branch!=`string`||t.branch.length===0||typeof t.groupId!=`string`||t.groupId.length===0||t.kind!==`file`&&t.kind!==`folder`||t.actor===null||typeof t.actor!=`object`)return null;let n=t.actor;return typeof n.writerId!=`string`||n.writerId.length===0||typeof n.displayName!=`string`?null:{v:1,from:t.from,to:t.to,at:t.at,commitSha:t.commitSha,branch:t.branch,groupId:t.groupId,kind:t.kind,actor:{writerId:n.writerId,displayName:n.displayName}}}function Xq(e,t){let n=e.byFrom.get(t.from);if(!n)return;let r=n.filter(e=>e!==t);r.length===0?e.byFrom.delete(t.from):e.byFrom.set(t.from,r)}function Zq(e,t){e.byTo.delete(t.to),Xq(e,t)}function Qq(e,t){let n=e.byTo.get(t.to);n&&Xq(e,n),e.byTo.set(t.to,t);let r=e.byFrom.get(t.from);r?r.push(t):e.byFrom.set(t.from,[t])}function $q(e){let t=qq(),n=Jq(e);if(!B(n))return t;let r;try{r=V(n,`utf-8`)}catch(e){return Bq.warn({path:n,err:e},`[rename-log] WARN: failed to read ${n}, treating as empty`),t}if(r.length===0)return t;let i=r.split(`
@@ -1221,7 +1221,7 @@ tags: [lore, history]
1221
1221
  `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{X.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),Fe.release(ai))}),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()),Fe.release(ai))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),Fe.release(ai))})}let Xi=`local-op-auth-signout`,Zi=q(Aa,async(e,t,n)=>{let r=n.host??pi();if(!Fe.tryAcquire(oi)){K(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Xi,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=oe,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=jl(e,i,fN({...Ur,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),J(t,200,ti,{},{handler:Xi})}catch(e){K(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Xi,cause:e})}finally{Fe.release(oi)}},{handler:Xi,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Xi})}),Qi=`/api/local-op/auth/set-identity`,ra=`local-op-auth-set-identity`,ia=q(Uee,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!j){K(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:ra});return}if(!Fe.tryAcquire(Qi)){K(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:ra,extraHeaders:{"Retry-After":`5`}});return}try{PB(j,r,i),ae?.()?.refreshIdentity().catch(()=>{}),J(t,200,ti,{},{handler:ra})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:ra,cause:e})}finally{Fe.release(Qi)}},{handler:ra,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ra})});async function oa(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=ae?.();if(!e){J(t,200,Eo,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),J(t,200,Eo,e.getStatus(),{handler:`sync-status`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let ga=q(Pee,async(e,t,n)=>{let r=ae?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;J(t,202,Ate,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?ae?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function _a(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=ae?.();J(t,200,Bi,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let va=q(Xr,async(e,t,n)=>{let r=ae?.();if(!r){K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),J(t,200,Ste,{},{handler:`sync-resolve-conflict`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?ae?.()?!0:(K(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function ya(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!j){K(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){K(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let a=Vx(i),o=s.documents.get(a)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=ae?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!o&&!l){K(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=Ns({baseDir:j,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),a=Vx(i),o=s.documents.get(a),c=``,l=!1,u=null;if(o){let e=o.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Se?Se(a):null;t!==null&&(c=t,l=!0)}else{CL(L(j,i),j);try{c=V(L(j,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;J(t,200,Ji,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),a=e.present?e.content:``,o=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=Vx(i),t=s.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=Se?Se(e):null;t!==null&&!fge(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else X.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}J(t,200,Ji,{file:i,base:a,ours:l,theirs:o,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function ba(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=nY(a);if(a!==null&&a!==``&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,Zee,{plan:await vY({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof WJ){K(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof GJ){K(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let Sa=q(Vee,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){K(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=nY(a);if(typeof a==`string`&&a.length>0&&o===void 0){K(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{J(t,200,Mi,{result:await pY(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function Ca(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}J(t,200,cte,{packs:iY()},{handler:`seed-packs`})}}let wa=q(Kee,async(e,t,n)=>{if(n.out!==void 0&&!$G(n.out)){K(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{J(t,200,bte,await II({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function Ta(e,t){if(r(e,t,{handler:`installed-agents`}))try{await ude(e,t,qe.probeAll)}catch(n){t.headersSent||(X.error({err:n,requestId:cS(e)},`[installed-agents] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}function Ea(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return K(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(l),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${Vl}`)?(K(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}function Da(e,t,n=`template`){return!e||!Fr.test(e)?(K(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Oa(e,t,n){let r=t===``?[]:t.split(`/`);for(let t=r.length;t>=0;t--){let i=t===0?``:r.slice(0,t).join(`/`),a=i===``?e:z(e,i);if(a!==e&&!a.startsWith(`${e}${Vl}`))continue;let o=z(a,`.ok`,`templates`,`${n}.md`);if(B(o))return{abs:o,folder:i,scope:t===r.length?`local`:`inherited`}}return null}function ka(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 ja=PW({GET:q(Zt,async(e,t)=>{try{let n=Ea(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await iA(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,CD.parse)(await _u(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);X.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}J(t,200,We,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Si,async(e,t,n)=>{try{if(Ae){K(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=Ea(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=uA({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(In(e,Pn(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await Ln(`folder-config-put`))}J(t,200,gte,{applied:i},{handler:`folder-config-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`}),Ma=q(Zt,async(e,t)=>{try{let{entries:e,truncated:n}=Qfe({homedirOverride:de});J(t,200,vt,{themes:e,truncated:n},{handler:`saved-themes-list`})}catch(e){K(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}),Na=q(ut,async(e,t,n)=>{try{let e=await tpe({name:n.name,stem:n.stem,scheme:n.scheme,extension:n.extension,homedirOverride:de,lockTimeoutMs:pe});if(!e.ok){if(e.code===`lock-timeout`){K(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`){K(t,409,`urn:ok:error:theme-name-taken`,`A saved theme with that name already exists.`,{handler:`saved-theme-save`,detail:n.name});return}K(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}J(t,201,Tte,{id:e.id,filename:e.filename},{handler:`saved-theme-save`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to save theme.`,{handler:`saved-theme-save`,cause:e})}},{handler:`saved-theme-save`,method:`POST`}),Fa=q(Zt,async(e,t)=>{try{let n=ec(e).get(`id`)??``;if(n===``){K(t,400,`urn:ok:error:invalid-request`,`Missing theme id.`,{handler:`saved-theme-delete`});return}let r=await rpe({id:n,homedirOverride:de,lockTimeoutMs:pe});if(!r.ok){if(r.code===`lock-timeout`){K(t,503,`urn:ok:error:concurrent-operation`,`Saved themes are temporarily busy.`,{handler:`saved-theme-delete`,detail:r.code,extraHeaders:{"Retry-After":`5`}});return}K(t,r.code===`invalid-id`?400:409,`urn:ok:error:invalid-request`,`Cannot delete saved theme.`,{handler:`saved-theme-delete`,detail:r.code});return}J(t,200,xee,r.existed?{existed:!0,filename:r.filename,scheme:r.scheme}:{existed:!1},{handler:`saved-theme-delete`})}catch(e){K(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}),Ia=PW({POST:Na,PUT:q(Cee,async(e,t,n)=>{try{let e=await npe({id:n.id,scheme:n.scheme,homedirOverride:de,lockTimeoutMs:pe});if(!e.ok){if(e.code===`lock-timeout`){K(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`){K(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`){K(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}K(t,400,`urn:ok:error:invalid-request`,`Not a saved theme id.`,{handler:`saved-theme-update`,detail:e.code});return}J(t,200,Tt,{id:e.id,filename:e.filename},{handler:`saved-theme-update`})}catch(e){K(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:Fa},{handler:`saved-theme`});function La(e,t,n){let r=s.documents.get(e);return r&&mS(r)?(_S(n,new gS({file:`${e}.md`}),t),!0):!1}function Ra(e,t,n){let r=s.documents.get(e);return r&&mS(r)?(_S(n,new gS({file:`${e}.md`}),t),!0):!1}let za=q(Zt,iV(async(e,t)=>{let n=await Ak(z(l));J(t,200,rte,{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}),Ba=e=>{let{body:t}=jt(e);return{frontmatter:Re(e)??{},body:t}},Va=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Da(r,t,`template-get`))return;let i=Ea(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Oa(o,a,r);if(!s){K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=$n(await _u(c,`utf-8`)),f=d.identity,p=d.starterContent;J(t,200,Ve,{template:{name:r,folder:l,scope:u,path:R(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ha=q(na,async(e,t,n)=>{try{if(Ae){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!Da(r,t,`template-put`))return;let i=Ea(n.folder,t,`folder`,`template-put`);if(!i||La(xo(i.folderRel,r),`template-put`,t))return;let a=VA({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:ka(n.frontmatter)});if(!a.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),s=!B(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=xo(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=Tn(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Fb(h.dc.document,a.content,`agent`)},h.origin);let g=await At(u);if(g?.kind===`failure`){Mt(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){Nt(t,`template-put`);return}Jt(u,a.content),In(e,Pn(`template`,i.folderRel,r),`${s?`template-create`:`template-edit`}: ${l}`),await Ln(`template-put`),J(t,200,jee,{path:l,created:s,warnings:a.warnings},{handler:`template-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ua=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Da(r,t,`template-delete`))return;let i=Ea(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=$a(n,ue);if(a.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(La(xo(i.folderRel,r),`template-delete`,t))return;await tn([xo(i.folderRel,r)],`deleted-upstream`);let o=UA({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!o.ok){let e=o.error.code===`WRITE_ERROR`||o.error.code===`UNLINK_FAILED`||o.error.code===`BAD_PROJECT_DIR`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:o.error.code,cause:Error(o.error.message)});return}o.existed&&(In(a,Pn(`template`,i.folderRel,r),`template-delete: ${o.path}`),await Ln(`template-delete`),xe?.setDeleted(xo(i.folderRel,r))),J(t,200,Vn,{existed:o.existed,path:o.path},{handler:`template-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ga=PW({GET:Va,PUT:Ha,POST:q(ete,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!Da(n.fromName,t,`template-move`)||!Da(n.toName,t,`template-move`))return;let r=Ea(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=Ea(n.toFolder,t,`folder`,`template-move`);if(!i||La(xo(r.folderRel,n.fromName),`template-move`,t))return;await tn([xo(r.folderRel,n.fromName)],`renamed`);let a=await GA({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await pQ(j,e,t);return n||fQ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Oa(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){K(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}K(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}xe?.setDeleted(xo(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=vo(V(z(i.resolvedContentDir,a.toPath),`utf-8`))}catch{e=null}if(e===null)o={code:`READ_FAILED`,message:`could not read the moved template to apply the metadata change; the move succeeded with the original content intact — retry the edit`};else{let t=HA({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:ka(n.frontmatter)});t.ok||(o=t.error)}}try{Jt(xo(i.folderRel,n.toName),V(z(i.resolvedContentDir,a.toPath),`utf-8`))}catch{}if(In(e,Pn(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await Ln(`template-move`),A?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}J(t,200,fte,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ua},{handler:`template`}),Ka=q(wi,async(e,t,n)=>{try{if(Ae){K(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!hQ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=pt(r);if(Zx(i)||Qx(i)){K(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let a=QZ(l,`file`,i);if(!B(a)){K(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let o=s.documents.get(i);if(n.deleteSource){let e=ae?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=o!==void 0&&mS(o),a=n.has(r);if(i||a){_S(t,new gS({file:r}),`template-import`);return}}let u=``;if(o)u=o.getText(`source`).toString();else{let e=await s.openDirectConnection(i);try{let n=e.document;if(!n){K(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=$Z(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!Da(d,t,`template-import`))return;let f=Ea(n.targetFolder,t,`folder`,`template-import`);if(!f||La(xo(f.folderRel,d),`template-import`,t))return;let{frontmatter:p,body:m}=jt(u),g=Xt(p),_={};try{g.trim()&&(_=(0,CD.parse)(g))}catch{}let v=n.title||_?.title||sk(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,CD.stringify)(x).trim()}\n`),S=S?`---\n${S}---\n${m}`:m;let C=VA({name:d,body:S,frontmatter:{title:v,description:y,tags:b}});if(!C.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:C.error.code,cause:Error(C.error.message)});return}let w=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),T=!B(w),E=R(f.resolvedContentDir,w).split(/[\\/]/).filter(Boolean).join(`/`),ee=xo(f.folderRel,d),{agentId:te,agentName:D,colorSeed:O,clientName:k}=Tn(n),ne=await c.getSession(ee,te,{displayName:D,colorSeed:O,clientName:k});ne.dc.document.transact(()=>{Fb(ne.dc.document,C.content,`agent`)},ne.origin);let re=await At(ee);if(re?.kind===`failure`){Mt(t,re.failure,`template-import`);return}if(re?.kind===`divergence`){Nt(t,`template-import`);return}Jt(ee,C.content),In(e,Pn(`template`,f.folderRel,d),`template-import: ${E}`),n.deleteSource&&(await tn([i],`deleted-upstream`),xe&&xe.setDeleted(i),is(a),h?.({kind:`delete`,path:a,docName:i})),await Ln(`template-import`),A?.(`files`),J(t,200,_te,{path:E,created:T,warnings:C.warnings},{handler:`template-import`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function qa(e,t,n){return!e||e.length>64||!Wa.test(e)?(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Ja(e,t,n){let r=Jn.safeParse(e??`project`);return r.success?r.data:(K(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Ya=de??uu(),Xa=Bhe({contentDir:l,skillsHome:Ya,effectiveInstallMode:co});function Za(e){return z(e===`global`?Ya:l,`.ok`,`skills`)}function Qa(e,t,n){let r=z(Za(e),t);if(e===`global`){if(n!==void 0){let e=bL(Ya).find(e=>e.name===t&&e.hosts.includes(n));return e?z(Ya,e.dir):null}let e=xL(Ya,t);return e===null?B(L(r,`SKILL.md`))?r:null:e}let i=yL(l).find(e=>e.name===t&&(n===void 0||e.hosts.includes(n)));return i?z(l,i.dir):n===void 0&&B(L(r,`SKILL.md`))?r:null}function $a(e,t){let n=e.searchParams;return OD({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 eo(e,t){let n=e===`project`?j:Ya;if(!n)return`symlink`;try{return os(L(n,...zE)).skills[t]===void 0?`symlink`:`copy`}catch{return`symlink`}}function to(e){let t=e===`project`?j:Ya;return t?L(t,...zE):null}function ro(e,t,n,r={}){let i=to(e);return i?FJ(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 ao(e,t,n){let r=to(e),i=to(t);if(!r||!i)return!1;let a=NJ(r).skills[n];if(!a)return!1;let o={...a};return t===`global`&&delete o.baselineRef,await FJ(i,e=>({...e,skills:{...e.skills,[n]:o}})),await FJ(r,e=>{let t={...e.skills};return delete t[n],{...e,skills:t}}),!0}function oo(e,t,n){let r=to(e);return r?FJ(r,e=>{let r=e.skills[t];return r?{...e,skills:{...e.skills,[t]:{...r,...n}}}:e}):Promise.resolve()}function so(e,t,n){let[r,i]={"no-shadow":[409,`urn:ok:error:shadow-not-configured`],"version-not-found":[404,`urn:ok:error:not-found`],"skill-absent":[404,`urn:ok:error:not-found`],"io-error":[500,`urn:ok:error:storage-error`],"path-escape":[500,`urn:ok:error:path-escape`]}[t.code];K(e,r,i,t.error,{handler:n,detail:t.code})}function co(e,t,n){let r=e===`project`?j:Ya;return(r?Rhe(r,t):void 0)||(n.hosts.length-1<=0||n.linkedHosts.some(e=>n.hosts.includes(e))?`link`:`copy`)}function lo(e){let t=Qa(`project`,e);return t?R(l,t).split(Vl).join(`/`):`${sr}/${e}`}let fo=rI.project;function po(e,t,n){let r=[],i=null,a=[...Pa.map(e=>({id:e,root:io[e]??``})),{id:`agents`,root:vr}];for(let{id:o,root:s}of a){if(!s)continue;let a=z(e,...s.split(`/`),t);B(z(a,`SKILL.md`))&&(r.push(o),(n===void 0?i===null:o===n)&&(i=a))}if(i===null)return null;let o=z(i,`SKILL.md`);return{dir:i,skillMd:o,hosts:r,relPath:R(e,o).split(/[\\/]/).filter(Boolean).join(`/`)}}function ho(e){let t=Rle(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 go(e,t){if(!aI(t))return null;let n=po(e,t);if(!n)return null;let r=JE(n.dir)?.contentHash??``,i;try{i=ou(n.skillMd).mtime.toISOString()}catch{i=new Date(0).toISOString()}return{source:Wt,skill:t,contentHash:r,autoUpdate:!1,importedAt:i}}function _o(e,t,n){let r=po(e,t);if(!r)return null;let i;try{let{frontmatter:e}=Ba(V(r.skillMd,`utf-8`));typeof e.description==`string`&&(i=e.description)}catch{}let a=go(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:ho(a)}:{}}}function bo(e,t,n){return aI(e)?(K(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is one of OpenKnowledge's runtime skills — its content is read-only in-app (updates arrive via reimport). Duplicate it under a new name to make your own version.`,{handler:n}),!0):!1}function xo(e,t){return Po(e,t)}function So(e){return e===`navigation`||e===`relevance`?e:void 0}function Co(e,t){return R(t===`global`?Ya:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function Do(e){return e===`global`?Ya:j}async function Oo(e,t,n,r={}){let i=await VN(e,t),a=n===`project`?l:Ya;if(r.purge!==void 0){eL(t,e,Pa,HI(n));for(let e of ome(a,n,t,r.purge.contentHash))ps(e,{recursive:!0,force:!0});return i!==null}if(!B(z(Za(n),t,`SKILL.md`))){let r=(n===`project`?yL(l):bL(Ya)).find(e=>e.name===t);if(r){let a=n===`project`?l:Ya,o=z(a,r.dir),s=z(a,`.agents`,`skills`),c=L(s,t);if(B(s)&&!B(L(c,`SKILL.md`))){let e=!1;try{e=H(o)===H(c)}catch{e=!1}e||fs(o,c,{recursive:!0,dereference:!0})}return $I({canonicalAbs:B(L(c,`SKILL.md`))?c:o,canonicalHash:r.contentHash,name:t,cwd:e,targets:[...Pa],roots:HI(n)}),i!==null}}return eL(t,e,Pa,HI(n)),i!==null}function ko(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=tu(e,{withFileTypes:!0})}catch(r){return F(`skills`).warn({err:r,skillsRoot:e,scope:t},`failed to read skills root — returning empty skills list`),{skills:n,truncated:!1}}let i=!1;for(let a of r.sort((e,t)=>e.name.localeCompare(t.name))){if(!a.isDirectory()||!Wa.test(a.name))continue;if(n.length>=500){i=!0;break}let r=z(e,a.name,`SKILL.md`);if(!B(r))continue;let o;try{let{frontmatter:e}=Ba(V(r,`utf-8`));typeof e.description==`string`&&(o=e.description)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Co(r,t),absolutePath:r})}return{skills:n,truncated:i}}function Ao(e){return`!/${I(e).split(Vl).join(`/`)}/`}let Mo=q(nee,iV(async(e,t,n)=>{if(!qa(n.name,t,`skill-track-in-git`))return;if(n.scope!==`project`){K(t,400,`urn:ok:error:invalid-request`,`Only project skills live in the repository; a global skill is outside any .gitignore.`,{handler:`skill-track-in-git`});return}if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project directory.`,{handler:`skill-track-in-git`});return}let r=yL(l).find(e=>e.name===n.name)?.dir??`.ok/skills/${n.name}`,i=HZ(z(l,r,`SKILL.md`),l)??`${r}/SKILL.md`,a=I(i),o=i,s=Ao(a),c=`.gitignore`,u=z(l,c);if(M&&!M.isPathIgnored(o)){J(t,200,dr,{line:s,gitignorePath:c,applied:!1,alreadyTracked:!0},{handler:`skill-track-in-git`});return}if(n.apply!==!0){J(t,200,dr,{line:s,gitignorePath:c,applied:!1},{handler:`skill-track-in-git`});return}let d=B(u)?V(u,`utf-8`):null;if((d??``).split(`
1222
1222
  `).some(e=>e.trim()===s)){K(t,409,`urn:ok:error:invalid-request`,`"${s}" is already in ${c}, but ${o} is still ignored — another rule excludes it.`,{handler:`skill-track-in-git`});return}if(cu(u,`${d===null||d.endsWith(`
1223
1223
  `)||d===``?d??``:`${d}\n`}${s}\n`,`utf-8`),await M?.rebuildIgnorePatterns(),M?.isPathIgnored(o)){d===null?iu(u,{force:!0}):cu(u,d,`utf-8`),await M.rebuildIgnorePatterns(),K(t,409,`urn:ok:error:invalid-request`,`Adding "${s}" did not make ${o} trackable — another .gitignore rule excludes a parent directory. ${c} was left unchanged.`,{handler:`skill-track-in-git`});return}A?.(`files`),J(t,200,dr,{line:s,gitignorePath:c,applied:!0},{handler:`skill-track-in-git`})},{handler:`skill-track-in-git`,title:`Failed to update .gitignore.`}),{handler:`skill-track-in-git`,method:`POST`}),Fo={lastKey:null},Io=q(Zt,iV(async(e,t)=>{let n=Za(`project`),r=ko(n,`project`),i=ko(Za(`global`),`global`),a=[...Pa],o=FI(Ya).map(e=>e.editorId),s=j?RN(j).skills:{},c=RN(Ya).skills,u=j?VE(B(L(j,...zE))?V(L(j,...zE),`utf-8`):``)??null:null,d=ho,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&&ss(n,e.name)!==a.localHash,c=a?.baselineRef!==void 0;return{...e,installed:i.length>0,hosts:i,...o?{origin:o}:{},...s?{modified:!0}:{},...c?{revertable:!0}:{}}}),p=j?qX(j):{},m=(e,t,n)=>{let r=[];for(let i of t??[]){let t=z(e,i.path);if(n!==void 0&&t===z(n))continue;let a=!1;try{a=Yl(t).isSymbolicLink()}catch{continue}if((a?`link`:`copy`)!==i.mode){if(a&&n!==void 0)try{if(H(t)===H(n))continue}catch{}r.push(i.path)}}return{drift:r}},h=j?dL(l,`project`):{},g=hL(h,`project`),_=(e,t)=>[...t].some(t=>e===t||e.startsWith(`${t}/`)),v=mL(`project`),y=mL(`global`),b=(e,t)=>(e??[]).filter(e=>![...t].some(t=>e.path===t||e.path.startsWith(`${t}/`))),x=new Set,S=j?yL(l).map(e=>{let t=!x.has(e.name);x.add(e.name);let n=t?u?.skills[e.name]??go(l,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:z(l,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:a,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(h).length>0?{hostAliases:h}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let n=b(t?p[e.name]:void 0,g).filter(e=>!_(e.path,v));return n.length?{customPlacements:n.map(e=>({path:e.path,mode:e.mode}))}:{}})(),...(()=>{let n=m(j,b(t?p[e.name]:void 0,g),z(l,e.dir));return n.drift.length>0?{driftPaths:n.drift}:{}})(),...co(`project`,e.name,e)===`link`?{linkMode:!0}:{},...r?{origin:r}:{},...i?{modified:!0}:{},...n?.baselineRef===void 0?{}:{revertable:!0},...aI(e.name)?{managed:!0}:{}}}):[],C=qX(Ya),w=os(L(Ya,...zE)),T=dL(Ya,`global`),E=hL(T,`global`),ee=new Set(bL(Ya).map(e=>e.name));i.skills=i.skills.filter(e=>!ee.has(e.name));let te=new Set,D=bL(Ya).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:z(Ya,e.dir,`SKILL.md`),installed:!0,hosts:[...e.hosts],installableEditors:o,...e.linkedHosts.length>0?{symlinkedHosts:[...e.linkedHosts]}:{},...Object.keys(T).length>0?{hostAliases:T}:{},...e.conflictHosts.length>0?{conflictHosts:[...e.conflictHosts]}:{},...(()=>{let t=m(Ya,b(n,E),z(Ya,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}))}:{}})(),...co(`global`,e.name,e)===`link`?{linkMode:!0}:{},...aI(e.name)?{managed:!0}:{},...(()=>{if(!t)return{};let n=w.skills[e.name]??go(Ya,e.name);return n?{origin:d(n),...n.localHash!==void 0&&e.contentHash!==n.localHash?{modified:!0}:{}}:{}})()}}),O=new Set(S.map(e=>e.name)),k=j&&!r.skills.some(e=>e.name===fo)&&!O.has(fo)?_o(j,fo,`project`):null,A=new Set(D.map(e=>e.name)),ne=cI.map(e=>rI[e]).filter(e=>!i.skills.some(t=>t.name===e)&&!A.has(e)).map(e=>_o(Ya,e,`global`)).filter(e=>e!==null),re=new Set(S.map(e=>e.name)),ie={skills:[...f(r,s,!0).filter(e=>!re.has(e.name)),...S,...f(i,c,!1),...D,...k?[k]:[],...ne].map(e=>{let t=e.scope===`project`&&e.absolutePath?HZ(e.absolutePath,l):null,n=t===null||t===e.path?e:{...e,canonicalPath:t},r=t??e.path;return e.scope===`project`&&M?.isPathIgnored(r)===!0?{...n,ignored:!0}:n}),truncated:r.truncated||i.truncated};await mge(S.map(e=>e.path),M??null,Fo),J(t,200,nn,ie,{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Lo=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!qa(r,t,`skill-get`))return;let i=Ja(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(aI(r)){let e=i===`global`?Ya:j,a=e?po(e,r,n.searchParams.get(`host`)??void 0):null;if(a){let{frontmatter:e,body:n}=Ba(await _u(a.skillMd,`utf-8`));J(t,200,wo,{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:nL(a.dir),managed:!0}},{handler:`skill-get`});return}}let a=n.searchParams.get(`host`)??void 0,o=Qa(i,r,a);if(o===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:a===void 0?`Skill "${r}" not found in ${i} scope.`:`No skill "${r}" (${i}) in ${a}.`});return}let s=z(o,`SKILL.md`),{frontmatter:c,body:l}=Ba(await _u(s,`utf-8`));J(t,200,wo,{skill:{name:r,scope:i,path:Co(s,i),frontmatter:{name:typeof c.name==`string`?c.name:r,description:typeof c.description==`string`?c.description:``},body:l,files:nL(o)}},{handler:`skill-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0});async function Ro(e,t){if(!(!k||rS(e))){if(M)try{await M.rebuildIgnorePatterns()}catch{}await Vt(e,t,`skill-put`)}}let zo=q(Je,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!qa(n.name,t,`skill-put`)||bo(n.name,t,`skill-put`))return;let r=_A({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=n.scope===`project`?l:Ya,a=Qa(n.scope,n.name);if(a===null){let a=gL(i,n.scope),o=vA({skillsRoot:z(i,a),name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!o.ok){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:o.error.code,cause:Error(o.error.message)});return}n.scope===`project`&&(In(e,`${a}/${n.name}/SKILL`,`skill-create: ${a}/${n.name}/SKILL.md`),await Ln(`skill-put`)),await Ro(n.scope===`project`?`${a}/${n.name}/SKILL`:Zn(`global`,n.name),r.content),A?.(`files`),J(t,200,sa,{path:`${a}/${n.name}/SKILL.md`,created:!0,warnings:[...r.warnings,...o.warnings]},{handler:`skill-put`});return}let o=R(i,a).split(Vl).join(`/`),s=`${o}/SKILL.md`,u=n.scope===`project`?`${o}/SKILL`:Zn(n.scope,n.name);if(Ra(u,`skill-put`,t))return;let{agentId:d,agentName:f,colorSeed:p,clientName:m}=Tn(n),h=await c.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{Fb(h.dc.document,r.content,`agent`)},h.origin);let g=await At(u);if(g?.kind===`failure`){Mt(t,g.failure,`skill-put`);return}if(g?.kind===`divergence`){Nt(t,`skill-put`);return}n.scope===`project`&&(In(e,Pn(`skill`,``,n.name),`skill-edit: ${s}`),await Ln(`skill-put`)),await Ro(u,r.content),A?.(`files`),J(t,200,sa,{path:s,created:!1,warnings:r.warnings},{handler:`skill-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`});function Bo(e,t){let n=e===`project`?l:Ya,r=Qa(e,t);return{root:r===null?Za(e):I(r),dirRel:r===null?`.ok/skills/${t}`:R(n,r).split(Vl).join(`/`),realDir:r}}function Vo(e,t){let n=e===`project`?l:Ya,r=(e===`project`?yL(l):bL(Ya)).find(e=>e.name===t);r&&$I({canonicalAbs:z(n,r.dir),canonicalHash:r.contentHash,name:t,cwd:n,targets:r.hosts.filter(e=>fi(e)),roots:HI(e)})}let Ho=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!qa(r,t,`skill-delete`))return;let i=Ja(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let{root:a,dirRel:o}=Bo(i,r),s=$a(n,ue);if(s.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await tn(i===`project`?[...new Set([`${o}/SKILL`,Zn(i,r)])]:[Zn(i,r)],`deleted-upstream`),Vo(i,r);let c=wA({skillsRoot:a,name:r}),l=Za(i);if(c.ok&&l!==a&&B(z(l,r,`SKILL.md`))){let e=wA({skillsRoot:l,name:r});e.ok||X.warn({name:r,scope:i,detail:e.error.code},`[skill-delete] legacy store resident survived the delete`)}if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(In(s,o,`skill-delete: ${o}`),await Ln(`skill-delete`)),A?.(`files`));let u=Do(i);u&&await Oo(u,r,i),J(t,200,mte,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),Uo=q(Ct,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!qa(n.fromName,t,`skill-move`)||!qa(n.toName,t,`skill-move`)||bo(n.toName,t,`skill-move`))return;let{root:r,dirRel:i}=Bo(n.scope,n.fromName);if(Qa(n.scope,n.toName)!==null){K(t,409,`urn:ok:error:doc-already-exists`,`A skill named "${n.toName}" already exists.`,{handler:`skill-move`});return}let a=Do(n.scope),o=a?RN(a).skills[n.fromName]:void 0,s=n.scope===`project`?l:Ya,c=(n.scope===`project`?yL(l):bL(Ya)).find(e=>e.name===n.fromName),u=c?I(c.dir):null,d=u===null?[]:Object.entries(dL(s,n.scope)).filter(([,e])=>e===u).map(([e])=>e),f=[...new Set([...o?RI(o.hosts):[],...c?RI(c.hosts):[],...RI(d)])];await tn(n.scope===`project`?[...new Set([`${i}/SKILL`,Zn(n.scope,n.fromName)])]:[Zn(n.scope,n.fromName)],`renamed`),Vo(n.scope,n.fromName);let p=await TA({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await pQ(j,e,t);return n||fQ(e,t),n}});if(!p.ok){if(p.error.code===`SKILL_NOT_FOUND`){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:p.error.message});return}if(p.error.code===`SKILL_EXISTS`){K(t,409,`urn:ok:error:doc-already-exists`,p.error.message,{handler:`skill-move`,detail:p.error.code});return}let e=p.error.code===`MOVE_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:p.error.code,cause:Error(p.error.message)});return}let m=null,h=z(r,n.toName,`SKILL.md`),g=``,_=``;try{let e=Ba(V(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=vA({skillsRoot:r,name:n.toName,body:v,frontmatter:{name:n.toName,description:y}});b.ok||(m=b.error);let x=[];if(!m)try{x=dme({base:n.scope===`project`?l:Ya,scope:n.scope,fromName:n.fromName,toName:n.toName})}catch(e){F(`skill-move`).warn({err:e,fromName:n.fromName,toName:n.toName},`skill-ref rewrite failed — rename succeeded, refs to the old name are left as authored`)}if(n.scope===`project`&&!m)try{await M?.rebuildIgnorePatterns(),await es(r,n.fromName,n.toName),await ts(x,n.toName)}catch(e){F(`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=Co(z(r,n.fromName),n.scope),C=Co(z(r,n.toName),n.scope);n.scope===`project`&&(In(e,Pn(`skill`,``,n.toName),`skill-rename: ${S} -> ${C}`,[{from:S,to:C}]),await Ln(`skill-move`));let w=ss(r,n.toName),T=n.scope===`project`?await cs(us(e),C):void 0;if(await ro(n.scope,n.fromName,n.toName,{localHash:w,...n.scope===`project`?{baselineRef:T}:{}}),a){await VN(a,n.fromName),eL(n.fromName,a,f,HI(n.scope));let e=z(r,n.toName);if(f.length>0){let t=qI(e,n.toName,a,f,eo(n.scope,n.toName),HI(n.scope));await BN(a,n.toName,{...o,scope:n.scope,hosts:t,scripts:o?.scripts??BI(e,n.toName).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}}if(A?.(`files`),m){let e=m.code===`WRITE_ERROR`;K(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:m.code,cause:Error(m.message)});return}J(t,200,ma,{from:S,to:C,committed:p.committed},{handler:`skill-move`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),Wo=q(yte,async(e,t,n)=>{let{name:r,home:i}=n;if(!qa(r,t,`skill-edit-external`))return;let a;try{a=H(i)}catch{K(t,404,`urn:ok:error:not-found`,`Skill directory not found.`,{handler:`skill-edit-external`,detail:`HOME_NOT_FOUND`});return}if(!ou(a).isDirectory()||!B(z(a,`SKILL.md`))){K(t,400,`urn:ok:error:invalid-request`,`Not a skill directory (no SKILL.md).`,{handler:`skill-edit-external`});return}Tz(r,a),J(t,200,zee,{docName:Ze(r)},{handler:`skill-edit-external`})},{handler:`skill-edit-external`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`skill-edit-external`})}),Ko=q(gt,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move-scope`});return}let{name:r,fromScope:i,toScope:a}=n;if(!qa(r,t,`skill-move-scope`))return;if(i===a){K(t,400,`urn:ok:error:invalid-request`,`Source and destination scope are the same.`,{handler:`skill-move-scope`});return}if(a===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot move to project scope — no project root is resolved for this server.`,{handler:`skill-move-scope`,detail:`NO_PROJECT_ROOT`});return}let{root:o,dirRel:s,realDir:c}=Bo(i,r),u=z(o,r),d=(()=>{try{return H(u)}catch{return u}})(),f=a===`project`?l:Ya,p=z(f,gL(f,a)),m=z(p,r);if(c===null||!B(u)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move-scope`,detail:`Skill "${r}" not found in ${i} scope.`});return}if(z(c)===z(m)||B(m)&&H(c)===H(m)){K(t,409,`urn:ok:error:doc-already-exists`,`The source and destination resolve to the same skill directory.`,{handler:`skill-move-scope`,detail:`SAME_STORAGE`});return}if(Qa(a,r)!==null||B(m)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${a} skill named "${r}" already exists.`,{handler:`skill-move-scope`});return}let h=Do(i),g=Do(a),_=h?RN(h).skills[r]:void 0,v=i===`project`?l:Ya,y=(i===`project`?yL(l):bL(Ya)).find(e=>e.name===r),b=y?I(y.dir):null,x=b===null?[]:Object.entries(dL(v,i)).filter(([,e])=>e===b).map(([e])=>e),S=[...new Set([..._?RI(_.hosts):[],...y?RI(y.hosts):[],...RI(x)])];await tn([...new Set([...i===`project`?[`${s}/SKILL`]:[],Zn(i,r),Zn(a,r)])],`renamed`),ls(p,{recursive:!0}),fs(d,m,{recursive:!0,dereference:!0}),Vo(i,r);let C=wA({skillsRoot:o,name:r});if(C.ok&&d!==u){let e=R((()=>{try{return H(v)}catch{return v}})(),d);e!==``&&!e.startsWith(`..`)&&!Ll(e)&&ps(d,{recursive:!0,force:!0})}if(!C.ok){wA({skillsRoot:p,name:r}),K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill (source removal failed); rolled back the copy.`,{handler:`skill-move-scope`,detail:C.error.code,cause:Error(C.error.message)});return}let w=await ao(i,a,r);if(h&&await Oo(h,r,i,y?{purge:{contentHash:y.contentHash}}:{}),h&&await zhe(h,r),g&&S.length>0){let e=qI(m,r,g,S,eo(a,n.name),HI(a));await BN(g,r,{..._,scope:a,hosts:e,scripts:_?.scripts??BI(m,r).hasScripts,installedAt:_?.installedAt??new Date().toISOString()})}if((i===`project`||a===`project`)&&(In(e,i===`project`?s:R(l,m).split(Vl).join(`/`),`skill-move-scope: ${i} -> ${a} ${r}`),await Ln(`skill-move-scope`)),w){let t=ss(p,r),n=a===`project`?await cs(us(e),R(l,m).split(Vl).join(`/`)):void 0;await oo(a,r,{localHash:t,...a===`project`?{baselineRef:n}:{}})}if(!B(L(m,`SKILL.md`))){K(t,500,`urn:ok:error:internal-server-error`,`The move did not leave a readable skill at the destination; nothing was reported as moved.`,{handler:`skill-move-scope`,detail:R(f,m).split(Vl).join(`/`)});return}await M?.rebuildIgnorePatterns(),A?.(`files`),J(t,200,mee,{scope:a,path:R(f,m).split(Vl).join(`/`)},{handler:`skill-move-scope`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill across scopes.`,{handler:`skill-move-scope`,cause:e})}},{handler:`skill-move-scope`,method:`POST`}),qo=q(Lee,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-duplicate`});return}if(!qa(n.name,t,`skill-duplicate`)||!qa(n.toName,t,`skill-duplicate`)||bo(n.toName,t,`skill-duplicate`))return;let r=Qa(n.scope,n.name);if(r===null||!B(L(r,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-duplicate`,detail:`SOURCE_NOT_FOUND`});return}let i=n.scope===`project`?l:Ya,a=z(i,gL(i,n.scope)),o=z(a,n.toName);if(Qa(n.scope,n.toName)!==null||B(o)){K(t,409,`urn:ok:error:doc-already-exists`,`A ${n.scope} skill named "${n.toName}" already exists.`,{handler:`skill-duplicate`});return}let s=JE(r);if(!s){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-duplicate`});return}ls(a,{recursive:!0}),fs(r,o,{recursive:!0,dereference:!0});let{fenced:c,body:u}=ua(s.skillMd),d=Qe(c,{name:n.toName});if(!d.ok){wA({skillsRoot:a,name:n.toName}),K(t,400,`urn:ok:error:invalid-request`,`Failed to write duplicated skill.`,{handler:`skill-duplicate`,detail:d.error.kind});return}try{vs(L(o,`SKILL.md`),`${d.nextFenced}${u}`)}catch(e){throw wA({skillsRoot:a,name:n.toName}),e}if(n.scope===`project`){let t=R(l,o).split(Vl).join(`/`);In(e,Pn(`skill`,``,n.toName),`skill-duplicate: ${n.name} -> ${t}`),await Ln(`skill-duplicate`)}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,Wee,{name:n.toName},{handler:`skill-duplicate`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate skill.`,{handler:`skill-duplicate`,cause:e})}},{handler:`skill-duplicate`,method:`POST`}),Jo=PW({GET:Lo,PUT:zo,POST:Uo,DELETE:Ho},{handler:`skill`});function Yo(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 Xo(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function Qo(e,t){let n=t.replace(/\.md$/i,``);return`${aee(e).replace(/\/SKILL$/,``)}/${n}`}function $o(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of tu(e,{withFileTypes:!0})){let a=t?`${t}/${n.name}`:n.name;n.isDirectory()?i(z(e,n.name),a):n.isFile()&&n.name.toLowerCase().endsWith(`.md`)&&r.push(`references/${a}`)}};return i(n,``),r}async function es(e,t,n){if(!k){F(`skill-move`).warn({fromName:t,toName:n},`no derived-document index available — skipping re-index of the moved skill (its old entries will be dropped with no replacement)`);return}let r=[],i=(e,t,n)=>{let i;try{i=V(n,`utf-8`)}catch(i){F(`skill-move`).warn({err:i,absFile:n,oldDocName:e,newDocName:t},`relocated skill file unreadable after move — dropping the old index entry with no replacement`),r.push({kind:`delete`,documentName:e});return}r.push({kind:`rename`,oldDocumentName:e,newDocumentName:t,markdown:i})},a=R(l,e).split(Vl).join(`/`),o=(e,t)=>`${a}/${e}/${t?t.replace(/\.mdx?$/i,``):`SKILL`}`;i(o(t),o(n),z(e,n,`SKILL.md`));for(let r of $o(e,n))i(o(t,r),o(n,r),z(e,n,r));await k.recordDirectMutations(r)}async function ts(e,t){if(!k||e.length===0)return;let n=[];for(let r of e)r.dir.split(`/`).pop()!==t&&n.push({kind:`link-rewrite`,documentName:`${r.dir}/${r.rel.replace(/\.mdx?$/i,``)}`,markdown:r.markdown});n.length>0&&await k.recordDirectMutations(n)}let ns=PW({GET:q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!qa(r,t,`skill-file-get`))return;let i=Ja(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=aI(r)?i===`global`?Ya:j:void 0,s=n.searchParams.get(`host`)??void 0,c=o?po(o,r,s):null;if(a===``||a.includes(`\0`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path.`,{handler:`skill-file-get`});return}let l=(c&&a===`SKILL.md`?`reference`:Yo(a))??`reference`,u=s,d=o?c?.dir??null:Qa(i,r,u);if(d===null&&u!==void 0){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-get`,detail:`No skill "${r}" (${i}) in ${u}.`});return}let f=d??z(Za(i),r),p=z(f,a);if(p!==f&&!p.startsWith(`${f}${Vl}`)){K(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let m=p,h=a;if(!B(m)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?uo.map(t=>`${e[1]}${t}`).find(e=>e!==a&&B(z(f,e))):void 0;if(n===void 0){K(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}h=n,m=z(f,n)}let g=await _u(m);if(g.includes(0)){K(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}J(t,200,ote,{path:h.replace(/\\/g,`/`),kind:l,text:g.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:q(Yee,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!qa(n.name,t,`skill-file-put`)||bo(n.name,t,`skill-file-put`))return;let r=Yo(n.path);if(r===null){K(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must name a file inside the skill dir, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){K(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=Qa(n.scope,n.name);if(i===null||!B(L(i,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=R(n.scope===`project`?l:Ya,i).split(Vl).join(`/`),o=n.path.replace(/\\/g,`/`),s=Xo(n.scope,r,o),u;if(s){let e=`${a}/${o.replace(/\.mdx?$/i,``)}`;if(Ra(e,`skill-file-put`,t))return;if(u=!B(z(i,o)),u&&bA(i)>=50){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:s,colorSeed:l,clientName:d}=Tn(n),f=await c.getSession(e,r,{displayName:s,colorSeed:l,clientName:d});f.dc.document.transact(()=>{Fb(f.dc.document,n.content,`agent`)},f.origin);let p=await At(e);if(p?.kind===`failure`){Mt(t,p.failure,`skill-file-put`);return}if(p?.kind===`divergence`){Nt(t,`skill-file-put`);return}}else{let e=xA({skillsRoot:I(i),name:n.name,relPath:o,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;K(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}u=e.created}n.scope===`project`&&(In(e,Pn(`skill`,``,n.name),`${u?`skill-file-create`:`skill-file-edit`}: ${a}/${o}`),await Ln(`skill-file-put`)),A?.(`files`),J(t,200,Ki,{path:o,created:u,kind:r,content:s},{handler:`skill-file-put`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams,i=r.get(`name`)??``;if(!qa(i,t,`skill-file-delete`)||bo(i,t,`skill-file-delete`))return;let a=Ja(r.get(`scope`),t,`skill-file-delete`);if(a===null)return;let o=(r.get(`path`)??``).replace(/\\/g,`/`),s=Yo(o);if(s===null){K(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must name a file inside the skill dir).`,{handler:`skill-file-delete`});return}let c=$a(n,ue);if(c.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let u=Qa(a,i),d=u===null?Za(a):I(u);if(B(z(u??L(d,i),o))&&Xo(a,s,o)){let e=o.replace(/\.md$/i,``);await tn([u===null?Qo(i,o):`${R(l,u).split(Vl).join(`/`)}/${e}`],`deleted-upstream`)}let f=CA({skillsRoot:d,name:i,relPath:o});if(!f.ok){let e=f.error.code===`UNLINK_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:f.error.code,cause:Error(f.error.message)});return}f.existed&&a===`project`&&(In(c,Pn(`skill`,``,i),`skill-file-delete: ${u===null?`${i}/${o}`:`${R(l,u).split(Vl).join(`/`)}/${o}`}`),await Ln(`skill-file-delete`)),f.existed&&A?.(`files`),J(t,200,Ai,{path:o,existed:f.existed,kind:s},{handler:`skill-file-delete`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),rs=q(Ri,async(e,t,n)=>{try{if(!qa(n.name,t,`skill-file-rename`)||bo(n.name,t,`skill-file-rename`))return;let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-rename`});return}let r=n.from.replace(/\\/g,`/`),i=n.to.replace(/\\/g,`/`),a=Yo(r),o=Yo(i);if(a===null||o===null){K(t,400,`urn:ok:error:invalid-request`,`Both paths must stay inside the skill dir.`,{handler:`skill-file-rename`,detail:a===null?r:i});return}let s=Qa(n.scope,n.name);if(s===null){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-rename`});return}let c=I(s),u=Xo(n.scope,a,r),d=Xo(n.scope,o,i),f=R(l,s).split(Vl).join(`/`),p=u?`${f}/${r.replace(/\.md$/i,``)}`:null,m=d?`${f}/${i.replace(/\.md$/i,``)}`:null;if(p!==null&&Ra(p,`skill-file-rename`,t))return;p!==null&&await tn([p],`deleted-upstream`);let h=SA({skillsRoot:c,name:n.name,relPath:r,toRelPath:i});if(!h.ok){let e=h.error.code===`RENAME_FAILED`?500:400;K(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,h.error.message,{handler:`skill-file-rename`,detail:h.error.code});return}if(k){let e=[];if(p!==null&&m!==null)try{e.push({kind:`rename`,oldDocumentName:p,newDocumentName:m,markdown:V(z(c,n.name,i),`utf-8`)})}catch{e.push({kind:`delete`,documentName:p})}else if(p!==null)e.push({kind:`delete`,documentName:p});else if(m!==null)try{e.push({kind:`upsert`,documentName:m,markdown:V(z(c,n.name,i),`utf-8`)})}catch{}await Bt(e,`skill-file-rename`)}n.scope===`project`&&(In(e,Pn(`skill`,``,n.name),`skill-file-rename: ${n.name}/${r} -> ${i}`),await Ln(`skill-file-rename`)),A?.(`files`),J(t,200,Aee,{from:r,to:i,...p===null?{}:{fromDocName:p},...m===null?{}:{toDocName:m}},{handler:`skill-file-rename`})}catch(e){X.error({err:e},`[skill-file-rename] failed`),t.headersSent||K(t,500,`urn:ok:error:internal-server-error`,`Failed to rename skill file.`,{handler:`skill-file-rename`})}},{handler:`skill-file-rename`,method:`POST`});function as(e){let t=/github\.com[/:]([\w.-]+)\//.exec(e);return t?t[1]:void 0}let os=NJ;function ss(e,t){return JE(z(e,t))?.contentHash}async function cs(e,t){let n=w?.current;if(!(!n||!e))try{let r=gx(n),i=async()=>{let t=(await r.raw(`for-each-ref`,`--format=%(refname)`,`refs/wip/`)).trim().split(`
1224
- `).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 Ln(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let us=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function ms(e){try{let t=Do(e.scope);if(!t)return;let n=VI(t);if(n.length===0)return;let r=qI(z(e.skillsRoot,e.name),e.name,t,n,`copy`,HI(e.scope));if(r.length===0)return;await BN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function hs(e,t){if(t.ok){J(e,200,Ote,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let _s=Mhe({contentDir:l,skillsHome:Ya,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:Qa,parseFrontmatterDoc:Ba,attributeOkArtifactWrite:In,commitOkArtifactWrite:Ln,shadowHeadSha:cs,artifactWriterId:us,effectiveInstallMode:co,signalFiles:()=>A?.(`files`)}),ys=q(Nee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await $E(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??IE(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(eZ(t,p,`skill-import`))return;let m=await RE(p);r=m.cleanup,s=m.ref;let h=YE(m.dir);if(h.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>KE(e.dir)?.name===f)??h.find(e=>e.name===xr[f]);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??as(d)}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await _s.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||ln(u))&&MI({source:u,skills:[d.body.name]},_I()),await M?.rebuildIgnorePatterns(),hs(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),bs=q(oee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await $E(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??IE(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(eZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??as(d),f.kind===`well-known`)a=f,o=await PE(f.origin);else{let e=await RE(f);r=e.cleanup,c=e.ref,s=YE(e.dir)}}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await RE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof OE?`not-found`:`failed`,warnings:[],...e instanceof OE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>JE(e.dir)?.name===t)??s.find(e=>e.name===xr[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await _s.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){F(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||ln(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&MI({source:u,skills:e},_I())}await M?.rebuildIgnorePatterns(),J(t,200,lte,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),xs=8*1024*1024,Ss=32*1024*1024;function Cs(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+Vl)?null:r}function ws(e){return new Promise((t,n)=>{let r;try{r=(0,wD.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:xs}})}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>Ss){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 Ts(e,t){return new Promise((n,r)=>{(0,hue.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=Cs(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>xs){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>Ss){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(I(n),{recursive:!0}),vs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Es(e,t){let n=Zl(L(pu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=Ja(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=OD({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},ue);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ws(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Ts(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Cs(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(I(r),{recursive:!0}),vs(r,e.data)}let u=YE(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];hs(t,await _s.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Ds=q(yee,async(e,t,n)=>{try{let e=Za(n.scope);if(!qa(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Do(n.scope),i=z(e,n.name),a=n.scope===`project`?l:Ya,o=(n.scope===`project`?yL(l):bL(Ya)).find(e=>e.name===n.name),s=o?z(a,o.dir):i;if(!B(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await At(n.scope===`project`?`${R(a,s).split(Vl).join(`/`)}/SKILL`:Zn(n.scope,n.name));let c=BI(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Xa.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o.hosts.filter(fi),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await Xa.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(fi),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await Xa.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:Ya;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await cr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:Ya;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await cr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:Ya,l=await cr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}A?.(`files`),J(t,200,mo,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?Pa.filter(e=>f?.some(t=>t===e)):[...Pa]:f===void 0?VI(r):Pa.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`)),c.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`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?j:Ya,l=d===void 0?co(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await Xa.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`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}A?.(`files`),J(t,200,mo,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await Xa.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:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),A?.(`files`),J(t,200,mo,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=RI(RN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&eL(n.name,r,v,HI(n.scope));let y=L(r,...zE),b=B(y)?V(y,`utf-8`):null,x=b===null?null:VE(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=qI(s,n.name,r,h,C,HI(n.scope));w.length===0?await VN(r,n.name):await BN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),A?.(`files`),J(t,200,mo,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Os=q(Dee,async(e,t,n)=>{try{if(!qa(n.name,t,`skill-uninstall`))return;let e=Do(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Oo(e,n.name,n.scope);A?.(`files`),J(t,200,Lt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),ks=PW({GET:q(Zt,async(e,t)=>{try{let e=VI(j??``),n=(e,t)=>{let n=Ihe(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,jo,{targets:e,configured:!1,folders:[...j?VX(l,pL(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...VX(Ya,pL(Ya,`global`)).map(e=>({...e,scope:`global`,...n(Ya,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(nt,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:Ya;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await Lhe(r,i.join(`/`)),A?.(`files`),J(t,200,_r,{targets:VI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(pL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?Fhe({base:r,folderRel:e.root,targetRootRel:a}):UX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await KX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),A?.(`files`),J(t,200,_r,{targets:VI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),As=q(_ee,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!qa(n.name,t,`skill-restore`)||bo(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=w?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await nZ({shadow:r,contentDir:l,contentRoot:O??`.`,name:n.name,version:n.version,skillDirRel:lo(n.name)});if(!i.ok){so(t,i,`skill-restore`);return}let a=[],o=BI(z(l,lo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),In(e,Pn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ln(`skill-restore`),A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,eee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),js=q(fee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!qa(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Ya:l,{root:a,dirRel:o,realDir:s}=Bo(n.scope,n.name),c=!o.startsWith(`${sr}/`);if(s===null||!B(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=L(n.scope===`global`?Ya:j,...zE),d=os(u).skills[n.name];if(!d){let e=lle(n.name,JE(z(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:cge(z(a,n.name))})??go(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await FJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await M?.rebuildIgnorePatterns(),J(t,200,Cn,{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=xr[e],a=await $E(d.source,e).catch(async e=>{if(i===void 0)throw e;return $E(d.source,i)}),o=a?.source??zle(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??IE(o);if(!c){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(eZ(t,c,`skill-reimport`))return;let l=await RE(c);r=l.cleanup,f=l.ref;let u=YE(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>JE(e.dir)?.name===n.name)??u.find(e=>e.name===xr[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=qE(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=JE(m.dir)}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=BX(p);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=JE(z(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 M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Ba(p.skillMd).body;if(n.dryRun){let e=JE(z(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=Ns({baseDir:j,timeout:{block:15e3}}),t=R(j,z(a,n.name)).split(Vl).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!0,source:d.source,localBody:Ba(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 tn(e,`deleted-upstream`)}let x=vA({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=xA({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:zX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=CA({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(In(e,Pn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await Ln(`skill-reimport`));let C=ss(a,n.name),w=n.scope===`project`?await cs(us(e),o):void 0;await FJ(u,e=>HE(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()})),!c&&n.scope===`project`&&await ms({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Ms=q(iee,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!qa(n.name,t,`skill-revert`)||bo(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=L(j,...zE),i=os(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=w?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await nZ({shadow:a,contentDir:l,contentRoot:O??`.`,name:n.name,version:i.baselineRef,skillDirRel:lo(n.name)});if(!o.ok){so(t,o,`skill-revert`);return}In(e,Pn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Ln(`skill-revert`);let s=z(l,lo(n.name),`..`),c=ss(s,n.name);await FJ(r,e=>HE(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Za(`project`)&&await ms({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),A?.(`files`),J(t,200,cee,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Fs(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Is(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 Ls(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Rs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let zs=Ahe({contentDir:l,projectDir:j,getAllFilesIndex:m,getFileIndexGeneration:g,getSearchMaxEntries:gge,semanticSearch:we,getSemanticSimilarityFloor:Te,ready:be,getProjectSkillsRoot:()=>Za(`project`),parseFrontmatterDoc:Ba});zs.prewarm();let Bs=PW({GET:q(Zt,iV(async(e,t)=>{let n=ec(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Fs(n.get(`intent`)),o=So(n.get(`ranking`)),s=Is(n.get(`scope`)??n.get(`scopes`)),c=Ls(n.get(`semantic`)),l=Rs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,ni,await zs.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(ea,iV(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Fs(n.intent),a=So(n.ranking),o=Is(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Ls(n.semantic),l=Rs(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,ni,await zs.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`}),Vs=q(Zt,iV(async(e,t)=>{J(t,200,ct,{...await kI(uu())},{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 Hs(e,t){if(r(e,t,{handler:`handoff`}))try{await _de(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:qe.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:cS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Ws(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await bN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:cS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Gs=q(Xee,async(e,t,n)=>{try{if(!j){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!ipe(e,n.kind)){BF(`invalid-path`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`invalid-path`},{handler:zF});return}let r=lpe(j);if(r===null){if(WF(j).kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}BF(`detached-head`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`detached-head`},{handler:zF});return}let i=WF(j);if(i.kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}if(i.kind===`non-github`){BF(`non-github-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`non-github-remote`},{handler:zF});return}if(!mpe(j,r)){BF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,qi,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:zF});return}let a=sQ(j,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=ape(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=ope(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${mne(s)}`,u=await spe(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);BF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,qi,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:zF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}},{handler:zF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),Ks=q(Zt,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:xB});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(!wt(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:xB});return}if(!yB(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:xB});return}J(t,200,Bee,await bB(j,r,i,a),{handler:xB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xB,cause:e})}},{handler:xB,method:`GET`,skipBodyParse:!0}),qs=q(kte,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:nI});return}if(!yB(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:nI});return}let e=sQ(j,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,bee,await Spe(j,n.branch,r,n.kind),{handler:nI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nI,cause:e})}},{handler:nI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nI})}),Ys=q(ji,async(e,t,n)=>{if(OD(n,ue).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:EB});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:EB});return}try{J(t,200,ste,await Ps(()=>OB(j,n.branch,{fastForward:n.fastForward===!0})),{handler:EB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:EB,cause:e})}},{handler:EB,method:`POST`});async function Xs(e){let[t,...n]=oe,r=[...n,...e];return await new Promise((e,n)=>{let i=jl(t,r,fN({...Hr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},YF),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 ${YF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=tI(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Zs=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:KF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Xs([`share`,`owners`,`--json`]),n=hpe(QF(e));eI(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,xte,n,{handler:KF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KF,cause:e})}finally{Fe.release(`/api/share/publish/owners`)}},{handler:KF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:KF})}),Qs=q(Zt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!ZF(r)||!XF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:qF});return}if(!Fe.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:qF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Xs([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=gpe(QF(e));eI(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Yr,n,{handler:qF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:qF,cause:e})}finally{Fe.release(`/api/share/publish/name-check`)}},{handler:qF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:qF})}),$s=q(To,async(e,t,n)=>{if(!j){eI(`publish-create`,`no-project`),J(t,200,ci,{ok:!1,error:`no-project`},{handler:JF});return}if(!ZF(n.owner)||!XF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:JF});return}if(!Fe.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:JF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Xs(e),i=ype(QF(r));eI(`publish-create`,i.ok?`ok`:i.error),i.ok&&ae?.()?.refreshRemote().catch(()=>{}),J(t,200,ci,i,{handler:JF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:JF,cause:e})}finally{Fe.release(`/api/share/publish`)}},{handler:JF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:JF})}),tc=q(Eee,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,It,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),nc=j?dO(j):null;async function rc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Sue(e.headers),previewUrl:null,port:nc?Js(nc)?.port??0:0,singleFile:Ae};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,$ee,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function ic(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Pe?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,fe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let ac=`local-op-embeddings-set-key`,oc=`local-op-embeddings-clear-key`,sc=`/api/local-op/embeddings`;function cc(){let e=De?.();return{projectDir:j??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let lc=q(ki,async(e,t,n)=>{if(!Fe.tryAcquire(sc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:ac,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=cc();await new rM(Ee).setForProject(e,r,n.key),we?.reloadCredential(),J(t,200,gi,{keyPresent:!0},{handler:ac,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:ac,cause:e})}finally{Fe.release(sc)}},{handler:ac,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ac})}),uc=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(sc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:oc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=cc();await new rM(Ee).clearForProject(e,n),we?.reloadCredential(),J(t,200,gi,{keyPresent:!1},{handler:oc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:oc,cause:e})}finally{Fe.release(sc)}},{handler:oc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oc})}),dc=`local-op-embeddings-test`,fc=`/api/local-op/embeddings/test`,pc=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(fc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:dc,extraHeaders:{"Retry-After":`5`}});return}try{let e=De?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await Kj(new rM(Ee),j??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Jj({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,ate,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:dc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:dc,cause:e})}finally{Fe.release(fc)}},{handler:dc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:dc})}),mc=q(Zt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(we){let t=we.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=De?.()?.baseUrl??`https://api.openai.com/v1`,o=await Kj(new rM(Ee),j??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of f())!Zx(e)&&!Qx(e)&&!_t(e)&&(p+=1);J(t,200,tte,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),hc=0;function gc(){hc+=1,A?.(`lint-config`)}let _c=()=>`${hc} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function vc(e,t){let n=Oe?.()??kt;try{let r=await Bn(e,qP(l,n,{docName:t,projectDir:j??l,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=ke?.()??`warning`;if(k&&a!==`off`&&!rS(t)){await Ht(t,e,`lint-validation`);let r=xF({projectDir:j??l,contentDir:l,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:Rt,docFilePathFor:e=>iQ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:iQ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function yc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=XP({projectDir:j??l,contentDir:l});return yP(t.schemas,n)}let bc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!hQ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Oe?.()??kt,i=[],a=WP(l,n??void 0,e=>i.push(e)),o=KP(j??l,GP(r,a),e=>i.push(e));n===null&&i.push(...yc(o)),J(t,200,hi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),xc=q(Wi,async(e,t,n)=>{let r;try{r=aF(z(l),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}gc();try{let e=Oe?.()??kt,n=[],r=WP(l,void 0,e=>n.push(e)),i=KP(j??l,GP(e,r),e=>n.push(e));n.push(...yc(i)),J(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Sc=q(Fee,async(e,t,n)=>{let r;try{let e=z(j??l),t=n.parentPath??[];r=n.delete?pfe(e,n.file):n.field!==void 0&&n.removeField?dfe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?ffe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?lfe(e,n.file,n.field,n.constraint,t):ufe(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&A?.(`files`),gc();try{let e=Oe?.()??kt,n=[],r=WP(l,void 0,e=>n.push(e)),i=KP(j??l,GP(e,r),e=>n.push(e));n.push(...yc(i)),J(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Cc=q(Zt,async(e,t)=>{try{let e=z(j??l),{schemas:n,truncated:r}=Rde(e),i=new Set(n),a=!1;if(M!==void 0){let t=JZ({contentDir:l,contentFilter:M,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&&ei(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!Ll(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,Hee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),wc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Tc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!hQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=iQ(l,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Oe?.()??kt,a=[],o=await YP({projectDir:j??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:wc});J(t,200,Oi,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof tN){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Ec=new hP,Dc=$X();function Oc(e,t,n){let r=`${n} ${_c()} ${t??``}`;return Dc.run(r,()=>Afe(e,{targetPath:t})).promise}function kc(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Ac=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!YZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Oe?.()??kt;J(t,200,vte,await ZP({projectDir:j??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:wc,cache:Ec,auditGeneration:_c}),{handler:`lint-audit`})}catch(e){if(e instanceof JP){kc(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),jc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=iQ(l,o)??`${o}.md`}let s=Oe?.()??kt,c=await Oc(xF({projectDir:j??l,contentDir:l,baseConfig:s,liveSourceFor:wc,derivedDocumentIndex:k??null,linksValidation:ke?.(),admittedDocNames:Rt,docFilePathFor:e=>iQ(l,e),cache:Ec,auditGeneration:_c}),i,hP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,Ii,kfe(c),{handler:`audit`});return}J(t,200,kee,c,{handler:`audit`})}catch(e){if(e instanceof JP){kc(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Mc=q(ite,async(t,n,r)=>{try{let t=ZZ(r.docName,n,`lint-fix`);if(t===null)return;let i=pt(t),a=OD(r,ue);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Zx(i)||Qx(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=iQ(l,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}uN(z(l,f),l);let p=Oe?.()??kt,{stored:m}=An(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await afe({projectDir:j??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=qr(d),n=xa[t]??Ui(u??o);re?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{xw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,yw(h))},h.origin),a.kind!==`anonymous`&&ej(i,o,s,u,void 0,a.kind===`agent`?En({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{re?.touchMode(o,`idle`)}let t=await At(i);if(t?.kind===`failure`){Mt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Nt(n,`lint-fix`);return}Ot(i,`lint-fix`);try{b=await Bn(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,qee,{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 tN){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof gS){_S(n,e,`lint-fix`);return}if(e instanceof xS){wS(n,e,`lint-fix`);return}if(e instanceof kw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Nc=`link-preview`,Pc=new HG({cacheDir:Ae?null:z(j??l,`.ok`,`local`,`link-previews`)}),Fc=null,Ic=()=>(Fc??=Pc.init(),Fc),Lc=Me??NG;async function Rc(e){let t=await Lc(e);return t.ok?{ok:!0,metadata:await RG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Lc})}:{ok:!1,reason:t.reason}}let zc=()=>{try{return Ne?.()===!0}catch{return!1}},Bc=q(Dte,async(e,t,n)=>{try{if(!zc()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,tr,{ok:!1,reason:`disabled`},{handler:Nc});return}await Ic();let e=!1,r=await Pc.load(n.url,()=>(e=!0,Rc(n.url)));Pc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,tr,i,{handler:Nc})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Nc,cause:e})}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>{let n=GG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Nc}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Nc}),!1)}}),Vc=$D({service:$e,getPrincipal:ue,onChanged:()=>A?.(`comments`)}),Hc=PW({GET:Vc.list,POST:Vc.create},{handler:`comments`}),Uc=PW({GET:Vc.read,POST:Vc.mutate,DELETE:Vc.remove},{handler:`comment`}),{handleSkillsSearch:Wc,handleSkillsPopular:Gc,handleSkillsPublisher:Kc,handleSkillsDetail:qc,handleSkillsPreview:Jc,handleSkillsDiscover:Yc,handleSkillsResolveRef:Xc}=Khe({log:X,skillsHome:Ya,projectDir:j,contentDir:l,resolveSkillDirForRead:Qa}),Zc={"/api/config":rc,"/api/config/diagnostics":ic,"/api/comments":Hc,"/api/comment":Uc,"/api/asset":Tr,"/api/asset-text":Dr,"/api/comment-counts":Gn,"/api/link-preview":Bc,"/api/folder-config":ja,"/api/saved-themes":Ma,"/api/saved-theme":Ia,"/api/template":Ga,"/api/template/import":Ka,"/api/templates":za,"/api/skill":Jo,"/api/skill-file":ns,"/api/skill-file/rename":rs,"/api/skills":Io,"/api/skills/installed":Wn,"/api/skills/search":Wc,"/api/skills/popular":Gc,"/api/skills/publisher":Kc,"/api/skills/detail":qc,"/api/skills/preview":Jc,"/api/skills/discover":Yc,"/api/skills/resolve-ref":Xc,"/api/skill/import":ys,"/api/skills/import-bulk":bs,"/api/skill/edit-external":Wo,"/api/skill/duplicate":qo,"/api/skill/move-scope":Ko,"/api/skill-upload":Es,"/api/skill/install":Ds,"/api/skill/uninstall":Os,"/api/skill/restore":As,"/api/skill/reimport":js,"/api/skill/revert":Ms,"/api/skill/track-in-git":Mo,"/api/skill-targets":ks,"/api/search":Bs,"/api/semantic-status":mc,"/api/lint/config":bc,"/api/lint/markdownlint-config":xc,"/api/lint/frontmatter-schema":Sc,"/api/lint/frontmatter-schemas":Cc,"/api/lint":Tc,"/api/lint/audit":Ac,"/api/lint/fix":Mc,"/api/audit":jc,"/api/create-page":kr,"/api/create-folder":jr,"/api/duplicate-path":Mr,"/api/rename-path":Nr,"/api/delete-path":Pr,"/api/trash/cleanup":Ir,"/api/upload":Lr,"/api/agent-write":Rn,"/api/agent-write-md":zn,"/api/agent-write-batch":Hn,"/api/frontmatter-patch":Un,"/api/agent-patch":Kn,"/api/agent-undo":qn,"/api/agent-activity":Yn,"/api/agent-burst-diff":Xn,"/api/save-version":lr,"/api/history":ur,"/api/rollback":pr,"/api/__embed-detect":br,"/api/server-info":mr,"/api/acp/catalog":gr,"/api/share/construct-url":Gs,"/api/share/target-status":qs,"/api/git/branch-info":Ks,"/api/git/checkout":Ys,"/api/share/publish/owners":Zs,"/api/share/publish/name-check":Qs,"/api/share/publish":$s,"/api/principal":yr,"/api/rescue":Or,"/api/workspace":Sr,"/api/sync/status":oa,"/api/sync/trigger":ga,"/api/sync/conflicts":_a,"/api/sync/conflict-content":ya,"/api/sync/resolve-conflict":va,"/api/local-op/clone":Gr,"/api/local-op/ok-init":$r,"/api/local-op/auth/login":bi,"/api/local-op/auth/status":Fi,"/api/local-op/auth/pat":zi,"/api/local-op/auth/gh-login":Ei,"/api/local-op/auth/cancel":Ni,"/api/local-op/auth/repos":Hi,"/api/local-op/auth/signout":Zi,"/api/local-op/auth/set-identity":ia,"/api/local-op/embeddings/set-key":lc,"/api/local-op/embeddings/clear-key":uc,"/api/local-op/embeddings/test":pc,"/api/installed-agents":Ta,"/api/spawn-cursor":Ws,"/api/handoff":Hs,"/api/install-skill":wa,"/api/skill/install-state":Vs,"/api/seed/plan":ba,"/api/seed/apply":Sa,"/api/seed/packs":Ca,"/api/client-logs":tc};C&&(Zc[`/api/test-reset`]=nr,Zc[`/api/test-flush-git`]=Qn,Zc[`/api/test-rescan-backlinks`]=rr,Zc[`/api/test-rescan-files`]=ir);let Qc=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/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/client-logs`.split(`.`)),$c=[`/api/local-op/`],el=rV({log:X,policy:n,ephemeral:Ae,table:{resolve(e){let t=Zc[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 fr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>Qc.has(e)||$c.some(t=>e.startsWith(t))}}),tl=AW({hocuspocus:s,derivedDocumentIndex:k,getFileIndex:f,isSafeDocName:hQ,readPageTitleForDocName:et,readPageTitleForLinkedDocName:tt,readFrontmatterMetadataForLinkedDocName:dt,collectAdmittedDocNames:Rt,resolveAlias:pt,respondToDerivedIndexQueryFailure:Gt}),nl=[tl,FW({hocuspocus:s,agentPresenceBroadcaster:re,isAllowedWorkspaceHostHeader:a,log:X}),Le],rl=nl.flatMap(e=>[...e.paths]);rW(rl,Zc);let il=nl.map(e=>rV({log:X,policy:n,ephemeral:Ae,table:e.table})),al={paths:rl,dispatch:async(e,t)=>{for(let n of il)if(await n(e,t))return!0;return!1}},ol=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 ol)if(Zc[e]===void 0&&tl.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 el(e,t)},nativeApi:al,localApi:NW({resolve:e=>{if(!ol.has(e))return;let t=Zc[e];return t===void 0?tl.table.resolve(e)?.dispatch:t}})}}function _Q(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=Il(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&&!qB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!YB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:HB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=AX(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=Ee.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 vQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function jge(e){let t;try{t=tu(e.contentDir,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Bx(n.name,w)&&e.basenameIndex.add(n.name)}async function yQ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await vu(i,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=oN(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await gu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await yu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!sN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await bu(i)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Bx(a,le)&&!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()&&Bx(a,le)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const bQ=N({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),xQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function SQ(e){return xQ.includes(e)}function CQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Mge(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!SQ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var wQ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=CQ(e,this.payload)}};function TQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=bQ.safeParse(t);return n.success?n.data:void 0}var EQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const DQ=F(`conflict-storage`);var OQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(dO(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!B(this.storePath)){this.conflicts=[];return}try{let e=V(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){DQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){DQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||Xl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return cu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return DQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-CEoe8TIl.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!sN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);CL(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),DQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Wb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){DQ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),DQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=z(this.projectDir),a=z(i,e.file);if(!sN(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(CL(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-CEoe8TIl.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);CL(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:B(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Nge(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 Pge(e,t){let n=dO(e);try{Xl(n,{recursive:!0}),cu(L(n,Ei),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Os(e);Xl(I(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};cu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const kQ=new Map;let AQ=!1;function Fge(e,t){try{let n=Nge(e,t);for(let e of kQ.keys())Pge(e,n)}catch{}}function Ige(e){kQ.set(e,(kQ.get(e)??0)+1),AQ||(AQ=!0,process.on(`uncaughtExceptionMonitor`,Fge));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=kQ.get(e)??0;n<=1?kQ.delete(e):kQ.set(e,n-1)}}}function jQ(e){let t=e.scheduler??vi,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function MQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NQ(e){if(!B(e))return{};let t;try{t=(0,CD.parse)(V(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!MQ(t))return{};let n=t.telemetry;if(!MQ(n))return{};let r=n.localSink;return MQ(r)?r:{}}function PQ(e){return typeof e==`boolean`?e:void 0}function Lge(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function FQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function IQ(e){if(MQ(e))return Lge(e.maxBytes)}function Rge(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=NQ(cs(`project`,e.projectDir)),n=NQ(cs(`project-local`,e.projectDir));if((PQ(n.enabled)??PQ(t.enabled)??!0)===!1)return null;let r=IQ(n.spans)??IQ(t.spans)??52428800,i=IQ(n.logs)??IQ(t.logs)??26214400,a=FQ(n.attributeDenylist)??FQ(t.attributeDenylist)??M;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var LQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(LQ||={});var zge;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(zge||={});const RQ=LQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),zQ=e=>{switch(typeof e){case`undefined`:return RQ.undefined;case`string`:return RQ.string;case`number`:return Number.isNaN(e)?RQ.nan:RQ.number;case`boolean`:return RQ.boolean;case`function`:return RQ.function;case`bigint`:return RQ.bigint;case`symbol`:return RQ.symbol;case`object`:return Array.isArray(e)?RQ.array:e===null?RQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?RQ.promise:typeof Map<`u`&&e instanceof Map?RQ.map:typeof Set<`u`&&e instanceof Set?RQ.set:typeof Date<`u`&&e instanceof Date?RQ.date:RQ.object;default:return RQ.unknown}},Z=LQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var BQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,LQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};BQ.create=e=>new BQ(e);const VQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===RQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,LQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${LQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${LQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${LQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:LQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,LQ.assertNever(e)}return{message:n}};let Bge=VQ;function HQ(){return Bge}const UQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function WQ(e,t){let n=HQ(),r=UQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===VQ?void 0:VQ].filter(e=>!!e)});e.common.issues.push(r)}var GQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return KQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return KQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const KQ=Object.freeze({status:`aborted`}),qQ=e=>({status:`dirty`,value:e}),JQ=e=>({status:`valid`,value:e}),YQ=e=>e.status===`aborted`,XQ=e=>e.status===`dirty`,ZQ=e=>e.status===`valid`,QQ=e=>typeof Promise<`u`&&e instanceof Promise;var $Q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})($Q||={});var e$=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const t$=(e,t)=>{if(ZQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new BQ(e.common.issues);return this._error=t,this._error}}};function n$(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var r$=class{get description(){return this._def.description}_getType(e){return zQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new GQ,ctx:{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(QQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)};return t$(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ZQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ZQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)},r=this._parse({data:e,path:n.path,parent:n});return t$(n,await(QQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new F$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return I$.create(this,this._def)}nullable(){return L$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return y$.create(this)}promise(){return P$.create(this,this._def)}or(e){return S$.create([this,e],this._def)}and(e){return T$.create(this,e,this._def)}transform(e){return new F$({...n$(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new R$({...n$(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new V$({typeName:Q.ZodBranded,type:this,...n$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new z$({...n$(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return H$.create(this,e)}readonly(){return U$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Vge=/^c[^\s-]{8,}$/i,Hge=/^[0-9a-z]+$/,Uge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Wge=/^[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,Gge=/^[a-z0-9_-]{21}$/i,Kge=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qge=/^[-+]?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)?)??$/,Jge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let i$;const Yge=/^(?:(?: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])$/,Xge=/^(?:(?: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])$/,Zge=/^(([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]))$/,Qge=/^(([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])$/,$ge=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,e_e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a$=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,t_e=RegExp(`^${a$}$`);function o$(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function n_e(e){return RegExp(`^${o$(e)}$`)}function r_e(e){let t=`${a$}T${o$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function i_e(e,t){return!!((t===`v4`||!t)&&Yge.test(e)||(t===`v6`||!t)&&Zge.test(e))}function a_e(e,t){if(!Kge.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 o_e(e,t){return!!((t===`v4`||!t)&&Xge.test(e)||(t===`v6`||!t)&&Qge.test(e))}var s$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==RQ.string){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.string,received:t.parsedType}),KQ}let t=new GQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?WQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&WQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Jge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)i$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),i$.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Wge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Gge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Vge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Hge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Uge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),WQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?r_e(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?t_e.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?n_e(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?qge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?i_e(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?a_e(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?o_e(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?$ge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?e_e.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...$Q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...$Q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...$Q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...$Q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...$Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...$Q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...$Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...$Q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...$Q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...$Q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...$Q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...$Q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...$Q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...$Q.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...$Q.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...$Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...$Q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...$Q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...$Q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...$Q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...$Q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...$Q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...$Q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...$Q.errToObj(t)})}nonempty(e){return this.min(1,$Q.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};s$.create=e=>new s$({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...n$(e)});function s_e(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var c$=class e extends r${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==RQ.number){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.number,received:t.parsedType}),KQ}let t,n=new GQ;for(let r of this._def.checks)r.kind===`int`?LQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?s_e(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:$Q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:$Q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:$Q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:$Q.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&LQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};c$.create=e=>new c$({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...n$(e)});var l$=class e extends r${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==RQ.bigint)return this._getInvalidInput(e);let t,n=new GQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.bigint,received:t.parsedType}),KQ}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};l$.create=e=>new l$({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...n$(e)});var u$=class extends r${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==RQ.boolean){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.boolean,received:t.parsedType}),KQ}return JQ(e.data)}};u$.create=e=>new u$({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...n$(e)});var d$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==RQ.date){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.date,received:t.parsedType}),KQ}if(Number.isNaN(e.data.getTime()))return WQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),KQ;let t=new GQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:$Q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:$Q.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};d$.create=e=>new d$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...n$(e)});var f$=class extends r${_parse(e){if(this._getType(e)!==RQ.symbol){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.symbol,received:t.parsedType}),KQ}return JQ(e.data)}};f$.create=e=>new f$({typeName:Q.ZodSymbol,...n$(e)});var p$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.undefined,received:t.parsedType}),KQ}return JQ(e.data)}};p$.create=e=>new p$({typeName:Q.ZodUndefined,...n$(e)});var m$=class extends r${_parse(e){if(this._getType(e)!==RQ.null){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.null,received:t.parsedType}),KQ}return JQ(e.data)}};m$.create=e=>new m$({typeName:Q.ZodNull,...n$(e)});var h$=class extends r${constructor(){super(...arguments),this._any=!0}_parse(e){return JQ(e.data)}};h$.create=e=>new h$({typeName:Q.ZodAny,...n$(e)});var g$=class extends r${constructor(){super(...arguments),this._unknown=!0}_parse(e){return JQ(e.data)}};g$.create=e=>new g$({typeName:Q.ZodUnknown,...n$(e)});var _$=class extends r${_parse(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.never,received:t.parsedType}),KQ}};_$.create=e=>new _$({typeName:Q.ZodNever,...n$(e)});var v$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.void,received:t.parsedType}),KQ}return JQ(e.data)}};v$.create=e=>new v$({typeName:Q.ZodVoid,...n$(e)});var y$=class e extends r${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==RQ.array)return WQ(t,{code:Z.invalid_type,expected:RQ.array,received:t.parsedType}),KQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(WQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(WQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(WQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new e$(t,e,t.path,n)))).then(e=>GQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new e$(t,e,t.path,n)));return GQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:$Q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:$Q.toString(n)}})}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...n$(t)});function b$(e){if(e instanceof x$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=I$.create(b$(r))}return new x$({...e._def,shape:()=>t})}else if(e instanceof y$)return new y$({...e._def,type:b$(e.element)});else if(e instanceof I$)return I$.create(b$(e.unwrap()));else if(e instanceof L$)return L$.create(b$(e.unwrap()));else if(e instanceof E$)return E$.create(e.items.map(e=>b$(e)));else return e}var x$=class e extends r${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=LQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==RQ.object){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.object,received:t.parsedType}),KQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _$&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new e$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof _$){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(WQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new e$(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>GQ.mergeObjectSync(t,e)):GQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return $Q.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:$Q.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of LQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of LQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return b$(this)}partial(t){let n={};for(let e of LQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of LQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof I$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return j$(LQ.objectKeys(this.shape))}};x$.create=(e,t)=>new x$({shape:()=>e,unknownKeys:`strip`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)}),x$.strictCreate=(e,t)=>new x$({shape:()=>e,unknownKeys:`strict`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)}),x$.lazycreate=(e,t)=>new x$({shape:e,unknownKeys:`strip`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)});var S$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new BQ(e.ctx.common.issues));return WQ(t,{code:Z.invalid_union,unionErrors:n}),KQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new BQ(e));return WQ(t,{code:Z.invalid_union,unionErrors:i}),KQ}}get options(){return this._def.options}};S$.create=(e,t)=>new S$({options:e,typeName:Q.ZodUnion,...n$(t)});const C$=e=>e instanceof k$?C$(e.schema):e instanceof F$?C$(e.innerType()):e instanceof A$?[e.value]:e instanceof M$?e.options:e instanceof N$?LQ.objectValues(e.enum):e instanceof R$?C$(e._def.innerType):e instanceof p$?[void 0]:e instanceof m$?[null]:e instanceof I$?[void 0,...C$(e.unwrap())]:e instanceof L$?[null,...C$(e.unwrap())]:e instanceof V$||e instanceof U$?C$(e.unwrap()):e instanceof z$?C$(e._def.innerType):[];var c_e=class e extends r${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.object)return WQ(t,{code:Z.invalid_type,expected:RQ.object,received:t.parsedType}),KQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(WQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),KQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=C$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...n$(r)})}};function w$(e,t){let n=zQ(e),r=zQ(t);if(e===t)return{valid:!0,data:e};if(n===RQ.object&&r===RQ.object){let n=LQ.objectKeys(t),r=LQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=w$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===RQ.array&&r===RQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=w$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===RQ.date&&r===RQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var T$=class extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(YQ(e)||YQ(r))return KQ;let i=w$(e.value,r.value);return i.valid?((XQ(e)||XQ(r))&&t.dirty(),{status:t.value,value:i.data}):(WQ(n,{code:Z.invalid_intersection_types}),KQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};T$.create=(e,t,n)=>new T$({left:e,right:t,typeName:Q.ZodIntersection,...n$(n)});var E$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.array)return WQ(n,{code:Z.invalid_type,expected:RQ.array,received:n.parsedType}),KQ;if(n.data.length<this._def.items.length)return WQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),KQ;!this._def.rest&&n.data.length>this._def.items.length&&(WQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new e$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>GQ.mergeArray(t,e)):GQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};E$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new E$({items:e,typeName:Q.ZodTuple,rest:null,...n$(t)})};var l_e=class e extends r${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.object)return WQ(n,{code:Z.invalid_type,expected:RQ.object,received:n.parsedType}),KQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new e$(n,e,n.path,e)),value:a._parse(new e$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?GQ.mergeObjectAsync(t,r):GQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof r$?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...n$(r)}):new e({keyType:s$.create(),valueType:t,typeName:Q.ZodRecord,...n$(n)})}},D$=class extends r${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.map)return WQ(n,{code:Z.invalid_type,expected:RQ.map,received:n.parsedType}),KQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new e$(n,e,n.path,[a,`key`])),value:i._parse(new e$(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};D$.create=(e,t,n)=>new D$({valueType:t,keyType:e,typeName:Q.ZodMap,...n$(n)});var O$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.set)return WQ(n,{code:Z.invalid_type,expected:RQ.set,received:n.parsedType}),KQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(WQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(WQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return KQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new e$(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:$Q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};O$.create=(e,t)=>new O$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...n$(t)});var u_e=class e extends r${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.function)return WQ(t,{code:Z.invalid_type,expected:RQ.function,received:t.parsedType}),KQ;function n(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof P$){let e=this;return JQ(async function(...t){let o=new BQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return JQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new BQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new BQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:E$.create(t).rest(g$.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||E$.create([]).rest(g$.create()),returns:n||g$.create(),typeName:Q.ZodFunction,...n$(r)})}},k$=class extends r${get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};k$.create=(e,t)=>new k$({getter:e,typeName:Q.ZodLazy,...n$(t)});var A$=class extends r${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return WQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),KQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};A$.create=(e,t)=>new A$({value:e,typeName:Q.ZodLiteral,...n$(t)});function j$(e,t){return new M$({values:e,typeName:Q.ZodEnum,...n$(t)})}var M$=class e extends r${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{expected:LQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),KQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),KQ}return JQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};M$.create=j$;var N$=class extends r${_parse(e){let t=LQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==RQ.string&&n.parsedType!==RQ.number){let e=LQ.objectValues(t);return WQ(n,{expected:LQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),KQ}if(this._cache||=new Set(LQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=LQ.objectValues(t);return WQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),KQ}return JQ(e.data)}get enum(){return this._def.values}};N$.create=(e,t)=>new N$({values:e,typeName:Q.ZodNativeEnum,...n$(t)});var P$=class extends r${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==RQ.promise&&t.common.async===!1?(WQ(t,{code:Z.invalid_type,expected:RQ.promise,received:t.parsedType}),KQ):JQ((t.parsedType===RQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};P$.create=(e,t)=>new P$({type:e,typeName:Q.ZodPromise,...n$(t)});var F$=class extends r${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{WQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return KQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r});{if(t.value===`aborted`)return KQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?KQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?KQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ZQ(e))return KQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ZQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):KQ);LQ.assertNever(r)}};F$.create=(e,t,n)=>new F$({schema:e,typeName:Q.ZodEffects,effect:t,...n$(n)}),F$.createWithPreprocess=(e,t,n)=>new F$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...n$(n)});var I$=class extends r${_parse(e){return this._getType(e)===RQ.undefined?JQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I$.create=(e,t)=>new I$({innerType:e,typeName:Q.ZodOptional,...n$(t)});var L$=class extends r${_parse(e){return this._getType(e)===RQ.null?JQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:Q.ZodNullable,...n$(t)});var R$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===RQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...n$(t)});var z$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return QQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...n$(t)});var B$=class extends r${_parse(e){if(this._getType(e)!==RQ.nan){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.nan,received:t.parsedType}),KQ}return{status:`valid`,value:e.data}}};B$.create=e=>new B$({typeName:Q.ZodNaN,...n$(e)});var V$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},H$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KQ:e.status===`dirty`?(t.dirty(),qQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},U$=class extends r${_parse(e){let t=this._def.innerType._parse(e),n=e=>(ZQ(e)&&(e.value=Object.freeze(e.value)),e);return QQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};U$.create=(e,t)=>new U$({innerType:e,typeName:Q.ZodReadonly,...n$(t)}),x$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),s$.create,c$.create,B$.create,l$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create;const d_e=x$.create;x$.strictCreate,S$.create,c_e.create,T$.create,E$.create,l_e.create,D$.create,O$.create,u_e.create,k$.create,A$.create,M$.create,N$.create,P$.create,F$.create,I$.create,L$.create,F$.createWithPreprocess,H$.create;const f_e=de(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>we(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>oe(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),p_e=de(`ZodMiniObject`,(e,t)=>{ie.init(e,t),f_e.init(e,t),T(e,`shape`,()=>t.shape)});function W$(e,t){return new p_e({type:`object`,shape:e??{},...r(t)})}function G$(e){return!!e._zod}function K$(e){let t=Object.values(e);if(t.length===0)return W$({});let n=t.every(G$),r=t.every(e=>!G$(e));if(n)return W$(e);if(r)return d_e(e);throw Error(`Mixed Zod versions detected in object shape.`)}function q$(e,t){return G$(e)?m(e,t):e.safeParse(t)}async function J$(e,t){return G$(e)?await oe(e,t):await e.safeParseAsync(t)}function Y$(e){if(!e)return;let t;if(t=G$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function X$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return K$(e)}}if(G$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Z$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function m_e(e){return e.description}function h_e(e){if(G$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Q$(e){if(G$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const $$=`2025-11-25`,e1=[$$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],t1=`io.modelcontextprotocol/related-task`,n1=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),r1=p([u(),i().int()]),i1=u();ve({ttl:i().optional(),pollInterval:i().optional()});const g_e=N({ttl:i().optional()}),__e=N({taskId:u()}),a1=ve({progressToken:r1.optional(),[t1]:__e.optional()}),o1=N({_meta:a1.optional()}),s1=o1.extend({task:g_e.optional()}),v_e=e=>s1.safeParse(e).success,c1=N({method:u(),params:o1.loose().optional()}),l1=N({_meta:a1.optional()}),u1=N({method:u(),params:l1.loose().optional()}),d1=ve({_meta:a1.optional()}),f1=p([u(),i().int()]),p1=N({jsonrpc:x(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=N({jsonrpc:x(`2.0`),...u1.shape}).strict(),y_e=e=>h1.safeParse(e).success,g1=N({jsonrpc:x(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(v1||={});const y1=N({jsonrpc:x(`2.0`),id:f1.optional(),error:N({code:i().int(),message:u(),data:_().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=p([p1,h1,g1,y1]);p([g1,y1]);const S1=d1.strict(),b_e=l1.extend({requestId:f1.optional(),reason:u().optional()}),C1=u1.extend({method:x(`notifications/cancelled`),params:b_e}),w1=N({icons:P(N({src:u(),mimeType:u().optional(),sizes:P(u()).optional(),theme:je([`light`,`dark`]).optional()})).optional()}),T1=N({name:u(),title:u().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),x_e=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(N({form:c(N({applyDefaults:D().optional()}),C(u(),_())).optional(),url:n1.optional()}),C(u(),_()).optional())),S_e=ve({list:n1.optional(),cancel:n1.optional(),requests:ve({sampling:ve({createMessage:n1.optional()}).optional(),elicitation:ve({create:n1.optional()}).optional()}).optional()}),C_e=ve({list:n1.optional(),cancel:n1.optional(),requests:ve({tools:ve({call:n1.optional()}).optional()}).optional()}),w_e=N({experimental:C(u(),n1).optional(),sampling:N({context:n1.optional(),tools:n1.optional()}).optional(),elicitation:x_e.optional(),roots:N({listChanged:D().optional()}).optional(),tasks:S_e.optional(),extensions:C(u(),n1).optional()}),T_e=o1.extend({protocolVersion:u(),capabilities:w_e,clientInfo:E1}),D1=c1.extend({method:x(`initialize`),params:T_e}),O1=e=>D1.safeParse(e).success,E_e=N({experimental:C(u(),n1).optional(),logging:n1.optional(),completions:n1.optional(),prompts:N({listChanged:D().optional()}).optional(),resources:N({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:N({listChanged:D().optional()}).optional(),tasks:C_e.optional(),extensions:C(u(),n1).optional()}),D_e=d1.extend({protocolVersion:u(),capabilities:E_e,serverInfo:E1,instructions:u().optional()}),k1=u1.extend({method:x(`notifications/initialized`),params:l1.optional()}),O_e=e=>k1.safeParse(e).success,A1=c1.extend({method:x(`ping`),params:o1.optional()}),k_e=N({progress:i(),total:v(i()),message:v(u())}),A_e=N({...l1.shape,...k_e.shape,progressToken:r1}),j1=u1.extend({method:x(`notifications/progress`),params:A_e}),j_e=o1.extend({cursor:i1.optional()}),M1=c1.extend({params:j_e.optional()}),N1=d1.extend({nextCursor:i1.optional()}),M_e=je([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=N({taskId:u(),status:M_e,ttl:p([i(),Fe()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),F1=d1.extend({task:P1}),N_e=l1.merge(P1),I1=u1.extend({method:x(`notifications/tasks/status`),params:N_e}),L1=c1.extend({method:x(`tasks/get`),params:o1.extend({taskId:u()})}),R1=d1.merge(P1),z1=c1.extend({method:x(`tasks/result`),params:o1.extend({taskId:u()})});d1.loose();const B1=M1.extend({method:x(`tasks/list`)}),V1=N1.extend({tasks:P(P1)}),H1=c1.extend({method:x(`tasks/cancel`),params:o1.extend({taskId:u()})}),P_e=d1.merge(P1),U1=N({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),W1=U1.extend({text:u()}),G1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=je([`user`,`assistant`]),J1=N({audience:P(q1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),Y1=N({...T1.shape,...w1.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:J1.optional(),_meta:v(ve({}))}),F_e=N({...T1.shape,...w1.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:J1.optional(),_meta:v(ve({}))}),X1=M1.extend({method:x(`resources/list`)}),I_e=N1.extend({resources:P(Y1)}),Z1=M1.extend({method:x(`resources/templates/list`)}),L_e=N1.extend({resourceTemplates:P(F_e)}),Q1=o1.extend({uri:u()}),R_e=Q1,$1=c1.extend({method:x(`resources/read`),params:R_e}),z_e=d1.extend({contents:P(p([W1,K1]))}),B_e=u1.extend({method:x(`notifications/resources/list_changed`),params:l1.optional()}),V_e=Q1,H_e=c1.extend({method:x(`resources/subscribe`),params:V_e}),U_e=Q1,W_e=c1.extend({method:x(`resources/unsubscribe`),params:U_e}),G_e=l1.extend({uri:u()}),K_e=u1.extend({method:x(`notifications/resources/updated`),params:G_e}),q_e=N({name:u(),description:v(u()),required:v(D())}),J_e=N({...T1.shape,...w1.shape,description:v(u()),arguments:v(P(q_e)),_meta:v(ve({}))}),e0=M1.extend({method:x(`prompts/list`)}),Y_e=N1.extend({prompts:P(J_e)}),X_e=o1.extend({name:u(),arguments:C(u(),u()).optional()}),t0=c1.extend({method:x(`prompts/get`),params:X_e}),n0=N({type:x(`text`),text:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),r0=N({type:x(`image`),data:G1,mimeType:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),i0=N({type:x(`audio`),data:G1,mimeType:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),Z_e=N({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Q_e=N({type:x(`resource`),resource:p([W1,K1]),annotations:J1.optional(),_meta:C(u(),_()).optional()}),a0=p([n0,r0,i0,Y1.extend({type:x(`resource_link`)}),Q_e]),$_e=N({role:q1,content:a0}),eve=d1.extend({description:u().optional(),messages:P($_e)}),tve=u1.extend({method:x(`notifications/prompts/list_changed`),params:l1.optional()}),nve=N({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),rve=N({taskSupport:je([`required`,`optional`,`forbidden`]).optional()}),o0=N({...T1.shape,...w1.shape,description:u().optional(),inputSchema:N({type:x(`object`),properties:C(u(),n1).optional(),required:P(u()).optional()}).catchall(_()),outputSchema:N({type:x(`object`),properties:C(u(),n1).optional(),required:P(u()).optional()}).catchall(_()).optional(),annotations:nve.optional(),execution:rve.optional(),_meta:C(u(),_()).optional()}),s0=M1.extend({method:x(`tools/list`)}),ive=N1.extend({tools:P(o0)}),c0=d1.extend({content:P(a0).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});c0.or(d1.extend({toolResult:_()}));const ave=s1.extend({name:u(),arguments:C(u(),_()).optional()}),l0=c1.extend({method:x(`tools/call`),params:ave}),ove=u1.extend({method:x(`notifications/tools/list_changed`),params:l1.optional()});N({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const u0=je([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),sve=o1.extend({level:u0}),d0=c1.extend({method:x(`logging/setLevel`),params:sve}),cve=l1.extend({level:u0,logger:u().optional(),data:_()}),lve=u1.extend({method:x(`notifications/message`),params:cve}),uve=N({hints:P(N({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),dve=N({mode:je([`auto`,`required`,`none`]).optional()}),fve=N({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:P(a0).default([]),structuredContent:N({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),pve=Ne(`type`,[n0,r0,i0]),f0=Ne(`type`,[n0,r0,i0,Z_e,fve]),mve=N({role:q1,content:p([f0,P(f0)]),_meta:C(u(),_()).optional()}),hve=s1.extend({messages:P(mve),modelPreferences:uve.optional(),systemPrompt:u().optional(),includeContext:je([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:P(u()).optional(),metadata:n1.optional(),tools:P(o0).optional(),toolChoice:dve.optional()}),gve=c1.extend({method:x(`sampling/createMessage`),params:hve}),p0=d1.extend({model:u(),stopReason:v(je([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:q1,content:pve}),m0=d1.extend({model:u(),stopReason:v(je([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:q1,content:p([f0,P(f0)])}),_ve=N({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),vve=N({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:je([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),yve=N({type:je([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),bve=N({type:x(`string`),title:u().optional(),description:u().optional(),enum:P(u()),default:u().optional()}),xve=N({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:P(N({const:u(),title:u()})),default:u().optional()}),Sve=p([p([N({type:x(`string`),title:u().optional(),description:u().optional(),enum:P(u()),enumNames:P(u()).optional(),default:u().optional()}),p([bve,xve]),p([N({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:N({type:x(`string`),enum:P(u())}),default:P(u()).optional()}),N({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:N({anyOf:P(N({const:u(),title:u()}))}),default:P(u()).optional()})])]),_ve,vve,yve]),Cve=p([s1.extend({mode:x(`form`).optional(),message:u(),requestedSchema:N({type:x(`object`),properties:C(u(),Sve),required:P(u()).optional()})}),s1.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),wve=c1.extend({method:x(`elicitation/create`),params:Cve}),Tve=l1.extend({elicitationId:u()}),Eve=u1.extend({method:x(`notifications/elicitation/complete`),params:Tve}),h0=d1.extend({action:je([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),P(u())])).optional())}),Dve=N({type:x(`ref/resource`),uri:u()}),Ove=N({type:x(`ref/prompt`),name:u()}),kve=o1.extend({ref:p([Ove,Dve]),argument:N({name:u(),value:u()}),context:N({arguments:C(u(),u()).optional()}).optional()}),g0=c1.extend({method:x(`completion/complete`),params:kve});function Ave(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function jve(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Mve=d1.extend({completion:ve({values:P(u()).max(100),total:v(i().int()),hasMore:v(D())})}),Nve=N({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),Pve=c1.extend({method:x(`roots/list`),params:o1.optional()}),_0=d1.extend({roots:P(Nve)}),Fve=u1.extend({method:x(`notifications/roots/list_changed`),params:l1.optional()});p([A1,D1,g0,d0,t0,e0,X1,Z1,$1,H_e,W_e,l0,s0,L1,z1,B1,H1]),p([C1,j1,k1,Fve,I1]),p([S1,p0,m0,h0,_0,R1,V1,F1]),p([A1,gve,wve,Pve,L1,z1,B1,H1]),p([C1,j1,lve,K_e,B_e,ove,tve,I1,Eve]),p([S1,D_e,Mve,eve,Y_e,I_e,L_e,z_e,c0,ive,R1,V1,F1]);var v0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ive(e.elicitations,n)}return new e(t,n,r)}},Ive=class extends v0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function y0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Lve=Symbol(`Let zodToJsonSchema decide on which parser to use`),b0={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Rve=e=>typeof e==`string`?{...b0,name:e}:{...b0,...e},zve=e=>{let t=Rve(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function x0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function S0(e,t,n,r,i){e[t]=n,x0(e,t,r,i)}const C0=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function w0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?C0(t,e.currentPath):t.join(`/`)}}function Bve(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=L0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&S0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&S0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(S0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),S0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Vve(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function Hve(){return{type:`boolean`}}function T0(e,t){return L0(e.type._def,t)}const Uve=(e,t)=>L0(e.innerType._def,t);function E0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E0(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Wve(e,t)}}const Wve=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minimum`,r.value,r.message,t);break;case`max`:S0(n,`maximum`,r.value,r.message,t);break}return n};function Gve(e,t){return{...L0(e.innerType._def,t),default:e.defaultValue()}}function Kve(e,t){return t.effectStrategy===`input`?L0(e.schema._def,t):w0(t)}function qve(e){return{type:`string`,enum:Array.from(e.values)}}const Jve=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Yve(e,t){let n=[L0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Jve(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 Xve(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let D0;const O0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(D0===void 0&&(D0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),D0),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function k0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:j0(n,`email`,r.message,t);break;case`format:idn-email`:j0(n,`idn-email`,r.message,t);break;case`pattern:zod`:M0(n,O0.email,r.message,t);break}break;case`url`:j0(n,`uri`,r.message,t);break;case`uuid`:j0(n,`uuid`,r.message,t);break;case`regex`:M0(n,r.regex,r.message,t);break;case`cuid`:M0(n,O0.cuid,r.message,t);break;case`cuid2`:M0(n,O0.cuid2,r.message,t);break;case`startsWith`:M0(n,RegExp(`^${A0(r.value,t)}`),r.message,t);break;case`endsWith`:M0(n,RegExp(`${A0(r.value,t)}$`),r.message,t);break;case`datetime`:j0(n,`date-time`,r.message,t);break;case`date`:j0(n,`date`,r.message,t);break;case`time`:j0(n,`time`,r.message,t);break;case`duration`:j0(n,`duration`,r.message,t);break;case`length`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:M0(n,RegExp(A0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&j0(n,`ipv4`,r.message,t),r.version!==`v4`&&j0(n,`ipv6`,r.message,t);break;case`base64url`:M0(n,O0.base64url,r.message,t);break;case`jwt`:M0(n,O0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&M0(n,O0.ipv4Cidr,r.message,t),r.version!==`v4`&&M0(n,O0.ipv6Cidr,r.message,t);break;case`emoji`:M0(n,O0.emoji(),r.message,t);break;case`ulid`:M0(n,O0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:j0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:S0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:M0(n,O0.base64,r.message,t);break}break;case`nanoid`:M0(n,O0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function A0(e,t){return t.patternStrategy===`escape`?Qve(e):e}const Zve=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Qve(e){let t=``;for(let n=0;n<e.length;n++)Zve.has(e[n])||(t+=`\\`),t+=e[n];return t}function j0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):S0(e,`format`,t,n,r)}function M0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:N0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):S0(e,`pattern`,N0(t,r),n,r)}function N0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1224
+ `).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 Ln(`baseline-verify`),o=await i(),o!==void 0&&!await a(o,t))?void 0:o}catch{return}}let us=e=>e.kind===`agent`||e.kind===`principal`?e.writerId:void 0;async function ms(e){try{let t=Do(e.scope);if(!t)return;let n=VI(t);if(n.length===0)return;let r=qI(z(e.skillsRoot,e.name),e.name,t,n,`copy`,HI(e.scope));if(r.length===0)return;await BN(t,e.name,{hosts:r,scope:e.scope,scripts:e.hasScripts,installedAt:new Date().toISOString(),projection:`copy`})}catch(t){X.warn({skill:e.name,err:t},`${e.handler}: inline projection failed; skill written, reconcile will project on next open`)}}function hs(e,t){if(t.ok){J(e,200,Ote,t.body,{handler:`skill-import`});return}K(e,t.status,t.urn,t.title,{handler:`skill-import`,...t.detail===void 0?{}:{detail:t.detail},...t.cause===void 0?{}:{cause:t.cause}})}let _s=Mhe({contentDir:l,skillsHome:Ya,...j===void 0?{}:{projectDir:j},resolveSkillDirForRead:Qa,parseFrontmatterDoc:Ba,attributeOkArtifactWrite:In,commitOkArtifactWrite:Ln,shadowHeadSha:cs,artifactWriterId:us,effectiveInstallMode:co,signalFiles:()=>A?.(`files`)}),ys=q(Nee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-import`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-import`});return}let i=n.scope,a=null,o,s,c,l,u=n.source;{let e=n.source;try{let i=await $E(e,n.skill),d=i?.source??e;u=d;let f=n.skill??i?.skill,p=i?.spec??IE(d);if(!p){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skill-import`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(eZ(t,p,`skill-import`))return;let m=await RE(p);r=m.cleanup,s=m.ref;let h=YE(m.dir);if(h.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skill-import`});return}let g=h[0];if(f){let e=h.find(e=>e.name===f)??h.find(e=>KE(e.dir)?.name===f)??h.find(e=>e.name===xr[f]);if(!e){K(t,404,`urn:ok:error:not-found`,`Named skill not in source.`,{handler:`skill-import`,detail:`--skill "${f}" not among: ${h.map(e=>e.name).join(`, `)}.`});return}g=e}else if(h.length>1){K(t,400,`urn:ok:error:invalid-request`,"Source has multiple skills; pass `skill` to choose one.",{handler:`skill-import`,detail:h.map(e=>e.name).join(`, `)});return}a=g.dir,l=g.name,o=e,c=i?.publisher??as(d)}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-import`,cause:e});return}throw e}}if(!a){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-import`});return}let d=await _s.runSkillImport({acquiredDir:a,scope:i,sourceLabel:o,ref:s,publisher:c,upstreamSkill:l,actor:e,skipProjection:n.install===!1});d.ok&&(n.marketplace===!0||ln(u))&&MI({source:u,skills:[d.body.name]},_I()),await M?.rebuildIgnorePatterns(),hs(t,d)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skill.`,{handler:`skill-import`,cause:e})}finally{r()}},{handler:`skill-import`,method:`POST`}),bs=q(oee,async(e,t,n)=>{let r=()=>{};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-import-bulk`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skills-import-bulk`});return}let i=n.source,a=null,o=null,s=[],c,l,u=i;try{let e=await $E(i,n.skills[0]),d=e?.source??i;u=d;let f=e?.spec??IE(d);if(!f){K(t,400,`urn:ok:error:invalid-request`,`Unrecognized import source.`,{handler:`skills-import-bulk`,detail:`Expected owner/repo, a git URL, a website source, a local path, or a skills.sh URL.`});return}if(eZ(t,f,`skills-import-bulk`))return;if(l=e?.publisher??as(d),f.kind===`well-known`)a=f,o=await PE(f.origin);else{let e=await RE(f);r=e.cleanup,c=e.ref,s=YE(e.dir)}}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skills-import-bulk`,cause:e});return}throw e}if(a===null&&s.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in source.`,{handler:`skills-import-bulk`});return}let d=[];for(let t of new Set(n.skills)){let r,u,f=()=>{};if(a!==null)try{let e=await RE({...a,skill:t},o?{index:o}:{});r=e.dir,f=e.cleanup,u=t}catch(e){d.push({requested:t,status:e instanceof OE?`not-found`:`failed`,warnings:[],...e instanceof OE?{}:{error:String(e)}});continue}else{let e=s.find(e=>e.name===t)??s.find(e=>JE(e.dir)?.name===t)??s.find(e=>e.name===xr[t]);if(!e){d.push({requested:t,status:`not-found`,warnings:[]});continue}r=e.dir,u=e.name}try{let a=await _s.runSkillImport({acquiredDir:r,scope:n.scope,sourceLabel:i,ref:c,publisher:l,upstreamSkill:u,actor:e,skipProjection:n.install===!1});if(!a.ok){F(`skills-import-bulk`).warn({skill:t,err:a.cause,detail:a.detail},`bulk import: one skill failed (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:a.detail??a.title});continue}d.push({requested:t,status:a.body.alreadyImported?`already-imported`:`imported`,name:a.body.name,...a.body.collisionRenamedFrom===void 0?{}:{collisionRenamedFrom:a.body.collisionRenamedFrom},warnings:a.body.warnings})}catch(e){F(`skills-import-bulk`).warn({skill:t,err:e},`bulk import: one skill threw (rest continue)`),d.push({requested:t,status:`failed`,warnings:[],error:e instanceof Error?e.message:String(e)})}finally{f()}}if(n.marketplace===!0||ln(u)){let e=d.filter(e=>e.status===`imported`).map(e=>e.requested);e.length>0&&MI({source:u,skills:e},_I())}await M?.rebuildIgnorePatterns(),J(t,200,lte,{results:d,imported:d.filter(e=>e.status===`imported`).length,alreadyImported:d.filter(e=>e.status===`already-imported`).length,failed:d.filter(e=>e.status===`failed`||e.status===`not-found`).length},{handler:`skills-import-bulk`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to import skills.`,{handler:`skills-import-bulk`,cause:e})}finally{r()}},{handler:`skills-import-bulk`,method:`POST`}),xs=8*1024*1024,Ss=32*1024*1024;function Cs(e,t){let n=t.split(`\\`).join(`/`).replace(/^\/+/,``);if(n===``||n.split(`/`).some(e=>e===`..`))return null;let r=z(e,n);return r!==e&&!r.startsWith(e+Vl)?null:r}function ws(e){return new Promise((t,n)=>{let r;try{r=(0,wD.default)({headers:e.headers,limits:{files:200,fields:10,fieldSize:2*1024,fileSize:xs}})}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>Ss){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 Ts(e,t){return new Promise((n,r)=>{(0,hue.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=Cs(t,e.fileName);if(!n){s(Error(`Unsafe archive entry: ${e.fileName}`));return}if(e.fileName.endsWith(`/`)){ls(n,{recursive:!0}),i.readEntry();return}if(e.uncompressedSize>xs){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>Ss){t.destroy(),s(Error(`Archive expands beyond the size limit.`));return}r.push(e)}),t.on(`error`,s),t.on(`end`,()=>{try{ls(I(n),{recursive:!0}),vs(n,Buffer.concat(r))}catch(e){s(e instanceof Error?e:Error(String(e)));return}i.readEntry()})})}),i.on(`end`,()=>n()),i.on(`error`,s),i.readEntry()})})}async function Es(e,t){let n=Zl(L(pu(),`ok-skill-upload-`)),r=()=>{try{ps(n,{recursive:!0,force:!0})}catch{}};try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-upload`,detail:`NO_PROJECT_ROOT`});return}if((e.method??``).toUpperCase()!==`POST`){K(t,405,`urn:ok:error:invalid-request`,`Use POST to upload a skill.`,{handler:`skill-upload`});return}let r=new URL(e.url??``,`http://localhost`),i=Ja(r.searchParams.get(`scope`),t,`skill-upload`);if(!i)return;let a=e=>r.searchParams.get(e)??void 0,o=OD({agentId:a(`agentId`),agentName:a(`agentName`),colorSeed:a(`colorSeed`),clientName:a(`clientName`),summary:a(`summary`)},ue);if(o.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-upload`});return}let s;try{s=await ws(e)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not read the upload.`,{handler:`skill-upload`,cause:e});return}if(s.length===0){K(t,400,`urn:ok:error:invalid-request`,`No files uploaded.`,{handler:`skill-upload`});return}let c=s.length===1?s[0]:null,l=c&&/\.(zip|skill)$/i.test(c.relPath)?c.relPath:null;if(c&&l)try{await Ts(c.data,n)}catch(e){K(t,400,`urn:ok:error:invalid-request`,`Could not unpack the archive.`,{handler:`skill-upload`,cause:e});return}else for(let e of s){let r=Cs(n,e.relPath);if(!r){K(t,400,`urn:ok:error:invalid-request`,`Unsafe file path in upload.`,{handler:`skill-upload`,detail:e.relPath});return}ls(I(r),{recursive:!0}),vs(r,e.data)}let u=YE(n);if(u.length===0){K(t,404,`urn:ok:error:not-found`,`No SKILL.md found in the upload.`,{handler:`skill-upload`});return}if(u.length>1){K(t,400,`urn:ok:error:invalid-request`,`Upload contains multiple skills; upload one at a time.`,{handler:`skill-upload`,detail:u.map(e=>e.name).join(`, `)});return}let d=u[0];hs(t,await _s.runSkillImport({acquiredDir:d.dir,scope:i,sourceLabel:`upload:${l??d.name}`,upstreamSkill:d.name,actor:o}))}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to upload skill.`,{handler:`skill-upload`,cause:e})}finally{r()}}let Ds=q(yee,async(e,t,n)=>{try{let e=Za(n.scope);if(!qa(n.name,t,`skill-install`))return;if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=Do(n.scope),i=z(e,n.name),a=n.scope===`project`?l:Ya,o=(n.scope===`project`?yL(l):bL(Ya)).find(e=>e.name===n.name),s=o?z(a,o.dir):i;if(!B(s)){K(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}await At(n.scope===`project`?`${R(a,s).split(Vl).join(`/`)}/SKILL`:Zn(n.scope,n.name));let c=BI(s,n.name);if(!c.ok){K(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${c.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}if(n.fork!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,`Skill is not in-place.`,{handler:`skill-install`,detail:`FORK_STORE_BACKED`});return}let e=Xa.resolveFork({scope:n.scope,name:n.name,fork:n.fork,inPlaceEntry:o});if(!e.ok)switch(e.kind){case`unknown-editor`:K(t,400,`urn:ok:error:invalid-request`,`Unknown editor.`,{handler:`skill-install`,detail:e.editor});return;case`fork-absent`:K(t,400,`urn:ok:error:invalid-request`,`No fork at that editor.`,{handler:`skill-install`,detail:`FORK_ABSENT`});return;case`not-a-fork`:K(t,400,`urn:ok:error:invalid-request`,`That copy matches the source — nothing to resolve.`,{handler:`skill-install`,detail:`NOT_A_FORK`});return;case`invalid-new-name`:K(t,400,`urn:ok:error:invalid-request`,`Invalid new name.`,{handler:`skill-install`,detail:e.toName});return;case`name-taken`:K(t,400,`urn:ok:error:invalid-request`,`Name already taken.`,{handler:`skill-install`,detail:e.toName});return;default:throw Error(`Unhandled fork outcome: ${String(e.kind)}`)}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o.hosts.filter(fi),scripts:!1,warnings:e.warnings,warningCodes:e.warnings.length>0?[`skill-fork-name-unpatched`]:[]},{handler:`skill-install`});return}let u=n.setSource??n.source,d=n.linkMode??(n.mode===void 0?void 0:n.mode===`link`),f=n.targets,p=[],m=[];if(n.add!==void 0||n.remove!==void 0){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before using add/remove.",{handler:`skill-install`,detail:`STORE_BACKED_ADDITIVE`});return}let e=await Xa.applyAddRemove({scope:n.scope,name:n.name,inPlaceEntry:o,...n.add===void 0?{}:{add:n.add},...n.remove===void 0?{}:{remove:n.remove}});if(!e.ok){e.kind===`remove-source`?K(t,400,`urn:ok:error:invalid-request`,`"${e.sourceId}" is the skill's SOURCE — its folder is the skill itself, so removing it would delete the skill. Move the source first (\`source\`) or use \`delete\`.`,{handler:`skill-install`,detail:`REMOVE_SOURCE`}):K(t,409,`urn:ok:error:invalid-request`,`Could not stop ${e.subRoot} following its pool (${e.reason}).`,{handler:`skill-install`,detail:e.reason});return}f=e.targets.filter(fi),p.push(...e.rootAdds),m.push(...e.rootRemoves)}if(u&&!o){let e=await Xa.promoteStoreBackedSource({scope:n.scope,name:n.name,base:r,skillDir:s,newSource:u});if(!e.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.kind===`source-occupied`?e.reason:e.target});return}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],sourceMovedTo:e.sourceMovedTo},{handler:`skill-install`});return}if(n.place){let e=n.scope===`project`?j:Ya;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot place — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await cr.place({placeBase:e,name:n.name,rawDir:n.place.dir,skillDir:s,mode:n.place.mode});if(!r.ok){r.kind===`invalid-path`?K(t,400,`urn:ok:error:invalid-request`,`Placement path must be a project-relative directory outside .ok/.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`}):K(t,409,`urn:ok:error:doc-already-exists`,`Something already exists at that path — placement never overwrites.`,{handler:`skill-install`,detail:`PLACE_DEST_EXISTS`});return}`alreadyAtSource`in r||A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[],placedAt:r.placedAt},{handler:`skill-install`});return}if(n.unplace){let e=n.scope===`project`?j:Ya;if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot remove a placement — no project root is resolved for this server.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=await cr.unplace({placeBase:e,name:n.name,rawPath:n.unplace.path,skillDir:s});if(!r.ok)switch(r.kind){case`not-recorded`:K(t,404,`urn:ok:error:not-found`,`No recorded placement at that path.`,{handler:`skill-install`,detail:r.path});return;case`unsafe-path`:K(t,400,`urn:ok:error:invalid-request`,`Recorded placement path is no longer safe.`,{handler:`skill-install`,detail:`PLACE_PATH_INVALID`});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — remove it manually if you mean it.`,{handler:`skill-install`,detail:r.path});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — it can't be removed here.`,{handler:`skill-install`,detail:r.path});return;default:throw Error(`Unhandled unplace outcome: ${String(r.kind)}`)}A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,mo,{name:n.name,hosts:o?[...o.hosts]:[],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}if(n.convert){if(!o){K(t,400,`urn:ok:error:invalid-request`,"This skill still lives in the legacy .ok/skills store — promote a real location first (`source`) before converting one.",{handler:`skill-install`,detail:`STORE_BACKED_CONVERT`});return}let{target:e,mode:i}=n.convert,a=n.scope===`project`?j:Ya,l=await cr.convert({ledgerBase:a??r,scope:n.scope,name:n.name,target:e,mode:i,skillDir:s,canonicalHash:o.contentHash});if(!l.ok)switch(l.kind){case`invalid-location`:K(t,400,`urn:ok:error:invalid-request`,`That location has no skills folder to convert.`,{handler:`skill-install`,detail:e});return;case`canonical-dir`:K(t,400,`urn:ok:error:invalid-request`,`That is the skill's own folder (the source) — move the source instead of converting it.`,{handler:`skill-install`,detail:e});return;case`forked`:K(t,409,`urn:ok:error:doc-already-exists`,`That copy has been edited and no longer matches the skill — resolve the fork before converting it.`,{handler:`skill-install`,detail:e});return;case`not-installed`:K(t,404,`urn:ok:error:not-found`,`The skill is not installed there.`,{handler:`skill-install`,detail:e});return;default:throw Error(`Unhandled convert outcome: ${String(l.kind)}`)}A?.(`files`),J(t,200,mo,{name:n.name,hosts:[...o.hosts],scripts:c.hasScripts,warnings:[],warningCodes:[]},{handler:`skill-install`});return}let h=n.scope===`global`?f?Pa.filter(e=>f?.some(t=>t===e)):[...Pa]:f===void 0?VI(r):Pa.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`)),c.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`)),c.warnings.length>0&&(g.push(c.warnings[0]),_.push(`no-description`)),o){let e=o.dir.split(`/`).slice(0,-1).join(`/`),i=f?.includes(`agents`)===!0?[...h,`agents`]:[...h],a=n.scope===`project`?j:Ya,l=d===void 0?co(n.scope,n.name,o):d?`link`:`copy`;if(u){let e=await Xa.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`?K(t,400,`urn:ok:error:invalid-request`,`Source target must be an editor id, "agents", or a project-relative skills root.`,{handler:`skill-install`,detail:e.target}):K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:e.reason});return}A?.(`files`),J(t,200,mo,{name:n.name,hosts:e.hosts,scripts:c.hasScripts,warnings:[],warningCodes:[],...e.sourceMovedTo===void 0?{}:{sourceMovedTo:e.sourceMovedTo}},{handler:`skill-install`});return}let v=await Xa.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:l,...d===void 0?{}:{linkModeReq:d},rootAdds:p,rootRemoves:m});if(!v.ok){K(t,409,`urn:ok:error:doc-already-exists`,`Cannot move the source there — a different skill occupies the target.`,{handler:`skill-install`,detail:v.reason});return}g.push(...v.warnings),_.push(...v.warningCodes),A?.(`files`),J(t,200,mo,{name:n.name,hosts:v.hosts,scripts:c.hasScripts,warnings:g,warningCodes:_,...v.sourceMovedTo===void 0?{}:{sourceMovedTo:v.sourceMovedTo}},{handler:`skill-install`});return}let v=RI(RN(r).skills[n.name]?.hosts??[]).filter(e=>!h.includes(e));v.length>0&&eL(n.name,r,v,HI(n.scope));let y=L(r,...zE),b=B(y)?V(y,`utf-8`):null,x=b===null?null:VE(b);b!==null&&x===null&&X.warn({skill:n.name},`skills-lock.json failed to parse — projecting as symlink (import origin unknown)`);let S=x?.skills[n.name]!==void 0,C=d===void 0?S?`copy`:`symlink`:d?`symlink`:`copy`,w=qI(s,n.name,r,h,C,HI(n.scope));w.length===0?await VN(r,n.name):await BN(r,n.name,{hosts:w,scope:n.scope,scripts:c.hasScripts,installedAt:new Date().toISOString(),projection:C}),A?.(`files`),J(t,200,mo,{name:n.name,hosts:w,scripts:c.hasScripts,warnings:g,warningCodes:_},{handler:`skill-install`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),Os=q(Dee,async(e,t,n)=>{try{if(!qa(n.name,t,`skill-uninstall`))return;let e=Do(n.scope);if(!e){K(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Oo(e,n.name,n.scope);A?.(`files`),J(t,200,Lt,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),ks=PW({GET:q(Zt,async(e,t)=>{try{let e=VI(j??``),n=(e,t)=>{let n=Ihe(e)[t.root];return n===void 0||(n.expect===`link`?t.state===`linked`&&t.target===n.target:t.state===`own`)?{}:{drift:!0,expected:n.expect===`link`?`link → ${n.target}`:`own folder`}};J(t,200,jo,{targets:e,configured:!1,folders:[...j?VX(l,pL(l,`project`)).map(e=>({...e,scope:`project`,...n(l,e)})):[],...VX(Ya,pL(Ya,`global`)).map(e=>({...e,scope:`global`,...n(Ya,e)}))]},{handler:`skill-targets-get`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill targets.`,{handler:`skill-targets-get`,cause:e})}},{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:q(nt,async(e,t,n)=>{try{{let e=n.folderAction,r=e.scope===`project`?l:Ya;if(e.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`Cannot manage skill folders — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}if(e.action===`add-root`){let n=e.root.replace(/\\/g,`/`).replace(/\/+$/g,``),i=n.split(`/`).filter(e=>e!==``&&e!==`.`);if(n===``||n.startsWith(`/`)||n.startsWith(`~`)||/^[A-Za-z]:/.test(n)||n.includes(`\0`)||i.length===0||i.some(e=>e===`..`)){K(t,400,`urn:ok:error:invalid-request`,`Invalid folder path.`,{handler:`skill-targets-put`,detail:e.root});return}await Lhe(r,i.join(`/`)),A?.(`files`),J(t,200,_r,{targets:VI(j??``),reprojected:[],bundleHosts:[],removedFrom:[]},{handler:`skill-targets-put`});return}let i=new Set(pL(r,e.scope).map(e=>e.root).filter(e=>!e.startsWith(`/`)&&!e.split(`/`).includes(`..`))),a=e.action===`link`?e.target??``:e.root;if(!i.has(e.root)||e.action===`link`&&(!i.has(a)||e.root===a)){K(t,400,`urn:ok:error:invalid-request`,`Folder and target must be distinct standard skills roots.`,{handler:`skill-targets-put`,detail:`${e.root} -> ${a}`});return}let o=e.action===`link`?Fhe({base:r,folderRel:e.root,targetRootRel:a}):UX({base:r,folderRel:e.root,...e.exclude===void 0?{}:{exclude:e.exclude}});if(!o.ok){K(t,409,`urn:ok:error:invalid-request`,o.reason===`conflicts`?`Cannot link — differing skills exist in both folders: ${(o.conflicts??[]).join(`, `)}. Resolve them first.`:o.reason===`stray-entries`?`Cannot link — the folder holds non-skill entries: ${(o.strays??[]).join(`, `)}.`:o.reason===`partial-move`?`The merge stopped partway (${(o.moved??[]).length} skill(s) already moved — nothing lost). Run Link again to resume and complete it. (${o.error??``})`:o.reason===`not-linked`?`That folder is not a symlink — nothing to unlink.`:`That folder cannot be linked (it is already a link or the same directory).`,{handler:`skill-targets-put`,detail:o.reason});return}await KX(r,e.root,e.action===`link`?{expect:`link`,target:a}:{expect:`own`}),A?.(`files`),J(t,200,_r,{targets:VI(j??``),reprojected:[],bundleHosts:[],removedFrom:[],folder:{moved:o.moved,dropped:o.dropped,linked:o.linked}},{handler:`skill-targets-put`});return}}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to set skill targets.`,{handler:`skill-targets-put`,cause:e})}},{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),As=q(_ee,async(e,t,n)=>{try{let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!qa(n.name,t,`skill-restore`)||bo(n.name,t,`skill-restore`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=w?.current;if(!r){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await nZ({shadow:r,contentDir:l,contentRoot:O??`.`,name:n.name,version:n.version,skillDirRel:lo(n.name)});if(!i.ok){so(t,i,`skill-restore`);return}let a=[],o=BI(z(l,lo(n.name)),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),In(e,Pn(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await Ln(`skill-restore`),A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,eee,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),js=q(fee,async(e,t,n)=>{let r=()=>{};try{if(n.scope===`project`&&!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-reimport`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-reimport`});return}if(!qa(n.name,t,`skill-reimport`))return;let i=n.scope===`global`?Ya:l,{root:a,dirRel:o,realDir:s}=Bo(n.scope,n.name),c=!o.startsWith(`${sr}/`);if(s===null||!B(z(i,o,`SKILL.md`))){K(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-reimport`,detail:`SKILL_ABSENT`});return}let u=L(n.scope===`global`?Ya:j,...zE),d=os(u).skills[n.name];if(!d){let e=lle(n.name,JE(z(a,n.name))?.contentHash??``,new Date().toISOString(),{selfIdentifiesAsPack:cge(z(a,n.name))})??go(i,n.name);e&&(d=e)}if(!d){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded import source to update from.`,{handler:`skill-reimport`,detail:`NOT_IMPORTED`});return}if(n.setAutoUpdate!==void 0){await FJ(u,e=>({...e,skills:{...e.skills,[n.name]:{...e.skills[n.name]??d,autoUpdate:n.setAutoUpdate}}})),await M?.rebuildIgnorePatterns(),J(t,200,Cn,{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=xr[e],a=await $E(d.source,e).catch(async e=>{if(i===void 0)throw e;return $E(d.source,i)}),o=a?.source??zle(d.source,d.pluginProvider),s=a?.skill??d.skill,c=a?.spec??IE(o);if(!c){K(t,400,`urn:ok:error:invalid-request`,`The recorded import source is no longer a valid source.`,{handler:`skill-reimport`,detail:d.source});return}if(eZ(t,c,`skill-reimport`))return;let l=await RE(c);r=l.cleanup,f=l.ref;let u=YE(l.dir),m=(s?u.find(e=>e.name===s):void 0)??u.find(e=>e.name===n.name)??u.find(e=>JE(e.dir)?.name===n.name)??u.find(e=>e.name===xr[s??n.name])??(u.length===1?u[0]:void 0);if(!m){K(t,404,`urn:ok:error:not-found`,`Could not locate this skill in its source anymore.`,{handler:`skill-reimport`,detail:u.map(e=>e.name).join(`, `)});return}let h=qE(m.dir);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}p=JE(m.dir)}catch(e){if(e instanceof OE){K(t,400,`urn:ok:error:invalid-request`,`Could not fetch source.`,{handler:`skill-reimport`,cause:e});return}throw e}if(!p){K(t,422,`urn:ok:error:invalid-request`,`Source has no readable skill.`,{handler:`skill-reimport`});return}let h=BX(p);if(h){K(t,400,`urn:ok:error:invalid-request`,`Skill bundle exceeds import limits.`,{handler:`skill-reimport`,detail:h});return}m=p.files.some(e=>e.relPath.startsWith(`scripts/`));let g=JE(z(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 M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!1,source:d.source,warnings:[]},{handler:`skill-reimport`});return}let b=Ba(p.skillMd).body;if(n.dryRun){let e=JE(z(a,n.name))?.skillMd??``,r;if(n.scope===`project`&&j)try{let e=Ns({baseDir:j,timeout:{block:15e3}}),t=R(j,z(a,n.name)).split(Vl).join(`/`);r=(await e.raw(`ls-files`,`--`,t)).trim().length>0}catch{r=void 0}await M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!0,source:d.source,localBody:Ba(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 tn(e,`deleted-upstream`)}let x=vA({skillsRoot:a,name:n.name,body:b,frontmatter:{name:n.name,description:p.description}});if(!x.ok){K(t,400,`urn:ok:error:invalid-request`,`Failed to write skill.`,{handler:`skill-reimport`,detail:x.error.code,cause:Error(x.error.message)});return}let S=[...x.warnings];for(let e of p.files){let r=xA({skillsRoot:a,name:n.name,relPath:e.relPath,content:e.content,bytes:e.bytes,limits:zX});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the complete refreshed skill bundle.`,{handler:`skill-reimport`,detail:`${e.relPath}: ${r.error.code}`,cause:Error(r.error.message)});return}}for(let e of y){let r=CA({skillsRoot:a,name:n.name,relPath:e});if(!r.ok){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reconcile files removed upstream.`,{handler:`skill-reimport`,detail:`${e}: ${r.error.code}`,cause:Error(r.error.message)});return}}n.scope===`project`&&(In(e,Pn(`skill`,``,n.name),`skill-reimport: ${d.source} -> ${o}`),await Ln(`skill-reimport`));let C=ss(a,n.name),w=n.scope===`project`?await cs(us(e),o):void 0;await FJ(u,e=>HE(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()})),!c&&n.scope===`project`&&await ms({skillsRoot:a,name:n.name,scope:`project`,hasScripts:m,handler:`skill-reimport`}),A?.(`files`),await M?.rebuildIgnorePatterns(),J(t,200,Cn,{name:n.name,updated:!0,source:d.source,warnings:S},{handler:`skill-reimport`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to reimport skill.`,{handler:`skill-reimport`,cause:e})}finally{r()}},{handler:`skill-reimport`,method:`POST`}),Ms=q(iee,async(e,t,n)=>{try{if(!j){K(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skill-revert`,detail:`NO_PROJECT_ROOT`});return}let e=OD(n,ue);if(e.kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-revert`});return}if(!qa(n.name,t,`skill-revert`)||bo(n.name,t,`skill-revert`))return;if(n.scope===`global`){K(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is nothing to revert to.`,{handler:`skill-revert`,detail:`GLOBAL_SCOPE`});return}let r=L(j,...zE),i=os(r).skills[n.name];if(!i?.baselineRef){K(t,400,`urn:ok:error:invalid-request`,`This skill has no recorded install baseline to revert to.`,{handler:`skill-revert`,detail:`NO_BASELINE`});return}let a=w?.current;if(!a){K(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to revert from.`,{handler:`skill-revert`,detail:`NO_SHADOW_REPO`});return}let o=await nZ({shadow:a,contentDir:l,contentRoot:O??`.`,name:n.name,version:i.baselineRef,skillDirRel:lo(n.name)});if(!o.ok){so(t,o,`skill-revert`);return}In(e,Pn(`skill`,``,n.name),`skill-revert: ${n.name} @ ${i.baselineRef.slice(0,8)}`),await Ln(`skill-revert`);let s=z(l,lo(n.name),`..`),c=ss(s,n.name);await FJ(r,e=>HE(e,n.name,{...e.skills[n.name]??i,...c===void 0?{}:{localHash:c}})),s===Za(`project`)&&await ms({skillsRoot:s,name:n.name,scope:`project`,hasScripts:o.restoredFiles.some(e=>e.startsWith(`scripts/`)),handler:`skill-revert`}),A?.(`files`),J(t,200,cee,{name:n.name,baselineRef:i.baselineRef,restoredFiles:o.restoredFiles,warnings:[]},{handler:`skill-revert`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to revert skill.`,{handler:`skill-revert`,cause:e})}},{handler:`skill-revert`,method:`POST`});function Fs(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function Is(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 Ls(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function Rs(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}let zs=Ahe({contentDir:l,projectDir:j,getAllFilesIndex:m,getFileIndexGeneration:g,getSearchMaxEntries:gge,semanticSearch:we,getSemanticSimilarityFloor:Te,ready:be,getProjectSkillsRoot:()=>Za(`project`),parseFrontmatterDoc:Ba});zs.prewarm();let Bs=PW({GET:q(Zt,iV(async(e,t)=>{let n=ec(e),r=n.get(`limit`),i=n.get(`query`)??``,a=Fs(n.get(`intent`)),o=So(n.get(`ranking`)),s=Is(n.get(`scope`)??n.get(`scopes`)),c=Ls(n.get(`semantic`)),l=Rs(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}J(t,200,ni,await zs.buildSearchResponse({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:q(ea,iV(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=Fs(n.intent),a=So(n.ranking),o=Is(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=Ls(n.semantic),l=Rs(n.source);if(r.length>200){K(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}J(t,200,ni,await zs.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`}),Vs=q(Zt,iV(async(e,t)=>{J(t,200,ct,{...await kI(uu())},{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 Hs(e,t){if(r(e,t,{handler:`handoff`}))try{await _de(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:qe.probeWithCache})}catch(n){t.headersSent||(X.error({err:n,requestId:cS(e)},`[handoff] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Ws(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await bN(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(X.error({err:n,requestId:cS(e)},`[spawn-cursor] route wrapper failed`),K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let Gs=q(Xee,async(e,t,n)=>{try{if(!j){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!ipe(e,n.kind)){BF(`invalid-path`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`invalid-path`},{handler:zF});return}let r=lpe(j);if(r===null){if(WF(j).kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}BF(`detached-head`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`detached-head`},{handler:zF});return}let i=WF(j);if(i.kind===`no-remote`){BF(`no-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`no-remote`},{handler:zF});return}if(i.kind===`non-github`){BF(`non-github-remote`,{kind:n.kind}),J(t,200,qi,{ok:!1,error:`non-github-remote`},{handler:zF});return}if(!mpe(j,r)){BF(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),J(t,200,qi,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:zF});return}let a=sQ(j,l);if(a===null)throw Error(`content dir is not contained within the project dir`);let o=n.kind===`doc`?n.docPath!==``:n.folderPath!==``;a!==``&&o&&F(`share`).warn({action:`construct-url`,kind:n.kind},`[share] content.dir != "." — non-root share URL omits the content.dir prefix; the github.com link may point at the wrong subtree. In-app receive navigation is content-relative and lands correctly.`);let s;if(n.kind===`doc`)s=ape(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=ope(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${mne(s)}`,u=await spe(j,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);BF(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),J(t,200,qi,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:zF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:zF,cause:e})}},{handler:zF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:zF})}),Ks=q(Zt,async(e,t)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:xB});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(!wt(r)){K(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:xB});return}if(!yB(i,a)){K(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:xB});return}J(t,200,Bee,await bB(j,r,i,a),{handler:xB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xB,cause:e})}},{handler:xB,method:`GET`,skipBodyParse:!0}),qs=q(kte,async(e,t,n)=>{try{if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:nI});return}if(!yB(n.path,n.kind)){K(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:nI});return}let e=sQ(j,l);if(e===null)throw Error(`content dir is not contained within the project dir`);let r=e===``?n.path:n.path===``?e:`${e}/${n.path}`;J(t,200,bee,await Spe(j,n.branch,r,n.kind),{handler:nI})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:nI,cause:e})}},{handler:nI,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nI})}),Ys=q(ji,async(e,t,n)=>{if(OD(n,ue).kind===`invalid-summary`){K(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:EB});return}if(!j){K(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:EB});return}try{J(t,200,ste,await Ps(()=>OB(j,n.branch,{fastForward:n.fastForward===!0})),{handler:EB})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:EB,cause:e})}},{handler:EB,method:`POST`});async function Xs(e){let[t,...n]=oe,r=[...n,...e];return await new Promise((e,n)=>{let i=jl(t,r,fN({...Hr,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},YF),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 ${YF}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=tI(Buffer.concat(c).toString(`utf-8`)).slice(0,500);X.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Zs=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(`/api/share/publish/owners`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:KF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Xs([`share`,`owners`,`--json`]),n=hpe(QF(e));eI(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),J(t,200,xte,n,{handler:KF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:KF,cause:e})}finally{Fe.release(`/api/share/publish/owners`)}},{handler:KF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:KF})}),Qs=q(Zt,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!ZF(r)||!XF(i)){K(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:qF});return}if(!Fe.tryAcquire(`/api/share/publish/name-check`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:qF,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Xs([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=gpe(QF(e));eI(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),J(t,200,Yr,n,{handler:qF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:qF,cause:e})}finally{Fe.release(`/api/share/publish/name-check`)}},{handler:qF,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:qF})}),$s=q(To,async(e,t,n)=>{if(!j){eI(`publish-create`,`no-project`),J(t,200,ci,{ok:!1,error:`no-project`},{handler:JF});return}if(!ZF(n.owner)||!XF(n.name)){K(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:JF});return}if(!Fe.tryAcquire(`/api/share/publish`)){K(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:JF,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,j,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Xs(e),i=ype(QF(r));eI(`publish-create`,i.ok?`ok`:i.error),i.ok&&ae?.()?.refreshRemote().catch(()=>{}),J(t,200,ci,i,{handler:JF})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:JF,cause:e})}finally{Fe.release(`/api/share/publish`)}},{handler:JF,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:JF})}),tc=q(Eee,async(e,t,n)=>{try{let e=F(`renderer`);n.droppedSinceLastFlush!==void 0&&n.droppedSinceLastFlush>0&&e.warn({source:`renderer-console`,transport:`web`,event:`client-log-entries-dropped`,droppedSinceLastFlush:n.droppedSinceLastFlush},`client-log-entries-dropped`);for(let t of n.entries)try{e[t.level]({...t.fields,source:`renderer-console`,transport:`web`,...t.sourceId?{sourceId:t.sourceId}:{},...t.lineNumber===void 0?{}:{lineNumber:t.lineNumber},...t.ts===void 0?{}:{clientTs:t.ts}},t.event??t.message)}catch{}J(t,200,It,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),nc=j?dO(j):null;async function rc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:Sue(e.headers),previewUrl:null,port:nc?Js(nc)?.port??0:0,singleFile:Ae};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,$ee,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}async function ic(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n=Pe?.()??{diagnostics:[]};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}J(t,200,fe,n,{handler:`api-config-diagnostics`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config-diagnostics`,cause:e})}return}K(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config-diagnostics`,extraHeaders:{Allow:`GET, HEAD`}})}let ac=`local-op-embeddings-set-key`,oc=`local-op-embeddings-clear-key`,sc=`/api/local-op/embeddings`;function cc(){let e=De?.();return{projectDir:j??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let lc=q(ki,async(e,t,n)=>{if(!Fe.tryAcquire(sc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:ac,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=cc();await new rM(Ee).setForProject(e,r,n.key),we?.reloadCredential(),J(t,200,gi,{keyPresent:!0},{handler:ac,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:ac,cause:e})}finally{Fe.release(sc)}},{handler:ac,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ac})}),uc=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(sc)){K(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:oc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=cc();await new rM(Ee).clearForProject(e,n),we?.reloadCredential(),J(t,200,gi,{keyPresent:!1},{handler:oc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:oc,cause:e})}finally{Fe.release(sc)}},{handler:oc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oc})}),dc=`local-op-embeddings-test`,fc=`/api/local-op/embeddings/test`,pc=q(Zt,async(e,t)=>{if(!Fe.tryAcquire(fc)){K(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:dc,extraHeaders:{"Retry-After":`5`}});return}try{let e=De?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await Kj(new rM(Ee),j??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await Jj({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};J(t,200,ate,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:dc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:dc,cause:e})}finally{Fe.release(fc)}},{handler:dc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:dc})}),mc=q(Zt,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(we){let t=we.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=De?.()?.baseUrl??`https://api.openai.com/v1`,o=await Kj(new rM(Ee),j??l,a),s=o.apiKey!==null,c=!s&&o.keyless,u=s?o.source:null,d=o.apiKey&&o.apiKey.length>=8?o.apiKey.slice(-4):null,p=0;for(let[e]of f())!Zx(e)&&!Qx(e)&&!_t(e)&&(p+=1);J(t,200,tte,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:p},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0}),hc=0;function gc(){hc+=1,A?.(`lint-config`)}let _c=()=>`${hc} ${t.getActiveBranch()} ${k?.readLocalTargetGeneration?.()??0}`;async function vc(e,t){let n=Oe?.()??kt;try{let r=await Bn(e,qP(l,n,{docName:t,projectDir:j??l,onProblem:e=>X.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=ke?.()??`warning`;if(k&&a!==`off`&&!rS(t)){await Ht(t,e,`lint-validation`);let r=xF({projectDir:j??l,contentDir:l,baseConfig:n,derivedDocumentIndex:k,linksValidation:a,admittedDocNames:Rt,docFilePathFor:e=>iQ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:iQ(l,t)??`${t}.md`})).files.flatMap(e=>e.diagnostics))}return[...r,...i].sort((e,t)=>e.range.start.line-t.range.start.line||e.range.start.character-t.range.start.character).slice(0,10).map(e=>({kind:`lint-violation`,source:e.source,code:e.code,message:e.message,severity:e.severity,line:e.range.start.line+1,column:e.range.start.character+1,...`linkTarget`in e&&e.linkTarget!==void 0?{linkTarget:e.linkTarget}:{},...`localTarget`in e&&e.localTarget!==void 0?{localTarget:e.localTarget}:{}}))}catch(e){return X.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function yc(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=XP({projectDir:j??l,contentDir:l});return yP(t.schemas,n)}let bc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!hQ(n))){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Oe?.()??kt,i=[],a=WP(l,n??void 0,e=>i.push(e)),o=KP(j??l,GP(r,a),e=>i.push(e));n===null&&i.push(...yc(o)),J(t,200,hi,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),xc=q(Wi,async(e,t,n)=>{let r;try{r=aF(z(l),n.ruleId,n.value)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){K(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}gc();try{let e=Oe?.()??kt,n=[],r=WP(l,void 0,e=>n.push(e)),i=KP(j??l,GP(e,r),e=>n.push(e));n.push(...yc(i)),J(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),Sc=q(Fee,async(e,t,n)=>{let r;try{let e=z(j??l),t=n.parentPath??[];r=n.delete?pfe(e,n.file):n.field!==void 0&&n.removeField?dfe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?ffe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?lfe(e,n.file,n.field,n.constraint,t):ufe(e,n.file)}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){K(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&A?.(`files`),gc();try{let e=Oe?.()??kt,n=[],r=WP(l,void 0,e=>n.push(e)),i=KP(j??l,GP(e,r),e=>n.push(e));n.push(...yc(i)),J(t,200,hi,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),Cc=q(Zt,async(e,t)=>{try{let e=z(j??l),{schemas:n,truncated:r}=Rde(e),i=new Set(n),a=!1;if(M!==void 0){let t=JZ({contentDir:l,contentFilter:M,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&&ei(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!Ll(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));J(t,200,Hee,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),wc=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=s.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},Tc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!hQ(n)){K(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=iQ(l,n);if(r===null){K(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Oe?.()??kt,a=[],o=await YP({projectDir:j??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:wc});J(t,200,Oi,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof tN){K(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),Ec=new hP,Dc=$X();function Oc(e,t,n){let r=`${n} ${_c()} ${t??``}`;return Dc.run(r,()=>Afe(e,{targetPath:t})).promise}function kc(e,t){K(e,409,`urn:ok:error:audit-superseded`,`The lint configuration or branch changed while the audit was running; re-run it.`,{handler:t})}let Ac=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`path`),r=n===null||n===``?void 0:n;if(r!==void 0&&!YZ(r)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Oe?.()??kt;J(t,200,vte,await ZP({projectDir:j??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:wc,cache:Ec,auditGeneration:_c}),{handler:`lint-audit`})}catch(e){if(e instanceof JP){kc(t,`lint-audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),jc=q(Zt,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`path`),i=r===null||r===``?void 0:r;if(i!==void 0&&!YZ(i)){K(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!YZ(o)){K(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=iQ(l,o)??`${o}.md`}let s=Oe?.()??kt,c=await Oc(xF({projectDir:j??l,contentDir:l,baseConfig:s,liveSourceFor:wc,derivedDocumentIndex:k??null,linksValidation:ke?.(),admittedDocNames:Rt,docFilePathFor:e=>iQ(l,e),cache:Ec,auditGeneration:_c}),i,hP.fingerprintConfig(s));if(n.searchParams.get(`counts`)===`1`){J(t,200,Ii,kfe(c),{handler:`audit`});return}J(t,200,kee,c,{handler:`audit`})}catch(e){if(e instanceof JP){kc(t,`audit`);return}K(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),Mc=q(ite,async(t,n,r)=>{try{let t=ZZ(r.docName,n,`lint-fix`);if(t===null)return;let i=pt(t),a=OD(r,ue);if(a.kind===`invalid-summary`){K(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,s=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(Zx(i)||Qx(i)){K(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=iQ(l,i);if(f===null){K(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}uN(z(l,f),l);let p=Oe?.()??kt,{stored:m}=An(a.summary),h=await c.getSession(i,o,{displayName:s,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await afe({projectDir:j??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=qr(d),n=xa[t]??Ui(u??o);re?.setPresence(o,{displayName:s,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{xw(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,yw(h))},h.origin),a.kind!==`anonymous`&&ej(i,o,s,u,void 0,a.kind===`agent`?En({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{re?.touchMode(o,`idle`)}let t=await At(i);if(t?.kind===`failure`){Mt(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){Nt(n,`lint-fix`);return}Ot(i,`lint-fix`);try{b=await Bn(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,X.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;J(n,200,qee,{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 tN){K(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof gS){_S(n,e,`lint-fix`);return}if(e instanceof xS){wS(n,e,`lint-fix`);return}if(e instanceof kw){K(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}X.error({err:e},`[lint-fix] handler failed`),K(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),Nc=`link-preview`,Pc=new HG({cacheDir:Ae?null:z(j??l,`.ok`,`local`,`link-previews`)}),Fc=null,Ic=()=>(Fc??=Pc.init(),Fc),Lc=Me??NG;async function Rc(e){let t=await Lc(e);return t.ok?{ok:!0,metadata:await RG({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:Lc})}:{ok:!1,reason:t.reason}}let zc=()=>{try{return Ne?.()===!0}catch{return!1}},Bc=q(Dte,async(e,t,n)=>{try{if(!zc()){X.debug({outcome:`disabled`},`[link-preview] request outcome`),J(t,200,tr,{ok:!1,reason:`disabled`},{handler:Nc});return}await Ic();let e=!1,r=await Pc.load(n.url,()=>(e=!0,Rc(n.url)));Pc.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};X.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),J(t,200,tr,i,{handler:Nc})}catch(e){K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:Nc,cause:e})}},{handler:Nc,method:`POST`,preBodyGate:(e,t)=>{let n=GG({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:Nc}):K(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:Nc}),!1)}}),Vc=$D({service:$e,getPrincipal:ue,onChanged:()=>A?.(`comments`)}),Hc=PW({GET:Vc.list,POST:Vc.create},{handler:`comments`}),Uc=PW({GET:Vc.read,POST:Vc.mutate,DELETE:Vc.remove},{handler:`comment`}),{handleSkillsSearch:Wc,handleSkillsPopular:Gc,handleSkillsPublisher:Kc,handleSkillsDetail:qc,handleSkillsPreview:Jc,handleSkillsDiscover:Yc,handleSkillsResolveRef:Xc}=Khe({log:X,skillsHome:Ya,projectDir:j,contentDir:l,resolveSkillDirForRead:Qa}),Zc={"/api/config":rc,"/api/config/diagnostics":ic,"/api/comments":Hc,"/api/comment":Uc,"/api/asset":Tr,"/api/asset-text":Dr,"/api/comment-counts":Gn,"/api/link-preview":Bc,"/api/folder-config":ja,"/api/saved-themes":Ma,"/api/saved-theme":Ia,"/api/template":Ga,"/api/template/import":Ka,"/api/templates":za,"/api/skill":Jo,"/api/skill-file":ns,"/api/skill-file/rename":rs,"/api/skills":Io,"/api/skills/installed":Wn,"/api/skills/search":Wc,"/api/skills/popular":Gc,"/api/skills/publisher":Kc,"/api/skills/detail":qc,"/api/skills/preview":Jc,"/api/skills/discover":Yc,"/api/skills/resolve-ref":Xc,"/api/skill/import":ys,"/api/skills/import-bulk":bs,"/api/skill/edit-external":Wo,"/api/skill/duplicate":qo,"/api/skill/move-scope":Ko,"/api/skill-upload":Es,"/api/skill/install":Ds,"/api/skill/uninstall":Os,"/api/skill/restore":As,"/api/skill/reimport":js,"/api/skill/revert":Ms,"/api/skill/track-in-git":Mo,"/api/skill-targets":ks,"/api/search":Bs,"/api/semantic-status":mc,"/api/lint/config":bc,"/api/lint/markdownlint-config":xc,"/api/lint/frontmatter-schema":Sc,"/api/lint/frontmatter-schemas":Cc,"/api/lint":Tc,"/api/lint/audit":Ac,"/api/lint/fix":Mc,"/api/audit":jc,"/api/create-page":kr,"/api/create-folder":jr,"/api/duplicate-path":Mr,"/api/rename-path":Nr,"/api/delete-path":Pr,"/api/trash/cleanup":Ir,"/api/upload":Lr,"/api/agent-write":Rn,"/api/agent-write-md":zn,"/api/agent-write-batch":Hn,"/api/frontmatter-patch":Un,"/api/agent-patch":Kn,"/api/agent-undo":qn,"/api/agent-activity":Yn,"/api/agent-burst-diff":Xn,"/api/save-version":lr,"/api/history":ur,"/api/rollback":pr,"/api/__embed-detect":br,"/api/server-info":mr,"/api/acp/catalog":gr,"/api/share/construct-url":Gs,"/api/share/target-status":qs,"/api/git/branch-info":Ks,"/api/git/checkout":Ys,"/api/share/publish/owners":Zs,"/api/share/publish/name-check":Qs,"/api/share/publish":$s,"/api/principal":yr,"/api/rescue":Or,"/api/workspace":Sr,"/api/sync/status":oa,"/api/sync/trigger":ga,"/api/sync/conflicts":_a,"/api/sync/conflict-content":ya,"/api/sync/resolve-conflict":va,"/api/local-op/clone":Gr,"/api/local-op/ok-init":$r,"/api/local-op/auth/login":bi,"/api/local-op/auth/status":Fi,"/api/local-op/auth/pat":zi,"/api/local-op/auth/gh-login":Ei,"/api/local-op/auth/cancel":Ni,"/api/local-op/auth/repos":Hi,"/api/local-op/auth/signout":Zi,"/api/local-op/auth/set-identity":ia,"/api/local-op/embeddings/set-key":lc,"/api/local-op/embeddings/clear-key":uc,"/api/local-op/embeddings/test":pc,"/api/installed-agents":Ta,"/api/spawn-cursor":Ws,"/api/handoff":Hs,"/api/install-skill":wa,"/api/skill/install-state":Vs,"/api/seed/plan":ba,"/api/seed/apply":Sa,"/api/seed/packs":Ca,"/api/client-logs":tc};C&&(Zc[`/api/test-reset`]=nr,Zc[`/api/test-flush-git`]=Qn,Zc[`/api/test-rescan-backlinks`]=rr,Zc[`/api/test-rescan-files`]=ir);let Qc=new Set(`/api/comments./api/comment./api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/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/client-logs`.split(`.`)),$c=[`/api/local-op/`],el=rV({log:X,policy:n,ephemeral:Ae,table:{resolve(e){let t=Zc[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 fr(e,n,decodeURIComponent(t))}:void 0}}return{template:`/api/*`}},isMutating:e=>Qc.has(e)||$c.some(t=>e.startsWith(t))}}),tl=AW({hocuspocus:s,derivedDocumentIndex:k,getFileIndex:f,isSafeDocName:hQ,readPageTitleForDocName:et,readPageTitleForLinkedDocName:tt,readFrontmatterMetadataForLinkedDocName:dt,collectAdmittedDocNames:Rt,resolveAlias:pt,respondToDerivedIndexQueryFailure:Gt}),nl=[tl,FW({hocuspocus:s,agentPresenceBroadcaster:re,isAllowedWorkspaceHostHeader:a,log:X}),Le],rl=nl.flatMap(e=>[...e.paths]);rW(rl,Zc);let il=nl.map(e=>rV({log:X,policy:n,ephemeral:Ae,table:e.table})),al={paths:rl,dispatch:async(e,t)=>{for(let n of il)if(await n(e,t))return!0;return!1}},ol=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 ol)if(Zc[e]===void 0&&tl.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 el(e,t)},nativeApi:al,localApi:NW({resolve:e=>{if(!ol.has(e))return;let t=Zc[e];return t===void 0?tl.table.resolve(e)?.dispatch:t}})}}function _Q(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=Il(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&&!qB(f,o)){K(s,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!YB(e.headers.host,o)){K(s,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:HB});return}s.setHeader(`X-Content-Type-Options`,`nosniff`);let p=AX(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=Ee.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 vQ(e){let t=e?.code;return typeof t==`string`?t:void 0}function jge(e){let t;try{t=tu(e.contentDir,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&Bx(n.name,w)&&e.basenameIndex.add(n.name)}async function yQ(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await vu(i,{withFileTypes:!0})}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=oN(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await gu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await yu(a)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!sN(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await bu(i)}catch(t){let n=vQ(t);n!==`ENOENT`&&e.onSkip?.(`symlink-stat-failed`,n,i);continue}if(n.has(o.ino))continue;n.add(o.ino),o.isDirectory()?await r(i):o.isFile()&&Bx(a,le)&&!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()&&Bx(a,le)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const bQ=N({principalId:u().optional(),tabSessionId:u().optional(),expectedServerInstanceId:u().optional(),expectedBranch:u().optional(),expectedDocLineageEpoch:u().optional(),clientProtocolVersion:i().optional(),clientRuntimeVersion:u().optional(),clientKind:u().optional()}).loose(),xQ=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function SQ(e){return xQ.includes(e)}function CQ(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function Mge(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!SQ(n))return{kind:null,payload:void 0};if(t===-1)return{kind:n,payload:void 0};let r=e.slice(t+1);return{kind:n,payload:r.length>0?r:void 0}}var wQ=class extends Error{kind;payload;reason;constructor(e,t,n){super(t),this.name=`HocuspocusAuthRejection`,this.kind=e,this.payload=typeof n==`string`&&n.length>0?n:void 0,this.reason=CQ(e,this.payload)}};function TQ(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=bQ.safeParse(t);return n.success?n.data:void 0}var EQ=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const DQ=F(`conflict-storage`);var OQ=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(dO(e),`conflicts.json`),this.projectDir=e,this.branch=t,this.load()}load(){if(!B(this.storePath)){this.conflicts=[];return}try{let e=V(this.storePath,`utf-8`),t=JSON.parse(e);if(t.version!==1){DQ.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){DQ.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||Xl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return cu(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return DQ.warn({err:e},`[conflicts] failed to save conflicts.json`),!1}}addConflict(e){if(e.variant===`working-tree`&&!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let t=this.conflicts.findIndex(t=>t.file===e.file);return t===-1?this.conflicts.push(e):this.conflicts[t]=e,this.save()}removeConflict(e){return this.conflicts=this.conflicts.filter(t=>t.file!==e),this.save()}clear(){this.conflicts=[],this.save()}count(){return this.conflicts.length}list(){return[...this.conflicts]}hasConflicts(){return this.conflicts.length>0}setBranch(e){this.branch=e}async resolveConflict(e,t,n,r=[]){let i=this.conflicts.find(t=>t.file===e);if(!i)throw Error(`[conflicts] no conflict tracked for file: ${e}`);if(t===`content`&&n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);if(i.variant===`working-tree`){await this.resolveWorkingTreeConflict(i,t,n,r);return}let{createGitInstance:a}=await import(`./git-handle-OIwLbjAT.mjs`),o=a(this.projectDir,{credentialArgs:r});switch(t){case`mine`:await o.git.raw([`checkout`,`--ours`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`theirs`:await o.git.raw([`checkout`,`--theirs`,`--`,e]),await o.git.raw([`add`,`--`,e]);break;case`content`:{if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);let t=z(this.projectDir),r=z(t,e);if(!sN(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);CL(r,t),vs(r,n,`utf-8`),await o.git.raw([`add`,`--`,e]);break}case`delete`:await o.git.raw([`rm`,`--`,e]);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}if(this.removeConflict(e),!this.hasConflicts())try{await o.git.raw([`commit`,`--no-edit`]),DQ.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await Wb(o.git,[`diff`,`--name-only`,`--diff-filter=U`]);for(let t of e)this.addConflict({file:t,detectedAt:n});r=e.length>0}catch(e){DQ.warn({err:e},`[conflicts] commit failed and re-scan of unmerged files failed — falling back to single-file re-add`)}r||this.addConflict({file:e,detectedAt:n}),DQ.warn({err:t},`[conflicts] failed to commit merge after all conflicts resolved — unmerged files re-added`);let i=t instanceof Error?t.message:String(t);throw Error(`Merge commit failed after resolving ${e}; ${r?`unmerged files re-added`:`original file re-added`} — ${i}`,{cause:t})}}async resolveWorkingTreeConflict(e,t,n,r){let i=z(this.projectDir),a=z(i,e.file);if(!sN(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(CL(a,i),t){case`mine`:break;case`theirs`:{if(!e.theirsSha)throw Error(`[conflicts] working-tree conflict for ${e.file} has no pinned theirs blob`);let{createGitInstance:t}=await import(`./git-handle-OIwLbjAT.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);CL(a,i),vs(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);vs(a,n,`utf-8`);break;case`delete`:B(a)&&is(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function Nge(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 Pge(e,t){let n=dO(e);try{Xl(n,{recursive:!0}),cu(L(n,Ei),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=Os(e);Xl(I(n),{recursive:!0});let r={level:60,time:Date.parse(t.timestamp),name:`crash`,origin:t.origin,err:t.error,pid:t.pid,uptimeSec:t.uptimeSec,msg:`fatal ${t.origin} — process crashing`};cu(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const kQ=new Map;let AQ=!1;function Fge(e,t){try{let n=Nge(e,t);for(let e of kQ.keys())Pge(e,n)}catch{}}function Ige(e){kQ.set(e,(kQ.get(e)??0)+1),AQ||(AQ=!0,process.on(`uncaughtExceptionMonitor`,Fge));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=kQ.get(e)??0;n<=1?kQ.delete(e):kQ.set(e,n-1)}}}function jQ(e){let t=e.scheduler??vi,n=e.warnBeforeMs??3e5,r=0,i=null,a=null,o=!1,s=!1;function c(){i!==null&&(t.clearTimeout(i),i=null),a!==null&&(t.clearTimeout(a),a=null)}function l(){c(),!(s||o)&&r===0&&(n>0&&n<e.thresholdMs&&(a=t.setTimeout(()=>{a=null,r===0&&!o&&e.log?.warn({msUntilShutdown:n,webSocketClientCount:0},`idle shutdown pending: no WebSocket clients`)},e.thresholdMs-n)),i=t.setTimeout(()=>{if(i=null,!(s||o)&&r===0){o=!0,e.log?.info({webSocketClientCount:0},`idle shutdown firing`);try{let t=e.onShutdown();t&&typeof t.then==`function`&&t.catch(t=>{e.log?.error({err:t},`idle shutdown handler rejected`)})}catch(t){e.log?.error({err:t},`idle shutdown handler threw`)}}},e.thresholdMs))}let u=(e,t)=>{e.url?.startsWith(`/collab`)&&(r++,c(),t.once(`close`,()=>{r--,r<0&&(r=0),r===0&&l()}))};return e.httpServer.on(`upgrade`,u),l(),{detach:()=>{s||(s=!0,e.httpServer.off(`upgrade`,u),c())}}}function MQ(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function NQ(e){if(!B(e))return{};let t;try{t=(0,CD.parse)(V(e,`utf-8`))}catch(t){return console.warn(`[telemetry.localSink] failed to parse ${e}; falling back to schema defaults — any explicit telemetry.localSink fields in this file are being ignored. Reason: ${t instanceof Error?t.message:String(t)}`),{}}if(!MQ(t))return{};let n=t.telemetry;if(!MQ(n))return{};let r=n.localSink;return MQ(r)?r:{}}function PQ(e){return typeof e==`boolean`?e:void 0}function Lge(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function FQ(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function IQ(e){if(MQ(e))return Lge(e.maxBytes)}function Rge(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=NQ(cs(`project`,e.projectDir)),n=NQ(cs(`project-local`,e.projectDir));if((PQ(n.enabled)??PQ(t.enabled)??!0)===!1)return null;let r=IQ(n.spans)??IQ(t.spans)??52428800,i=IQ(n.logs)??IQ(t.logs)??26214400,a=FQ(n.attributeDenylist)??FQ(t.attributeDenylist)??M;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var LQ;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(LQ||={});var zge;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(zge||={});const RQ=LQ.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),zQ=e=>{switch(typeof e){case`undefined`:return RQ.undefined;case`string`:return RQ.string;case`number`:return Number.isNaN(e)?RQ.nan:RQ.number;case`boolean`:return RQ.boolean;case`function`:return RQ.function;case`bigint`:return RQ.bigint;case`symbol`:return RQ.symbol;case`object`:return Array.isArray(e)?RQ.array:e===null?RQ.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?RQ.promise:typeof Map<`u`&&e instanceof Map?RQ.map:typeof Set<`u`&&e instanceof Set?RQ.set:typeof Date<`u`&&e instanceof Date?RQ.date:RQ.object;default:return RQ.unknown}},Z=LQ.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var BQ=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r];r===i.path.length-1?(e[n]=e[n]||{_errors:[]},e[n]._errors.push(t(i))):e[n]=e[n]||{_errors:[]},e=e[n],r++}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,LQ.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};BQ.create=e=>new BQ(e);const VQ=(e,t)=>{let n;switch(e.code){case Z.invalid_type:n=e.received===RQ.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,LQ.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${LQ.joinValues(e.keys,`, `)}`;break;case Z.invalid_union:n=`Invalid input`;break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${LQ.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${LQ.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n=`Invalid function arguments`;break;case Z.invalid_return_type:n=`Invalid function return type`;break;case Z.invalid_date:n=`Invalid date`;break;case Z.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:LQ.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case Z.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case Z.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case Z.custom:n=`Invalid input`;break;case Z.invalid_intersection_types:n=`Intersection results could not be merged`;break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,LQ.assertNever(e)}return{message:n}};let Bge=VQ;function HQ(){return Bge}const UQ=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function WQ(e,t){let n=HQ(),r=UQ({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===VQ?void 0:VQ].filter(e=>!!e)});e.common.issues.push(r)}var GQ=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return KQ;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return KQ;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const KQ=Object.freeze({status:`aborted`}),qQ=e=>({status:`dirty`,value:e}),JQ=e=>({status:`valid`,value:e}),YQ=e=>e.status===`aborted`,XQ=e=>e.status===`dirty`,ZQ=e=>e.status===`valid`,QQ=e=>typeof Promise<`u`&&e instanceof Promise;var $Q;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})($Q||={});var e$=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const t$=(e,t)=>{if(ZQ(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new BQ(e.common.issues);return this._error=t,this._error}}};function n$(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var r$=class{get description(){return this._def.description}_getType(e){return zQ(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new GQ,ctx:{common:e.parent.common,data:e.data,parsedType:zQ(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(QQ(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)};return t$(n,this._parseSync({data:e,path:n.path,parent:n}))}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ZQ(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ZQ(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:zQ(e)},r=this._parse({data:e,path:n.path,parent:n});return t$(n,await(QQ(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:Z.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new F$({schema:this,typeName:Q.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return I$.create(this,this._def)}nullable(){return L$.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return y$.create(this)}promise(){return P$.create(this,this._def)}or(e){return S$.create([this,e],this._def)}and(e){return T$.create(this,e,this._def)}transform(e){return new F$({...n$(this._def),schema:this,typeName:Q.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new R$({...n$(this._def),innerType:this,defaultValue:t,typeName:Q.ZodDefault})}brand(){return new V$({typeName:Q.ZodBranded,type:this,...n$(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new z$({...n$(this._def),innerType:this,catchValue:t,typeName:Q.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return H$.create(this,e)}readonly(){return U$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const Vge=/^c[^\s-]{8,}$/i,Hge=/^[0-9a-z]+$/,Uge=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Wge=/^[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,Gge=/^[a-z0-9_-]{21}$/i,Kge=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qge=/^[-+]?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)?)??$/,Jge=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let i$;const Yge=/^(?:(?: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])$/,Xge=/^(?:(?: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])$/,Zge=/^(([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]))$/,Qge=/^(([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])$/,$ge=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,e_e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,a$=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,t_e=RegExp(`^${a$}$`);function o$(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function n_e(e){return RegExp(`^${o$(e)}$`)}function r_e(e){let t=`${a$}T${o$(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function i_e(e,t){return!!((t===`v4`||!t)&&Yge.test(e)||(t===`v6`||!t)&&Zge.test(e))}function a_e(e,t){if(!Kge.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 o_e(e,t){return!!((t===`v4`||!t)&&Xge.test(e)||(t===`v6`||!t)&&Qge.test(e))}var s$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==RQ.string){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.string,received:t.parsedType}),KQ}let t=new GQ,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?WQ(n,{code:Z.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&WQ(n,{code:Z.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)Jge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`email`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)i$||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),i$.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`emoji`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)Wge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`uuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)Gge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`nanoid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)Vge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)Hge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cuid2`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)Uge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ulid`,code:Z.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),WQ(n,{validation:`url`,code:Z.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`regex`,code:Z.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?r_e(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?t_e.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?n_e(r).test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?qge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`duration`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?i_e(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`ip`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?a_e(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`jwt`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?o_e(e.data,r.version)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`cidr`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?$ge.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64`,code:Z.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?e_e.test(e.data)||(n=this._getOrReturnCtx(e,n),WQ(n,{validation:`base64url`,code:Z.invalid_string,message:r.message}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:Z.invalid_string,...$Q.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...$Q.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...$Q.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...$Q.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...$Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...$Q.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...$Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...$Q.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...$Q.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...$Q.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...$Q.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...$Q.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...$Q.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...$Q.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...$Q.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...$Q.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...$Q.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...$Q.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...$Q.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...$Q.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...$Q.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...$Q.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...$Q.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...$Q.errToObj(t)})}nonempty(e){return this.min(1,$Q.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};s$.create=e=>new s$({checks:[],typeName:Q.ZodString,coerce:e?.coerce??!1,...n$(e)});function s_e(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var c$=class e extends r${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==RQ.number){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.number,received:t.parsedType}),KQ}let t,n=new GQ;for(let r of this._def.checks)r.kind===`int`?LQ.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?s_e(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_finite,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:$Q.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:$Q.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:$Q.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:$Q.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&LQ.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};c$.create=e=>new c$({checks:[],typeName:Q.ZodNumber,coerce:e?.coerce||!1,...n$(e)});var l$=class e extends r${constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==RQ.bigint)return this._getInvalidInput(e);let t,n=new GQ;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),WQ(t,{code:Z.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):LQ.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.bigint,received:t.parsedType}),KQ}gte(e,t){return this.setLimit(`min`,e,!0,$Q.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,$Q.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,$Q.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,$Q.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:$Q.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:$Q.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:$Q.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:$Q.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};l$.create=e=>new l$({checks:[],typeName:Q.ZodBigInt,coerce:e?.coerce??!1,...n$(e)});var u$=class extends r${_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==RQ.boolean){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.boolean,received:t.parsedType}),KQ}return JQ(e.data)}};u$.create=e=>new u$({typeName:Q.ZodBoolean,coerce:e?.coerce||!1,...n$(e)});var d$=class e extends r${_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==RQ.date){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.date,received:t.parsedType}),KQ}if(Number.isNaN(e.data.getTime()))return WQ(this._getOrReturnCtx(e),{code:Z.invalid_date}),KQ;let t=new GQ,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),WQ(n,{code:Z.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):LQ.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:$Q.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:$Q.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};d$.create=e=>new d$({checks:[],coerce:e?.coerce||!1,typeName:Q.ZodDate,...n$(e)});var f$=class extends r${_parse(e){if(this._getType(e)!==RQ.symbol){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.symbol,received:t.parsedType}),KQ}return JQ(e.data)}};f$.create=e=>new f$({typeName:Q.ZodSymbol,...n$(e)});var p$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.undefined,received:t.parsedType}),KQ}return JQ(e.data)}};p$.create=e=>new p$({typeName:Q.ZodUndefined,...n$(e)});var m$=class extends r${_parse(e){if(this._getType(e)!==RQ.null){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.null,received:t.parsedType}),KQ}return JQ(e.data)}};m$.create=e=>new m$({typeName:Q.ZodNull,...n$(e)});var h$=class extends r${constructor(){super(...arguments),this._any=!0}_parse(e){return JQ(e.data)}};h$.create=e=>new h$({typeName:Q.ZodAny,...n$(e)});var g$=class extends r${constructor(){super(...arguments),this._unknown=!0}_parse(e){return JQ(e.data)}};g$.create=e=>new g$({typeName:Q.ZodUnknown,...n$(e)});var _$=class extends r${_parse(e){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.never,received:t.parsedType}),KQ}};_$.create=e=>new _$({typeName:Q.ZodNever,...n$(e)});var v$=class extends r${_parse(e){if(this._getType(e)!==RQ.undefined){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.void,received:t.parsedType}),KQ}return JQ(e.data)}};v$.create=e=>new v$({typeName:Q.ZodVoid,...n$(e)});var y$=class e extends r${_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==RQ.array)return WQ(t,{code:Z.invalid_type,expected:RQ.array,received:t.parsedType}),KQ;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(WQ(t,{code:e?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(WQ(t,{code:Z.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(WQ(t,{code:Z.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new e$(t,e,t.path,n)))).then(e=>GQ.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new e$(t,e,t.path,n)));return GQ.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:$Q.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:$Q.toString(n)}})}nonempty(e){return this.min(1,e)}};y$.create=(e,t)=>new y$({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Q.ZodArray,...n$(t)});function b$(e){if(e instanceof x$){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=I$.create(b$(r))}return new x$({...e._def,shape:()=>t})}else if(e instanceof y$)return new y$({...e._def,type:b$(e.element)});else if(e instanceof I$)return I$.create(b$(e.unwrap()));else if(e instanceof L$)return L$.create(b$(e.unwrap()));else if(e instanceof E$)return E$.create(e.items.map(e=>b$(e)));else return e}var x$=class e extends r${constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=LQ.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==RQ.object){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.object,received:t.parsedType}),KQ}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof _$&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new e$(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof _$){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(WQ(n,{code:Z.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new e$(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>GQ.mergeObjectSync(t,e)):GQ.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return $Q.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:$Q.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Q.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of LQ.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of LQ.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return b$(this)}partial(t){let n={};for(let e of LQ.objectKeys(this.shape)){let r=this.shape[e];t&&!t[e]?n[e]=r:n[e]=r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of LQ.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof I$;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return j$(LQ.objectKeys(this.shape))}};x$.create=(e,t)=>new x$({shape:()=>e,unknownKeys:`strip`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)}),x$.strictCreate=(e,t)=>new x$({shape:()=>e,unknownKeys:`strict`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)}),x$.lazycreate=(e,t)=>new x$({shape:e,unknownKeys:`strip`,catchall:_$.create(),typeName:Q.ZodObject,...n$(t)});var S$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new BQ(e.ctx.common.issues));return WQ(t,{code:Z.invalid_union,unionErrors:n}),KQ}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new BQ(e));return WQ(t,{code:Z.invalid_union,unionErrors:i}),KQ}}get options(){return this._def.options}};S$.create=(e,t)=>new S$({options:e,typeName:Q.ZodUnion,...n$(t)});const C$=e=>e instanceof k$?C$(e.schema):e instanceof F$?C$(e.innerType()):e instanceof A$?[e.value]:e instanceof M$?e.options:e instanceof N$?LQ.objectValues(e.enum):e instanceof R$?C$(e._def.innerType):e instanceof p$?[void 0]:e instanceof m$?[null]:e instanceof I$?[void 0,...C$(e.unwrap())]:e instanceof L$?[null,...C$(e.unwrap())]:e instanceof V$||e instanceof U$?C$(e.unwrap()):e instanceof z$?C$(e._def.innerType):[];var c_e=class e extends r${_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.object)return WQ(t,{code:Z.invalid_type,expected:RQ.object,received:t.parsedType}),KQ;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(WQ(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),KQ)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let e of n){let n=C$(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Q.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...n$(r)})}};function w$(e,t){let n=zQ(e),r=zQ(t);if(e===t)return{valid:!0,data:e};if(n===RQ.object&&r===RQ.object){let n=LQ.objectKeys(t),r=LQ.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=w$(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===RQ.array&&r===RQ.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=w$(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===RQ.date&&r===RQ.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var T$=class extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(YQ(e)||YQ(r))return KQ;let i=w$(e.value,r.value);return i.valid?((XQ(e)||XQ(r))&&t.dirty(),{status:t.value,value:i.data}):(WQ(n,{code:Z.invalid_intersection_types}),KQ)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};T$.create=(e,t,n)=>new T$({left:e,right:t,typeName:Q.ZodIntersection,...n$(n)});var E$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.array)return WQ(n,{code:Z.invalid_type,expected:RQ.array,received:n.parsedType}),KQ;if(n.data.length<this._def.items.length)return WQ(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),KQ;!this._def.rest&&n.data.length>this._def.items.length&&(WQ(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new e$(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>GQ.mergeArray(t,e)):GQ.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};E$.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new E$({items:e,typeName:Q.ZodTuple,rest:null,...n$(t)})};var l_e=class e extends r${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.object)return WQ(n,{code:Z.invalid_type,expected:RQ.object,received:n.parsedType}),KQ;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new e$(n,e,n.path,e)),value:a._parse(new e$(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?GQ.mergeObjectAsync(t,r):GQ.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof r$?new e({keyType:t,valueType:n,typeName:Q.ZodRecord,...n$(r)}):new e({keyType:s$.create(),valueType:t,typeName:Q.ZodRecord,...n$(n)})}},D$=class extends r${get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.map)return WQ(n,{code:Z.invalid_type,expected:RQ.map,received:n.parsedType}),KQ;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new e$(n,e,n.path,[a,`key`])),value:i._parse(new e$(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}else{let e=new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return KQ;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};D$.create=(e,t,n)=>new D$({valueType:t,keyType:e,typeName:Q.ZodMap,...n$(n)});var O$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==RQ.set)return WQ(n,{code:Z.invalid_type,expected:RQ.set,received:n.parsedType}),KQ;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(WQ(n,{code:Z.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(WQ(n,{code:Z.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return KQ;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new e$(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:$Q.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:$Q.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};O$.create=(e,t)=>new O$({valueType:e,minSize:null,maxSize:null,typeName:Q.ZodSet,...n$(t)});var u_e=class e extends r${constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==RQ.function)return WQ(t,{code:Z.invalid_type,expected:RQ.function,received:t.parsedType}),KQ;function n(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Z.invalid_arguments,argumentsError:n}})}function r(e,n){return UQ({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,HQ(),VQ].filter(e=>!!e),issueData:{code:Z.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof P$){let e=this;return JQ(async function(...t){let o=new BQ([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}else{let e=this;return JQ(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new BQ([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new BQ([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:E$.create(t).rest(g$.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||E$.create([]).rest(g$.create()),returns:n||g$.create(),typeName:Q.ZodFunction,...n$(r)})}},k$=class extends r${get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};k$.create=(e,t)=>new k$({getter:e,typeName:Q.ZodLazy,...n$(t)});var A$=class extends r${_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return WQ(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),KQ}return{status:`valid`,value:e.data}}get value(){return this._def.value}};A$.create=(e,t)=>new A$({value:e,typeName:Q.ZodLiteral,...n$(t)});function j$(e,t){return new M$({values:e,typeName:Q.ZodEnum,...n$(t)})}var M$=class e extends r${_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{expected:LQ.joinValues(n),received:t.parsedType,code:Z.invalid_type}),KQ}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return WQ(t,{received:t.data,code:Z.invalid_enum_value,options:n}),KQ}return JQ(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};M$.create=j$;var N$=class extends r${_parse(e){let t=LQ.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==RQ.string&&n.parsedType!==RQ.number){let e=LQ.objectValues(t);return WQ(n,{expected:LQ.joinValues(e),received:n.parsedType,code:Z.invalid_type}),KQ}if(this._cache||=new Set(LQ.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=LQ.objectValues(t);return WQ(n,{received:n.data,code:Z.invalid_enum_value,options:e}),KQ}return JQ(e.data)}get enum(){return this._def.values}};N$.create=(e,t)=>new N$({values:e,typeName:Q.ZodNativeEnum,...n$(t)});var P$=class extends r${unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==RQ.promise&&t.common.async===!1?(WQ(t,{code:Z.invalid_type,expected:RQ.promise,received:t.parsedType}),KQ):JQ((t.parsedType===RQ.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};P$.create=(e,t)=>new P$({type:e,typeName:Q.ZodPromise,...n$(t)});var F$=class extends r${innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Q.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{WQ(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return KQ;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r});{if(t.value===`aborted`)return KQ;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?KQ:r.status===`dirty`||t.value===`dirty`?qQ(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?KQ:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?KQ:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`)if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ZQ(e))return KQ;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ZQ(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):KQ);LQ.assertNever(r)}};F$.create=(e,t,n)=>new F$({schema:e,typeName:Q.ZodEffects,effect:t,...n$(n)}),F$.createWithPreprocess=(e,t,n)=>new F$({schema:t,effect:{type:`preprocess`,transform:e},typeName:Q.ZodEffects,...n$(n)});var I$=class extends r${_parse(e){return this._getType(e)===RQ.undefined?JQ(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};I$.create=(e,t)=>new I$({innerType:e,typeName:Q.ZodOptional,...n$(t)});var L$=class extends r${_parse(e){return this._getType(e)===RQ.null?JQ(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};L$.create=(e,t)=>new L$({innerType:e,typeName:Q.ZodNullable,...n$(t)});var R$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===RQ.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};R$.create=(e,t)=>new R$({innerType:e,typeName:Q.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...n$(t)});var z$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return QQ(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new BQ(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};z$.create=(e,t)=>new z$({innerType:e,typeName:Q.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...n$(t)});var B$=class extends r${_parse(e){if(this._getType(e)!==RQ.nan){let t=this._getOrReturnCtx(e);return WQ(t,{code:Z.invalid_type,expected:RQ.nan,received:t.parsedType}),KQ}return{status:`valid`,value:e.data}}};B$.create=e=>new B$({typeName:Q.ZodNaN,...n$(e)});var V$=class extends r${_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},H$=class e extends r${_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KQ:e.status===`dirty`?(t.dirty(),qQ(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?KQ:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Q.ZodPipeline})}},U$=class extends r${_parse(e){let t=this._def.innerType._parse(e),n=e=>(ZQ(e)&&(e.value=Object.freeze(e.value)),e);return QQ(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};U$.create=(e,t)=>new U$({innerType:e,typeName:Q.ZodReadonly,...n$(t)}),x$.lazycreate;var Q;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Q||={}),s$.create,c$.create,B$.create,l$.create,u$.create,d$.create,f$.create,p$.create,m$.create,h$.create,g$.create,_$.create,v$.create,y$.create;const d_e=x$.create;x$.strictCreate,S$.create,c_e.create,T$.create,E$.create,l_e.create,D$.create,O$.create,u_e.create,k$.create,A$.create,M$.create,N$.create,P$.create,F$.create,I$.create,L$.create,F$.createWithPreprocess,H$.create;const f_e=de(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);d.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>h(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>m(e,t,n),e.parseAsync=async(t,n)=>we(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>oe(e,t,n),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0}),e.with=e.check,e.clone=(t,n)=>se(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),p_e=de(`ZodMiniObject`,(e,t)=>{ie.init(e,t),f_e.init(e,t),T(e,`shape`,()=>t.shape)});function W$(e,t){return new p_e({type:`object`,shape:e??{},...r(t)})}function G$(e){return!!e._zod}function K$(e){let t=Object.values(e);if(t.length===0)return W$({});let n=t.every(G$),r=t.every(e=>!G$(e));if(n)return W$(e);if(r)return d_e(e);throw Error(`Mixed Zod versions detected in object shape.`)}function q$(e,t){return G$(e)?m(e,t):e.safeParse(t)}async function J$(e,t){return G$(e)?await oe(e,t):await e.safeParseAsync(t)}function Y$(e){if(!e)return;let t;if(t=G$(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function X$(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return K$(e)}}if(G$(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Z$(e){if(e&&typeof e==`object`){if(`message`in e&&typeof e.message==`string`)return e.message;if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0){let t=e.issues[0];if(t&&typeof t==`object`&&`message`in t)return String(t.message)}try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function m_e(e){return e.description}function h_e(e){if(G$(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function Q$(e){if(G$(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const $$=`2025-11-25`,e1=[$$,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],t1=`io.modelcontextprotocol/related-task`,n1=s(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),r1=p([u(),i().int()]),i1=u();ve({ttl:i().optional(),pollInterval:i().optional()});const g_e=N({ttl:i().optional()}),__e=N({taskId:u()}),a1=ve({progressToken:r1.optional(),[t1]:__e.optional()}),o1=N({_meta:a1.optional()}),s1=o1.extend({task:g_e.optional()}),v_e=e=>s1.safeParse(e).success,c1=N({method:u(),params:o1.loose().optional()}),l1=N({_meta:a1.optional()}),u1=N({method:u(),params:l1.loose().optional()}),d1=ve({_meta:a1.optional()}),f1=p([u(),i().int()]),p1=N({jsonrpc:x(`2.0`),id:f1,...c1.shape}).strict(),m1=e=>p1.safeParse(e).success,h1=N({jsonrpc:x(`2.0`),...u1.shape}).strict(),y_e=e=>h1.safeParse(e).success,g1=N({jsonrpc:x(`2.0`),id:f1,result:d1}).strict(),_1=e=>g1.safeParse(e).success;var v1;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(v1||={});const y1=N({jsonrpc:x(`2.0`),id:f1.optional(),error:N({code:i().int(),message:u(),data:_().optional()})}).strict(),b1=e=>y1.safeParse(e).success,x1=p([p1,h1,g1,y1]);p([g1,y1]);const S1=d1.strict(),b_e=l1.extend({requestId:f1.optional(),reason:u().optional()}),C1=u1.extend({method:x(`notifications/cancelled`),params:b_e}),w1=N({icons:P(N({src:u(),mimeType:u().optional(),sizes:P(u()).optional(),theme:je([`light`,`dark`]).optional()})).optional()}),T1=N({name:u(),title:u().optional()}),E1=T1.extend({...T1.shape,...w1.shape,version:u(),websiteUrl:u().optional(),description:u().optional()}),x_e=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c(N({form:c(N({applyDefaults:D().optional()}),C(u(),_())).optional(),url:n1.optional()}),C(u(),_()).optional())),S_e=ve({list:n1.optional(),cancel:n1.optional(),requests:ve({sampling:ve({createMessage:n1.optional()}).optional(),elicitation:ve({create:n1.optional()}).optional()}).optional()}),C_e=ve({list:n1.optional(),cancel:n1.optional(),requests:ve({tools:ve({call:n1.optional()}).optional()}).optional()}),w_e=N({experimental:C(u(),n1).optional(),sampling:N({context:n1.optional(),tools:n1.optional()}).optional(),elicitation:x_e.optional(),roots:N({listChanged:D().optional()}).optional(),tasks:S_e.optional(),extensions:C(u(),n1).optional()}),T_e=o1.extend({protocolVersion:u(),capabilities:w_e,clientInfo:E1}),D1=c1.extend({method:x(`initialize`),params:T_e}),O1=e=>D1.safeParse(e).success,E_e=N({experimental:C(u(),n1).optional(),logging:n1.optional(),completions:n1.optional(),prompts:N({listChanged:D().optional()}).optional(),resources:N({subscribe:D().optional(),listChanged:D().optional()}).optional(),tools:N({listChanged:D().optional()}).optional(),tasks:C_e.optional(),extensions:C(u(),n1).optional()}),D_e=d1.extend({protocolVersion:u(),capabilities:E_e,serverInfo:E1,instructions:u().optional()}),k1=u1.extend({method:x(`notifications/initialized`),params:l1.optional()}),O_e=e=>k1.safeParse(e).success,A1=c1.extend({method:x(`ping`),params:o1.optional()}),k_e=N({progress:i(),total:v(i()),message:v(u())}),A_e=N({...l1.shape,...k_e.shape,progressToken:r1}),j1=u1.extend({method:x(`notifications/progress`),params:A_e}),j_e=o1.extend({cursor:i1.optional()}),M1=c1.extend({params:j_e.optional()}),N1=d1.extend({nextCursor:i1.optional()}),M_e=je([`working`,`input_required`,`completed`,`failed`,`cancelled`]),P1=N({taskId:u(),status:M_e,ttl:p([i(),Fe()]),createdAt:u(),lastUpdatedAt:u(),pollInterval:v(i()),statusMessage:v(u())}),F1=d1.extend({task:P1}),N_e=l1.merge(P1),I1=u1.extend({method:x(`notifications/tasks/status`),params:N_e}),L1=c1.extend({method:x(`tasks/get`),params:o1.extend({taskId:u()})}),R1=d1.merge(P1),z1=c1.extend({method:x(`tasks/result`),params:o1.extend({taskId:u()})});d1.loose();const B1=M1.extend({method:x(`tasks/list`)}),V1=N1.extend({tasks:P(P1)}),H1=c1.extend({method:x(`tasks/cancel`),params:o1.extend({taskId:u()})}),P_e=d1.merge(P1),U1=N({uri:u(),mimeType:v(u()),_meta:C(u(),_()).optional()}),W1=U1.extend({text:u()}),G1=u().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),K1=U1.extend({blob:G1}),q1=je([`user`,`assistant`]),J1=N({audience:P(q1).optional(),priority:i().min(0).max(1).optional(),lastModified:a({offset:!0}).optional()}),Y1=N({...T1.shape,...w1.shape,uri:u(),description:v(u()),mimeType:v(u()),size:v(i()),annotations:J1.optional(),_meta:v(ve({}))}),F_e=N({...T1.shape,...w1.shape,uriTemplate:u(),description:v(u()),mimeType:v(u()),annotations:J1.optional(),_meta:v(ve({}))}),X1=M1.extend({method:x(`resources/list`)}),I_e=N1.extend({resources:P(Y1)}),Z1=M1.extend({method:x(`resources/templates/list`)}),L_e=N1.extend({resourceTemplates:P(F_e)}),Q1=o1.extend({uri:u()}),R_e=Q1,$1=c1.extend({method:x(`resources/read`),params:R_e}),z_e=d1.extend({contents:P(p([W1,K1]))}),B_e=u1.extend({method:x(`notifications/resources/list_changed`),params:l1.optional()}),V_e=Q1,H_e=c1.extend({method:x(`resources/subscribe`),params:V_e}),U_e=Q1,W_e=c1.extend({method:x(`resources/unsubscribe`),params:U_e}),G_e=l1.extend({uri:u()}),K_e=u1.extend({method:x(`notifications/resources/updated`),params:G_e}),q_e=N({name:u(),description:v(u()),required:v(D())}),J_e=N({...T1.shape,...w1.shape,description:v(u()),arguments:v(P(q_e)),_meta:v(ve({}))}),e0=M1.extend({method:x(`prompts/list`)}),Y_e=N1.extend({prompts:P(J_e)}),X_e=o1.extend({name:u(),arguments:C(u(),u()).optional()}),t0=c1.extend({method:x(`prompts/get`),params:X_e}),n0=N({type:x(`text`),text:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),r0=N({type:x(`image`),data:G1,mimeType:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),i0=N({type:x(`audio`),data:G1,mimeType:u(),annotations:J1.optional(),_meta:C(u(),_()).optional()}),Z_e=N({type:x(`tool_use`),name:u(),id:u(),input:C(u(),_()),_meta:C(u(),_()).optional()}),Q_e=N({type:x(`resource`),resource:p([W1,K1]),annotations:J1.optional(),_meta:C(u(),_()).optional()}),a0=p([n0,r0,i0,Y1.extend({type:x(`resource_link`)}),Q_e]),$_e=N({role:q1,content:a0}),eve=d1.extend({description:u().optional(),messages:P($_e)}),tve=u1.extend({method:x(`notifications/prompts/list_changed`),params:l1.optional()}),nve=N({title:u().optional(),readOnlyHint:D().optional(),destructiveHint:D().optional(),idempotentHint:D().optional(),openWorldHint:D().optional()}),rve=N({taskSupport:je([`required`,`optional`,`forbidden`]).optional()}),o0=N({...T1.shape,...w1.shape,description:u().optional(),inputSchema:N({type:x(`object`),properties:C(u(),n1).optional(),required:P(u()).optional()}).catchall(_()),outputSchema:N({type:x(`object`),properties:C(u(),n1).optional(),required:P(u()).optional()}).catchall(_()).optional(),annotations:nve.optional(),execution:rve.optional(),_meta:C(u(),_()).optional()}),s0=M1.extend({method:x(`tools/list`)}),ive=N1.extend({tools:P(o0)}),c0=d1.extend({content:P(a0).default([]),structuredContent:C(u(),_()).optional(),isError:D().optional()});c0.or(d1.extend({toolResult:_()}));const ave=s1.extend({name:u(),arguments:C(u(),_()).optional()}),l0=c1.extend({method:x(`tools/call`),params:ave}),ove=u1.extend({method:x(`notifications/tools/list_changed`),params:l1.optional()});N({autoRefresh:D().default(!0),debounceMs:i().int().nonnegative().default(300)});const u0=je([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),sve=o1.extend({level:u0}),d0=c1.extend({method:x(`logging/setLevel`),params:sve}),cve=l1.extend({level:u0,logger:u().optional(),data:_()}),lve=u1.extend({method:x(`notifications/message`),params:cve}),uve=N({hints:P(N({name:u().optional()})).optional(),costPriority:i().min(0).max(1).optional(),speedPriority:i().min(0).max(1).optional(),intelligencePriority:i().min(0).max(1).optional()}),dve=N({mode:je([`auto`,`required`,`none`]).optional()}),fve=N({type:x(`tool_result`),toolUseId:u().describe(`The unique identifier for the corresponding tool call.`),content:P(a0).default([]),structuredContent:N({}).loose().optional(),isError:D().optional(),_meta:C(u(),_()).optional()}),pve=Ne(`type`,[n0,r0,i0]),f0=Ne(`type`,[n0,r0,i0,Z_e,fve]),mve=N({role:q1,content:p([f0,P(f0)]),_meta:C(u(),_()).optional()}),hve=s1.extend({messages:P(mve),modelPreferences:uve.optional(),systemPrompt:u().optional(),includeContext:je([`none`,`thisServer`,`allServers`]).optional(),temperature:i().optional(),maxTokens:i().int(),stopSequences:P(u()).optional(),metadata:n1.optional(),tools:P(o0).optional(),toolChoice:dve.optional()}),gve=c1.extend({method:x(`sampling/createMessage`),params:hve}),p0=d1.extend({model:u(),stopReason:v(je([`endTurn`,`stopSequence`,`maxTokens`]).or(u())),role:q1,content:pve}),m0=d1.extend({model:u(),stopReason:v(je([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(u())),role:q1,content:p([f0,P(f0)])}),_ve=N({type:x(`boolean`),title:u().optional(),description:u().optional(),default:D().optional()}),vve=N({type:x(`string`),title:u().optional(),description:u().optional(),minLength:i().optional(),maxLength:i().optional(),format:je([`email`,`uri`,`date`,`date-time`]).optional(),default:u().optional()}),yve=N({type:je([`number`,`integer`]),title:u().optional(),description:u().optional(),minimum:i().optional(),maximum:i().optional(),default:i().optional()}),bve=N({type:x(`string`),title:u().optional(),description:u().optional(),enum:P(u()),default:u().optional()}),xve=N({type:x(`string`),title:u().optional(),description:u().optional(),oneOf:P(N({const:u(),title:u()})),default:u().optional()}),Sve=p([p([N({type:x(`string`),title:u().optional(),description:u().optional(),enum:P(u()),enumNames:P(u()).optional(),default:u().optional()}),p([bve,xve]),p([N({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:N({type:x(`string`),enum:P(u())}),default:P(u()).optional()}),N({type:x(`array`),title:u().optional(),description:u().optional(),minItems:i().optional(),maxItems:i().optional(),items:N({anyOf:P(N({const:u(),title:u()}))}),default:P(u()).optional()})])]),_ve,vve,yve]),Cve=p([s1.extend({mode:x(`form`).optional(),message:u(),requestedSchema:N({type:x(`object`),properties:C(u(),Sve),required:P(u()).optional()})}),s1.extend({mode:x(`url`),message:u(),elicitationId:u(),url:u().url()})]),wve=c1.extend({method:x(`elicitation/create`),params:Cve}),Tve=l1.extend({elicitationId:u()}),Eve=u1.extend({method:x(`notifications/elicitation/complete`),params:Tve}),h0=d1.extend({action:je([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,C(u(),p([u(),i(),D(),P(u())])).optional())}),Dve=N({type:x(`ref/resource`),uri:u()}),Ove=N({type:x(`ref/prompt`),name:u()}),kve=o1.extend({ref:p([Ove,Dve]),argument:N({name:u(),value:u()}),context:N({arguments:C(u(),u()).optional()}).optional()}),g0=c1.extend({method:x(`completion/complete`),params:kve});function Ave(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function jve(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const Mve=d1.extend({completion:ve({values:P(u()).max(100),total:v(i().int()),hasMore:v(D())})}),Nve=N({uri:u().startsWith(`file://`),name:u().optional(),_meta:C(u(),_()).optional()}),Pve=c1.extend({method:x(`roots/list`),params:o1.optional()}),_0=d1.extend({roots:P(Nve)}),Fve=u1.extend({method:x(`notifications/roots/list_changed`),params:l1.optional()});p([A1,D1,g0,d0,t0,e0,X1,Z1,$1,H_e,W_e,l0,s0,L1,z1,B1,H1]),p([C1,j1,k1,Fve,I1]),p([S1,p0,m0,h0,_0,R1,V1,F1]),p([A1,gve,wve,Pve,L1,z1,B1,H1]),p([C1,j1,lve,K_e,B_e,ove,tve,I1,Eve]),p([S1,D_e,Mve,eve,Y_e,I_e,L_e,z_e,c0,ive,R1,V1,F1]);var v0=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===v1.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ive(e.elicitations,n)}return new e(t,n,r)}},Ive=class extends v0{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(v1.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function y0(e){return e===`completed`||e===`failed`||e===`cancelled`}const Lve=Symbol(`Let zodToJsonSchema decide on which parser to use`),b0={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},Rve=e=>typeof e==`string`?{...b0,name:e}:{...b0,...e},zve=e=>{let t=Rve(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function x0(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function S0(e,t,n,r,i){e[t]=n,x0(e,t,r,i)}const C0=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function w0(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?C0(t,e.currentPath):t.join(`/`)}}function Bve(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Q.ZodAny&&(n.items=L0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&S0(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&S0(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(S0(n,`minItems`,e.exactLength.value,e.exactLength.message,t),S0(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function Vve(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function Hve(){return{type:`boolean`}}function T0(e,t){return L0(e.type._def,t)}const Uve=(e,t)=>L0(e.innerType._def,t);function E0(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>E0(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return Wve(e,t)}}const Wve=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minimum`,r.value,r.message,t);break;case`max`:S0(n,`maximum`,r.value,r.message,t);break}return n};function Gve(e,t){return{...L0(e.innerType._def,t),default:e.defaultValue()}}function Kve(e,t){return t.effectStrategy===`input`?L0(e.schema._def,t):w0(t)}function qve(e){return{type:`string`,enum:Array.from(e.values)}}const Jve=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Yve(e,t){let n=[L0(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),L0(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Jve(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 Xve(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let D0;const O0={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(D0===void 0&&(D0=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),D0),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function k0(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:j0(n,`email`,r.message,t);break;case`format:idn-email`:j0(n,`idn-email`,r.message,t);break;case`pattern:zod`:M0(n,O0.email,r.message,t);break}break;case`url`:j0(n,`uri`,r.message,t);break;case`uuid`:j0(n,`uuid`,r.message,t);break;case`regex`:M0(n,r.regex,r.message,t);break;case`cuid`:M0(n,O0.cuid,r.message,t);break;case`cuid2`:M0(n,O0.cuid2,r.message,t);break;case`startsWith`:M0(n,RegExp(`^${A0(r.value,t)}`),r.message,t);break;case`endsWith`:M0(n,RegExp(`${A0(r.value,t)}$`),r.message,t);break;case`datetime`:j0(n,`date-time`,r.message,t);break;case`date`:j0(n,`date`,r.message,t);break;case`time`:j0(n,`time`,r.message,t);break;case`duration`:j0(n,`duration`,r.message,t);break;case`length`:S0(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),S0(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:M0(n,RegExp(A0(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&j0(n,`ipv4`,r.message,t),r.version!==`v4`&&j0(n,`ipv6`,r.message,t);break;case`base64url`:M0(n,O0.base64url,r.message,t);break;case`jwt`:M0(n,O0.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&M0(n,O0.ipv4Cidr,r.message,t),r.version!==`v4`&&M0(n,O0.ipv6Cidr,r.message,t);break;case`emoji`:M0(n,O0.emoji(),r.message,t);break;case`ulid`:M0(n,O0.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:j0(n,`binary`,r.message,t);break;case`contentEncoding:base64`:S0(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:M0(n,O0.base64,r.message,t);break}break;case`nanoid`:M0(n,O0.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function A0(e,t){return t.patternStrategy===`escape`?Qve(e):e}const Zve=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function Qve(e){let t=``;for(let n=0;n<e.length;n++)Zve.has(e[n])||(t+=`\\`),t+=e[n];return t}function j0(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):S0(e,`format`,t,n,r)}function M0(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:N0(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):S0(e,`pattern`,N0(t,r),n,r)}function N0(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
1225
1225
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1226
1226
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function P0(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Q.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??w0(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===Q.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=k0(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Q.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Q.ZodBranded&&e.keyType._def.type._def.typeName===Q.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=T0(e.keyType._def,t);return{...n,propertyNames:i}}return n}function $ve(e,t){return t.mapStrategy===`record`?P0(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||w0(t),L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||w0(t)],minItems:2,maxItems:2}}}function eye(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 tye(e){return e.target===`openAi`?void 0:{not:w0({...e,currentPath:[...e.currentPath,`not`]})}}function nye(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const F0={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function rye(e,t){if(t.target===`openApi3`)return I0(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in F0&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=F0[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return I0(e,t)}const I0=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L0(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function iye(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:F0[e.innerType._def.typeName],nullable:!0}:{type:[F0[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function aye(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,x0(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?S0(n,`minimum`,r.value,r.message,t):S0(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),S0(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?S0(n,`maximum`,r.value,r.message,t):S0(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),S0(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:S0(n,`multipleOf`,r.value,r.message,t);break}return n}function oye(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=cye(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=L0(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=sye(e,t);return o!==void 0&&(r.additionalProperties=o),r}function sye(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L0(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function cye(e){try{return e.isOptional()}catch{return!0}}const lye=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L0(e.innerType._def,t);let n=L0(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:w0(t)},n]}:w0(t)},uye=(e,t)=>{if(t.pipeStrategy===`input`)return L0(e.in._def,t);if(t.pipeStrategy===`output`)return L0(e.out._def,t);let n=L0(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L0(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function dye(e,t){return L0(e.type._def,t)}function fye(e,t){let n={type:`array`,uniqueItems:!0,items:L0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&S0(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&S0(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function pye(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L0(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L0(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function mye(e){return{not:w0(e)}}function hye(e){return w0(e)}const gye=(e,t)=>L0(e.innerType._def,t),_ye=(e,t,n)=>{switch(t){case Q.ZodString:return k0(e,n);case Q.ZodNumber:return aye(e,n);case Q.ZodObject:return oye(e,n);case Q.ZodBigInt:return Vve(e,n);case Q.ZodBoolean:return Hve();case Q.ZodDate:return E0(e,n);case Q.ZodUndefined:return mye(n);case Q.ZodNull:return nye(n);case Q.ZodArray:return Bve(e,n);case Q.ZodUnion:case Q.ZodDiscriminatedUnion:return rye(e,n);case Q.ZodIntersection:return Yve(e,n);case Q.ZodTuple:return pye(e,n);case Q.ZodRecord:return P0(e,n);case Q.ZodLiteral:return Xve(e,n);case Q.ZodEnum:return qve(e);case Q.ZodNativeEnum:return eye(e);case Q.ZodNullable:return iye(e,n);case Q.ZodOptional:return lye(e,n);case Q.ZodMap:return $ve(e,n);case Q.ZodSet:return fye(e,n);case Q.ZodLazy:return()=>e.getter()._def;case Q.ZodPromise:return dye(e,n);case Q.ZodNaN:case Q.ZodNever:return tye(n);case Q.ZodEffects:return Kve(e,n);case Q.ZodAny:return w0(n);case Q.ZodUnknown:return hye(n);case Q.ZodDefault:return Gve(e,n);case Q.ZodBranded:return T0(e,n);case Q.ZodReadonly:return gye(e,n);case Q.ZodCatch:return Uve(e,n);case Q.ZodPipeline:return uye(e,n);case Q.ZodFunction:case Q.ZodVoid:case Q.ZodSymbol:return;default:return(e=>void 0)(t)}};function L0(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==Lve)return i}if(r&&!n){let e=vye(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=_ye(e,e.typeName,t),o=typeof a==`function`?L0(a(),t):a;if(o&&yye(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const vye=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:C0(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),w0(t)):t.$refStrategy===`seen`?w0(t):void 0}},yye=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),bye=(e,t)=>{let n=zve(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L0(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??w0(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L0(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??w0(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function xye(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function R0(e,t){return G$(e)?re(e,{target:xye(t?.target),io:t?.pipeStrategy??`input`}):bye(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function z0(e){let t=Y$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Q$(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function B0(e,t){let n=q$(e,t);if(!n.success)throw n.error;return n.data}var Sye=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(C1,e=>{this._oncancel(e)}),this.setNotificationHandler(j1,e=>{this._onprogress(e)}),this.setRequestHandler(A1,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(L1,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new v0(v1.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(z1,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);){if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r)if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new v0(e.error.code,e.error.message,e.error.data))}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(Error(`${t} handler missing for request ${n}`))}continue}await this._transport?.send(e.message,{relatedRequestId:t.requestId})}}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new v0(v1.InvalidParams,`Task not found: ${r}`);if(!y0(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(y0(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[t1]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(B1,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new v0(v1.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(H1,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new v0(v1.InvalidParams,`Task not found: ${e.params.taskId}`);if(y0(n.status))throw new v0(v1.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new v0(v1.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof v0?e:new v0(v1.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),v0.fromError(v1.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),_1(e)||b1(e)?this._onresponse(e):m1(e)?this._onrequest(e,t):y_e(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=v0.fromError(v1.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[t1]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:v1.MethodNotFound,message:`Method not found`}};i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let o=v_e(e.params)?e.params.task:void 0,s=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,c={signal:a.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(a.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(a.signal.aborted)throw new v0(v1.ConnectionClosed,`Request was cancelled`);let o={...r,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});let c=o.relatedTask?.taskId??i;return c&&s&&await s.updateTaskStatus(c,`input_required`),await this.request(t,n,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:s,taskRequestedTtl:o?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{o&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,c)).then(async t=>{if(a.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(a.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:v1.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),_1(e)?n(e):n(new v0(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(_1(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),_1(e)?r(e):r(v0.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof v0?e:new v0(v1.InternalError,String(e))}}return}let i;try{let r=await this.request(e,F1,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new v0(v1.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},y0(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new v0(v1.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new v0(v1.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)};return}let r=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof v0?e:new v0(v1.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:d}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[t1]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof v0?e:new v0(v1.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=q$(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(v0.fromError(v1.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},R1,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},V1,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},P_e,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[t1]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[t1]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[t1]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=z0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=B0(e,n);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=z0(e);this._notificationHandlers.set(n,n=>{let r=B0(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&m1(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new v0(v1.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e);t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted){r(new v0(v1.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new v0(v1.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new v0(v1.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=I1.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),y0(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new v0(v1.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(y0(a.status))throw new v0(v1.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=I1.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),y0(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function V0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cye(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];V0(a)&&V0(i)?n[r]={...a,...i}:n[r]=i}return n}var wye=t(br(),1),Tye=t(lr(),1);function Eye(){let e=new wye.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Tye.default)(e),e}var Dye=class{constructor(e){this._ajv=e??Eye()}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)}}},Oye=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},p0,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`);break}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},h0,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function kye(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 Aye(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 jye=class extends Sye{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(u0.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new Dye,this.setRequestHandler(D1,e=>this._oninitialize(e)),this.setNotificationHandler(k1,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(d0,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=u0.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new Oye(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Cye(this._capabilities,e)}setRequestHandler(e,t){let n=Y$(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(G$(n)){let e=n;r=e._zod?.def?.value??e.value}else{let e=n;r=e._def?.value??e.value}if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=q$(l0,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new v0(v1.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=q$(F1,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new v0(v1.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=q$(c0,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new v0(v1.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`);break;case`ping`:break}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`);break;case`notifications/cancelled`:break;case`notifications/progress`:break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`);break;case`ping`:case`initialize`:break}}assertTaskCapability(e){Aye(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&kye(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:e1.includes(t)?t:$$,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:`ping`},S1)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-1],n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this.request({method:`sampling/createMessage`,params:e},m0,t):this.request({method:`sampling/createMessage`,params:e},p0,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},h0,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},h0,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new v0(v1.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof v0?e:new v0(v1.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},_0,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const H0=Symbol.for(`mcp.completable`);function U0(e){return!!e&&typeof e==`object`&&H0 in e}function Mye(e){return e[H0]?.complete}var Nye;(function(e){e.Completable=`McpCompletable`})(Nye||={});const Pye=/^[A-Za-z0-9._-]{1,128}$/;function Fye(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`),!Pye.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 Iye(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function W0(e){let t=Fye(e);return Iye(e,t.warnings),t.isValid}var Lye=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},G0=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new jye(e,t)}get experimental(){return this._experimental||={tasks:new Lye(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(s0)),this.server.assertCanSetRequestHandler(X0(l0)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(s0,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=X$(t.inputSchema);return e?R0(e,{strictUnions:!0,pipeStrategy:`input`}):Rye})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=X$(t.outputSchema);e&&(n.outputSchema=R0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(l0,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new v0(v1.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new v0(v1.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new v0(v1.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new v0(v1.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof v0&&e.code===v1.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await J$(X$(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new v0(v1.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await J$(X$(e.outputSchema),t.structuredContent);if(!r.success){let e=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}else{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}else{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new v0(v1.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(X0(g0)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(g0,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Ave(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return jve(e),this.handleResourceCompletion(e,e.params.ref);default:throw new v0(v1.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new v0(v1.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new v0(v1.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Q0;let r=Y$(n.argsSchema)?.[e.params.argument.name];if(!U0(r))return Q0;let i=Mye(r);return i?Z0(await i(e.params.argument.value,e.params.context)):Q0}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return Q0;throw new v0(v1.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Z0(await r(e.params.argument.value,e.params.context)):Q0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(X1)),this.server.assertCanSetRequestHandler(X0(Z1)),this.server.assertCanSetRequestHandler(X0($1)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(X1,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(Z1,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler($1,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new v0(v1.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new v0(v1.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(X0(e0)),this.server.assertCanSetRequestHandler(X0(t0)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(e0,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?zye(t.argsSchema):void 0}))})),this.server.setRequestHandler(t0,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new v0(v1.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new v0(v1.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await J$(X$(n.argsSchema),e.params.arguments);if(!r.success){let t=Z$(`error`in r?r.error:`Unknown error`);throw new v0(v1.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}else{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i){let a={title:t,description:n,argsSchema:r===void 0?void 0:K$(r),callback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=K$(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>U0(e instanceof j?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){W0(e);let l={title:t,description:n,inputSchema:Y0(r),outputSchema:Y0(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&W0(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=K$(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=K$(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(J0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!J0(t[0])&&(i=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=t.shift()}}let a=t[0];return this._createRegisteredTool(e,void 0,n,r,void 0,i,{taskSupport:`forbidden`},void 0,a)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};const Rye={type:`object`,properties:{}};function K0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function q0(e){return`_def`in e||`_zod`in e||K0(e)}function J0(e){return typeof e!=`object`||!e||q0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(K0)}function Y0(e){if(e){if(J0(e))return K$(e);if(!q0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function zye(e){let t=Y$(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:m_e(t),required:!h_e(t)})):[]}function X0(e){let t=Y$(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=Q$(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Z0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Q0={completion:{values:[],hasMore:!1}};var $0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},Bye=e=>e instanceof $0?e:new $0(e.message,{cause:e}),Vye=global.Request,e2=class extends Vye{constructor(e,t){typeof e==`object`&&n2 in e&&(e=e[n2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Hye=e=>{let t=[],n=e.rawHeaders;for(let e=0;e<n.length;e+=2){let{[e]:r,[e+1]:i}=n;r.charCodeAt(0)!==58&&t.push([r,i])}return new Headers(t)},t2=Symbol(`wrapBodyStream`),Uye=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new e2(t,a);return Object.defineProperty(e,`method`,{get(){return`TRACE`}}),e}if(!(e===`GET`||e===`HEAD`))if(`rawBody`in r&&r.rawBody instanceof Buffer)a.body=new ReadableStream({start(e){e.enqueue(r.rawBody),e.close()}});else if(r[t2]){let e;a.body=new ReadableStream({async pull(t){try{e||=Eu.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=Eu.toWeb(r);return new e2(t,a)},n2=Symbol(`getRequestCache`),r2=Symbol(`requestCache`),i2=Symbol(`incomingKey`),a2=Symbol(`urlKey`),Wye=Symbol(`headersKey`),o2=Symbol(`abortControllerKey`),s2={get method(){return this[i2].method||`GET`},get url(){return this[a2]},get headers(){return this[Wye]||=Hye(this[i2])},[Symbol(`getAbortController`)](){return this[n2](),this[o2]},[n2](){return this[o2]||=new AbortController,this[r2]||=Uye(this.method,this[a2],this.headers,this[i2],this[o2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(s2,e,{get(){return this[n2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(s2,e,{value:function(){return this[n2]()[e]()}})}),Object.defineProperty(s2,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Request (lightweight) ${n({method:this.method,url:this.url,headers:this.headers,nativeRequest:this[r2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(s2,e2.prototype);var Gye=(e,t)=>{let n=Object.create(s2);n[i2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof Mu)throw new $0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[a2]=new URL(r).href}catch(e){throw new $0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof Mu?e.authority:e.headers.host)||t;if(!i)throw new $0(`Missing host header`);let a;if(e instanceof Mu){if(a=e.scheme,!(a===`http`||a===`https`))throw new $0(`Unsupported scheme`)}else a=e.socket&&e.socket.encrypted?`https`:`http`;let o=new URL(`${a}://${i}${r}`);if(o.hostname.length!==i.length&&o.hostname!==i.replace(/:\d+$/,``))throw new $0(`Invalid host header`);return n[a2]=o.href,n},c2=Symbol(`responseCache`),l2=Symbol(`getResponseCache`),u2=Symbol(`cache`),d2=global.Response,f2=class e{#e;#t;[l2](){return delete this[u2],this[c2]||=new d2(this.#e,this.#t)}constructor(t,n){let r;if(this.#e=t,n instanceof e){let e=n[c2];if(e){this.#t=e,this[l2]();return}else this.#t=n.#t,r=new Headers(n.#t.headers)}else this.#t=n;(typeof t==`string`||t?.getReader!==void 0||t instanceof Blob||t instanceof Uint8Array)&&(this[u2]=[n?.status||200,t,r||n?.headers])}get headers(){let e=this[u2];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2]||{"content-type":`text/plain; charset=UTF-8`})),e[2]):this[l2]().headers}get status(){return this[u2]?.[0]??this[l2]().status}get ok(){let e=this.status;return e>=200&&e<300}};[`body`,`bodyUsed`,`redirected`,`statusText`,`trailers`,`type`,`url`].forEach(e=>{Object.defineProperty(f2.prototype,e,{get(){return this[l2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(f2.prototype,e,{value:function(){return this[l2]()[e]()}})}),Object.defineProperty(f2.prototype,Symbol.for(`nodejs.util.inspect.custom`),{value:function(e,t,n){return`Response (lightweight) ${n({status:this.status,headers:this.headers,ok:this.ok,nativeResponse:this[c2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(f2,d2),Object.setPrototypeOf(f2.prototype,d2.prototype);async function Kye(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function p2(e,t,n){let r=t=>{e.cancel(t).catch(()=>{})};return t.on(`close`,r),t.on(`error`,r),(n??e.read()).then(o,i),e.closed.finally(()=>{t.off(`close`,r),t.off(`error`,r)});function i(e){e&&t.destroy(e)}function a(){e.read().then(o,i)}function o({done:n,value:r}){try{if(n)t.end();else if(!t.write(r))t.once(`drain`,a);else return e.read().then(o,i)}catch(e){i(e)}}}function qye(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:p2(e.getReader(),t)}var m2=e=>{let t={};e instanceof Headers||(e=new Headers(e??void 0));let n=[];for(let[r,i]of e)r===`set-cookie`?n.push(i):t[r]=i;return n.length>0&&(t[`set-cookie`]=n),t[`content-type`]??=`text/plain; charset=UTF-8`,t},Jye=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Zte);var h2=Symbol(`outgoingEnded`),g2=Symbol(`incomingDraining`),Yye=500,Xye=64*1024*1024,_2=e=>{let t=e;if(e.destroyed||t[g2])return;if(t[g2]=!0,e instanceof Mu){try{e.stream?.close?.(une.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,Yye);a.unref?.();let o=e=>{n+=e.length,n>Xye&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},Zye=()=>new Response(null,{status:400}),v2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),y2=(e,t)=>{let n=e instanceof Error?e:Error(`unknown error`,{cause:e});n.code===`ERR_STREAM_PREMATURE_CLOSE`?console.info(`The user aborted a request.`):(console.error(e),t.headersSent||t.writeHead(500,{"Content-Type":`text/plain`}),t.end(`Error: ${n.message}`),t.destroy(n))},b2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},x2=async(e,t)=>{let[n,r,i]=e[u2],a=!1;if(!i)i={"content-type":`text/plain; charset=UTF-8`};else if(i instanceof Headers)a=i.has(`content-length`),i=m2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=m2(e)}else for(let e in i)if(e.length===14&&e.toLowerCase()===`content-length`){a=!0;break}a||(typeof r==`string`?i[`Content-Length`]=Buffer.byteLength(r):r instanceof Uint8Array?i[`Content-Length`]=r.byteLength:r instanceof Blob&&(i[`Content-Length`]=r.size)),t.writeHead(n,i),typeof r==`string`||r instanceof Uint8Array?t.end(r):r instanceof Blob?t.end(new Uint8Array(await r.arrayBuffer())):(b2(t),await qye(r,t)?.catch(e=>y2(e,t))),t[h2]?.()},Qye=e=>typeof e.then==`function`,$ye=async(e,t,n={})=>{if(Qye(e))if(n.errorHandler)try{e=await e}catch(t){let r=await n.errorHandler(t);if(!r)return;e=r}else e=await e.catch(v2);if(u2 in e)return x2(e,t);let r=m2(e.headers);if(e.body){let n=e.body.getReader(),i=[],a=!1,o;if(r[`transfer-encoding`]!==`chunked`){let e=2;for(let t=0;t<e;t++){o||=n.read();let r=await Kye(o).catch(e=>{console.error(e),a=!0});if(!r){if(t===1){await new Promise(e=>setTimeout(e)),e=3;continue}break}if(o=void 0,r.value&&i.push(r.value),r.done){a=!0;break}}a&&!(`content-length`in r)&&(r[`content-length`]=i.reduce((e,t)=>e+t.length,0))}t.writeHead(e.status,r),i.forEach(e=>{t.write(e)}),a?t.end():(i.length===0&&b2(t),await p2(n,t,o))}else r[Jye]||(t.writeHead(e.status,r),t.end());t[h2]?.()},S2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==e2&&(Object.defineProperty(global,`Request`,{value:e2}),Object.defineProperty(global,`Response`,{value:f2})),async(r,i)=>{let a,o;try{o=Gye(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[t2]=!0,r.on(`end`,()=>{s=!0}),r instanceof Mu&&(i[h2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{_2(r)})})}),i.on(`finish`,()=>{s||_2(r)})),i.on(`close`,()=>{o[o2]&&(r.errored?o[o2].abort(r.errored.toString()):i.writableFinished||o[o2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{_2(r)})})}),a=e(o,{incoming:r,outgoing:i}),u2 in a)return x2(a,i)}catch(e){if(a)return y2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:Bye(e)),!a)return}else a=o?v2(e):Zye()}try{return await $ye(a,i,t)}catch(e){return y2(e,i)}}},ebe=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
1227
1227
  `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null}),{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i={headers:Object.fromEntries(e.headers.entries()),url:new URL(e.url)},a;if(t?.parsedBody!==void 0)a=t.parsedBody;else try{a=await e.json()}catch{return this.onerror?.(Error(`Parse error: Invalid JSON`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}let o;try{o=Array.isArray(a)?a.map(e=>x1.parse(e)):[x1.parse(a)]}catch{return this.onerror?.(Error(`Parse error: Invalid JSON-RPC message`)),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(O1);if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(m1)){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>O1(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)m1(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)m1(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;m1(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,requestInfo:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!e1.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${e1.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${e1.join(`, `)})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((_1(e)||b1(e))&&(n=e.id),n===void 0){if(_1(e)||b1(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(_1(e)||b1(e)){this._requestResponseMap.set(n,e);let t=Array.from(this._requestToStreamMapping.entries()).filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(new Response(JSON.stringify(n[0]),{status:200,headers:e})):i.resolveJson(new Response(JSON.stringify(n),{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}},tbe=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new ebe(e),this._requestListener=S2(async e=>{let t=this._requestContext.get(e);return this._webStandardTransport.handleRequest(e,{authInfo:t?.authInfo,parsedBody:t?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,t){return this._webStandardTransport.send(e,t)}async handleRequest(e,t,n){let r=e.auth;await S2(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};function C2(e){let t=e;if(t.__prettyZodErrorsInstalled===!0)return;let n=t.validateToolInput;if(typeof n!=`function`){console.warn(`[pretty-zod-errors] McpServer.validateToolInput not found — SDK internals may have changed. Falling back to default error formatting.`);return}t.validateToolInput=async function(e,t,r){if(!e.inputSchema||!nbe(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=ae(i.error);throw new v0(v1.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function nbe(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const w2=2e3,T2=2e3,rbe=[/cli\.mjs/,/(^|[\s/])(open-knowledge|ok)\s+(start|mcp|ui)(\s|$)/,/Open ?Knowledge(?:\.app| Helper)/,/(^|[\s/])bun([\s/]).*?(run dev|packages\/app|vite|hocuspocus)/,/(^|[\s/])node([\s/]).*?(packages\/(cli|app)|vite|hocuspocus)/,/(^|\s)--ok-lock-dir-b64=/,/(^|\s)--ok-project-path=/];function E2(e){return rbe.some(t=>t.test(e))}function ibe(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 Ll(e)?e:null}catch{return null}}function abe(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&&Ll(a)?a:null}function obe(e){let t=[];for(let n of e.split(`
@@ -2014,7 +2014,7 @@ $$`,guidance:"Write LaTeX in `$…$` (inline) or `$$…$$` (block) — OK auto-p
2014
2014
  `),{asset:{ok:!0,...p?{src:p}:{},...m?{path:m}:{},...h?{deduped:h}:{}}})}async function zDe(e,t,n,r,i){let a=r.identityRef?.current,o=e.description!==void 0,s=e.files??[];if(!o&&s.length===0)return Y("Error: provide `description` (to author SKILL.md) and/or `files` (to write references/scripts) — a skill write with neither does nothing.",!0);if(e.body!==void 0&&!o)return Y('Error: `body` updates SKILL.md, so it needs a `description` too. To write a reference, use `files: [{ path: "references/...", content }]` instead.',!0);for(let e of s){let t=s4(e.path);if(!t.ok)return Y(`Error: ${t.error}`,!0)}let c=[],l=null;if(o&&(l=await u4(n,{name:e.name,scope:e.scope,description:e.description,body:e.body,summary:t,identity:a,lockDir:i}),l.isError))return l;for(let r of s){let i=await f4(n,{name:e.name,scope:e.scope,path:r.path,content:r.content,summary:t,identity:a}),o=i.structuredContent;if(i.isError)c.push({path:r.path,ok:!1,error:i.content[0]?.text??`write failed`});else{let e=o?.skill?.file??{};c.push({path:r.path,ok:!0,...typeof e.kind==`string`?{kind:e.kind}:{},...typeof e.created==`boolean`?{created:e.created}:{}})}}let u=c.filter(e=>e.ok).length,d=c.some(e=>!e.ok),f=l?.structuredContent??{},p=f.skill??{ok:!0},m={...f,skill:{...p,...s.length>0?{files:c}:{}}},h=[];if(o&&l&&h.push(l.content[0]?.text??``),s.length>0){h.push(`${u}/${s.length} bundle file(s) written.`);for(let e of c)h.push(e.ok?` ${e.path} (${e.kind??`file`})`:` Failed ${e.path}: ${e.error}`)}return PO(h.filter(Boolean).join(`
2015
2015
  `),m,d)}async function BDe(e,t,n,r,i,a,o){let s=[];for(let a of e)s.push(await L8(a,t,n,r,i));let c=s.map(e=>{if(!e.ok)return{docName:e.docName,ok:!1,error:e.error};let t=Z2(e.docName,{lockDir:a}),n=g4(e.raw.warnings),r=_4(e.raw.brokenLinks);return{docName:e.docName,ok:!0,position:e.position,...t?{previewUrl:t.url}:{},...n?{warnings:n}:{},...e.templateHint?{templateHint:e.templateHint}:{},brokenLinks:r}}),l=c.filter(e=>e.ok).length,u=l===c.length,d=e.map((e,t)=>{let n=s[t];if(!n?.ok)return`Failed ${e.path}: ${n?.error??`unknown error`}`;if(I8(n.position,e.content))return`No change to ${e.path} — empty ${n.position}, document unchanged.`;let r=c[t],i=[`Wrote ${e.path} (${n.position}).`];if(r?.ok&&r.warnings&&i.push(...gxe(r.warnings)),r?.ok){let e=lxe(r.brokenLinks);e&&i.push(e)}return n.ok&&n.templateHint&&i.push(`ℹ ${n.templateHint.length} template${n.templateHint.length===1?``:`s`} available here (pass \`template\`).`),i.join(` `)}),f=e.flatMap((e,t)=>{let n=s[t];if(!n?.ok)return[];let r=F8(n.position,e.content);return[...r?[r]:[],...n.extensionNote?[n.extensionNote]:[]].map(t=>`${e.path} — ${t}`)}),p=[`${l}/${c.length} written.`,...d,...f].join(`
2016
2016
  `),m={documents:c},h=s.find(e=>e.ok);return h&&h.raw.systemSubscriberCount===0&&(m.warning=G2(Z2(h.docName,{lockDir:a}),o)),PO(p,m,!u)}async function VDe(e,t,n,r,i,a,o){let s=await L8(e,t,n,r,i);if(!s.ok)return Y(`Error: ${s.error}`,!0);let c=s.raw,l=Z2(s.docName,{lockDir:a}),u=(typeof c.systemSubscriberCount==`number`?c.systemSubscriberCount:void 0)===0,d=Array.isArray(c.hints)?c.hints:void 0,f=c.summary&&typeof c.summary==`object`?c.summary:void 0,p=typeof f?.hint==`string`?f.hint:void 0,m=g4(c.warnings),h=_4(c.brokenLinks),g=[I8(s.position,e.content)??(s.fromTemplate===void 0?`Written successfully (${s.position}).`:`Written successfully (instantiated from template "${s.fromTemplate}").`)],_=F8(s.position,e.content);if(_&&g.push(_),s.extensionNote&&g.push(s.extensionNote),u&&!l&&g.push(K2),p&&g.push(p),d)for(let e of d)e.message&&g.push(e.message);m&&g.push(...C4(m)),g.push(...v4(h)),s.templateHint&&g.push(FDe(s.templateHint));let v=g.join(`
2017
- `),y={brokenLinks:h};return d&&(y.hints=d),f&&(y.summary=f),m&&(y.warnings=m),s.templateHint&&(y.templateHint=s.templateHint),PO(v,AO(l,u?G2(l,o):void 0,y))}function HDe(e,t){let n={path:u().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:u().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:nxe.optional(),template:u().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:$2.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:txe.optional()};e.registerTool(`write`,{description:jDe,inputSchema:{document:N(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:N({path:u().describe(`Folder path. Example: "meetings".`),frontmatter:$2.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:N({path:u().describe(t4),content:u().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time."),frontmatter:N({title:u().min(1).describe(`Required — the label shown when an agent picks this template.`),description:u().optional().describe(`Optional — shown beside the title in the template menu.`),tags:P(u()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:N({name:u().describe(r4),description:u().optional().describe(`${i4} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:u().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`."),files:P(N({path:u().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:u().describe(`Full text of the bundle file.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:a4.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:N({path:u().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:u().optional().describe(`Base64 of the binary. Use for small files.`),source:u().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:P(N({...n,summary:vO})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:vO,cwd:u().optional().describe(_O)},outputSchema:NO({document:N({hints:TO.optional().describe(`Server-provided write hints, when any.`),...kO}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:N({ok:D(),path:u(),frontmatterError:u().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:N({ok:D(),path:u(),created:D().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:N({ok:D(),path:u().optional(),created:D().optional().describe(`true if created, false if an existing skill was overwritten.`),files:TO.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:N({ok:D(),src:u().optional().describe(`The reference src to embed in a doc.`),path:u().optional(),deduped:D().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:TO.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:xO.optional(),previewUrlSource:SO,warning:EO})},async e=>{let n=await BO(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return Y(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=fO(r),s=uO(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=c4(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?Y(`Error: ${n}`,!0):a?BDe(e.documents,r,s,a,t,o,c):Y(FO,!0)}let l=c4(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?Y(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?RDe(e.asset,r,a,t):zDe(e.skill,e.summary,a,t,o):LDe(e.template,e.summary,a,t):IDe(e.folder,e.summary,a,t):a?VDe({...e.document,summary:e.summary},r,s,a,t,o,c):Y(FO,!0)})}function R8(e,t){let n=t.logger,r=Lbe(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(F2()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(F2()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};sEe(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),dDe(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),wEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),PEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),zbe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),HDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Mxe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),cxe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),UEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),SEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),yEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),_Ee(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),ADe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Hbe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),eDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),YEe(r,{resolveCwd:i(`palette`),config:t.config}),qbe(r,{config:t.config,resolveCwd:i(`config`)}),mEe(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:bbe()}:{}}),Ybe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`conflicts`)}),QEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`resolve_conflict`)}),yDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function z8(e){return Array.isArray(e)?e[0]:e}function B8(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function UDe(e,t,n,r){let i=e.config,a=new G0({name:He,version:Vs});C2(a);let o=n??wu(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Pw(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Fi(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return R8(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=hO(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),{server:a,transport:t}}function V8(e){let t=new Map,n=e.sessionTtlMs??1800*1e3,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=z8(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){B8(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){B8(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),B8(o,503,`Too many active MCP sessions`);return}let c=z8(n.headers[Mw]),l=rh(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=z8(n.headers[Nw])===`1`,d=new tbe({sessionIdGenerator:()=>wu(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=UDe(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const H8=1024*1024;function U8(e){if(!e)return null;try{return rh(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function W8(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function WDe(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=W8(t.searchParams.get(`displayName`)),r=W8(t.searchParams.get(`clientName`)),i=W8(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function G8(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??KB({}),l=e.keepaliveGraceMs??1e4,u=new Lte.default({noServer:!0,maxPayload:H8}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>qB(e.socket.remoteAddress,c)&&YB(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{sx(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!XB(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=U8(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=WDe(e.url);if(t)try{let e=qr(t.clientName);a.setPresence(ih(s),{displayName:t.displayName,icon:e,color:xa[e]??Ui(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(ih(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(ih(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{sx(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),$B(e,{}),ZB(e,c))return n.warn({url:e.url,host:e.headers.host},"[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL, or start with `ok start --remote <url>`"),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!XB(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>TE(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!XB(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>H8){o=!0,ox(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:H8},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(ox(),n.warn({event:`collab-message-too-large`,limit:H8},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):sx(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}const GDe={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function K8(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??KB({}),p=G8({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let a=e.url?.split(`?`)[0];if(!nW(e,t,f,`mcp-mount`))return;if(r!==void 0&&a===`/mcp`){let n=e.headers.origin,a=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!qB(e.socket.remoteAddress,f)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!YB(e.headers.host,f)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:HB});return}if(n!==void 0&&!XB(n,f)){K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`));for(let[e,n]of Object.entries(GDe))t.setHeader(e,n);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}r.handle(e,t).catch(e=>{i.error({err:e,sessionId:a},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(a?.startsWith(`/api/`)){n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||K(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${a}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let o=(n,r,a)=>{if(n===void 0){a();return}try{n(e,t,()=>{t.writableEnded||t.headersSent||a()})}catch(e){i.error({err:e},`Unhandled ${r} middleware error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},s=n=>{if(d===!0&&l!==void 0){if(!qB(e.socket.remoteAddress,f)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!YB(e.headers.host,f)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:HB});return}}o(l,`content-asset`,n)},c=e=>o(u,`react-shell`,e),p=()=>{t.writableEnded||t.headersSent||K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${u===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${a??`/`}`})};if(u!==void 0&&a?.startsWith(`/assets/`)){c(()=>s(p));return}if(l!==void 0||u!==void 0){s(()=>c(p));return}K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${a??`/`}`})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(ZB(e,f)&&i.warn({url:e.url,host:e.headers.host},"[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_PUBLIC_URL, or start with `ok start --remote <url>`"),t.destroy())},{requestListener:g}=aW({health:e.health,nativeApi:e.nativeApi,ingressPolicy:f,legacyDispatch:m,log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const q8=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var J8=class extends Error{kind;projectDir;constructor(e,t,n){super(q8,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function KDe(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}let Y8=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const qDe=(e,t)=>{Gh(e,Y8.PermissionDenied),Yh(e,t)},JDe=(e,t)=>{Gh(e,Y8.Authenticated),Yh(e,t)},YDe=e=>{Gh(e,Y8.Token)},X8={code:4205,reason:`Reset Connection`},Z8={code:4401,reason:`Unauthorized`},XDe={code:4403,reason:`Forbidden`},ZDe={code:4408,reason:`Connection Timeout`},QDe=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var $De=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let Q8=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const eOe=Error(`request for lock canceled`);var tOe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},nOe=class{constructor(e,t=eOe){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=$8(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return tOe(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),rOe(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function rOe(e,t){let n=$8(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function $8(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var iOe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},aOe=class{constructor(e){this._semaphore=new nOe(1,e)}acquire(){return iOe(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let e5,t5,n5,r5,i5=!0;typeof process<`u`&&({FORCE_COLOR:e5,NODE_DISABLE_COLORS:t5,NO_COLOR:n5,TERM:r5}=process.env||{},i5=process.stdout&&process.stdout.isTTY);const a5={enabled:!t5&&n5==null&&r5!==`dumb`&&(e5!=null&&e5!==`0`||i5),reset:s5(0,0),bold:s5(1,22),dim:s5(2,22),italic:s5(3,23),underline:s5(4,24),inverse:s5(7,27),hidden:s5(8,28),strikethrough:s5(9,29),black:s5(30,39),red:s5(31,39),green:s5(32,39),yellow:s5(33,39),blue:s5(34,39),magenta:s5(35,39),cyan:s5(36,39),white:s5(37,39),gray:s5(90,39),grey:s5(90,39),bgBlack:s5(40,49),bgRed:s5(41,49),bgGreen:s5(42,49),bgYellow:s5(43,49),bgBlue:s5(44,49),bgMagenta:s5(45,49),bgCyan:s5(46,49),bgWhite:s5(47,49)};function o5(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function oOe(e,t){let n={has:e,keys:t};return n.reset=a5.reset.bind(n),n.bold=a5.bold.bind(n),n.dim=a5.dim.bind(n),n.italic=a5.italic.bind(n),n.underline=a5.underline.bind(n),n.inverse=a5.inverse.bind(n),n.hidden=a5.hidden.bind(n),n.strikethrough=a5.strikethrough.bind(n),n.black=a5.black.bind(n),n.red=a5.red.bind(n),n.green=a5.green.bind(n),n.yellow=a5.yellow.bind(n),n.blue=a5.blue.bind(n),n.magenta=a5.magenta.bind(n),n.cyan=a5.cyan.bind(n),n.white=a5.white.bind(n),n.gray=a5.gray.bind(n),n.grey=a5.grey.bind(n),n.bgBlack=a5.bgBlack.bind(n),n.bgRed=a5.bgRed.bind(n),n.bgGreen=a5.bgGreen.bind(n),n.bgYellow=a5.bgYellow.bind(n),n.bgBlue=a5.bgBlue.bind(n),n.bgMagenta=a5.bgMagenta.bind(n),n.bgCyan=a5.bgCyan.bind(n),n.bgWhite=a5.bgWhite.bind(n),n}function s5(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:a5.enabled?o5(this.keys,t+``):t+``):t===void 0?oOe([e],[n]):a5.enabled?o5([n],t+``):t+``}}const c5=Math.floor,sOe=(e,t)=>e<t?e:t,cOe=(e,t)=>e>t?e:t;Number.isNaN;const lOe=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const uOe=()=>new Set,dOe=Array.from;Array.isArray;const fOe=String.fromCharCode;String.fromCodePoint,fOe(65535);const pOe=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},l5=typeof TextEncoder<`u`?new TextEncoder:null,mOe=l5?e=>l5.encode(e):pOe;let u5=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});u5&&u5.decode(new Uint8Array).length===1&&(u5=null);const d5=e=>Error(e);var hOe=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const f5=()=>new hOe,p5=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},m5=e=>{let t=new Uint8Array(p5(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},h5=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},g5=(e,t)=>{for(;t>127;)h5(e,128|127&t),t=c5(t/128);h5(e,127&t)},_5=new Uint8Array(3e4),gOe=_5.length/3,v5=l5&&l5.encodeInto?(e,t)=>{if(t.length<gOe){let n=l5.encodeInto(t,_5).written||0;g5(e,n);for(let t=0;t<n;t++)h5(e,_5[t])}else y5(e,mOe(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;g5(e,r);for(let t=0;t<r;t++)h5(e,n.codePointAt(t))},_Oe=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=sOe(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(cOe(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},y5=(e,t)=>{g5(e,t.byteLength),_Oe(e,t)},vOe=d5(`Unexpected end of array`),yOe=d5(`Integer out of Range`);var bOe=class{constructor(e){this.arr=e,this.pos=0}};const b5=e=>new bOe(e),xOe=e=>e.pos!==e.arr.length,SOe=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},x5=e=>SOe(e,C5(e)),S5=e=>e.arr[e.pos++],C5=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>lOe)throw yOe}throw vOe},w5=u5?e=>u5.decode(x5(e)):e=>{let t=C5(e);if(t===0)return``;{let n=String.fromCodePoint(S5(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(S5(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var T5=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=b5(e)}get encoder(){return this.encoderInternal||=f5(),this.encoderInternal}readVarUint8Array(){return x5(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=x5(this.decoder);return this.decoder.pos=e,t}readVarUint(){return C5(this.decoder)}readVarString(){return w5(this.decoder)}toUint8Array(){return m5(this.encoder)}writeVarUint(e){g5(this.encoder,e)}writeVarString(e){v5(this.encoder,e)}get length(){return p5(this.encoder)}};const E5=Date.now,D5=()=>new Map,COe=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var wOe=class{constructor(){this._observers=D5()}on(e,t){COe(this._observers,e,uOe).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return dOe((this._observers.get(e)||D5()).values()).forEach(e=>e(...t))}destroy(){this._observers=D5()}};const O5=Symbol(`Equality`),TOe=Object.keys,k5=e=>TOe(e).length,EOe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),A5=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[O5]!=null)return e[O5](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!A5(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(k5(e)!==k5(t))return!1;for(let n in e)if(!EOe(e,n)||!A5(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!A5(e[n],t[n]))return!1;break;default:return!1}return!0},j5=3e4;var DOe=class extends wOe{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=E5();this.getLocalState()!==null&&j5/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&j5<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&M5(this,t,`timeout`)},c5(j5/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:E5()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),A5(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const M5=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:E5()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},OOe=(e,t,n=e.states)=>{let r=t.length,i=f5();g5(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;g5(i,r),g5(i,s),v5(i,JSON.stringify(o))}return m5(i)},N5=(e,t,n)=>{let r=b5(t),i=E5(),a=[],o=[],s=[],c=[],l=C5(r);for(let t=0;t<l;t++){let t=C5(r),n=C5(r),l=JSON.parse(w5(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(A5(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},kOe=(e,t)=>{g5(e,0),y5(e,vv(t))},AOe=(e,t,n)=>{g5(e,1),y5(e,fv(t,n))},jOe=(e,t,n)=>AOe(t,n,x5(e)),P5=(e,t,n,r)=>{try{lv(t,x5(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},MOe=(e,t)=>{g5(e,2),y5(e,t)},NOe=P5;function F5(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function POe(e){if(!F5(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let I5=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var L5=class{constructor(e){this.encoder=f5(),v5(this.encoder,e)}createSyncMessage(){return this.type=I5.Sync,g5(this.encoder,I5.Sync),this}createSyncReplyMessage(){return this.type=I5.SyncReply,g5(this.encoder,I5.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=I5.Awareness,this.category=`Update`;let n=OOe(e,t||Array.from(e.getStates().keys()));return g5(this.encoder,I5.Awareness),y5(this.encoder,n),this}writeQueryAwareness(){return this.type=I5.QueryAwareness,this.category=`Update`,g5(this.encoder,I5.QueryAwareness),this}writeTokenSyncRequest(){return this.type=I5.Auth,this.category=`TokenSync`,g5(this.encoder,I5.Auth),YDe(this.encoder),this}writeAuthenticated(e){return this.type=I5.Auth,this.category=`Authenticated`,g5(this.encoder,I5.Auth),JDe(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=I5.Auth,this.category=`PermissionDenied`,g5(this.encoder,I5.Auth),qDe(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,kOe(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,MOe(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,g5(this.encoder,I5.Stateless),v5(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,g5(this.encoder,I5.BroadcastStateless),v5(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,g5(this.encoder,I5.SyncStatus),g5(this.encoder,+!!e),this}writeCloseMessage(e){return this.type=I5.CLOSE,g5(this.encoder,I5.CLOSE),v5(this.encoder,e),this}toUint8Array(){return m5(this.encoder)}},FOe=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case I5.Sync:case I5.SyncReply:r.writeVarUint(I5.Sync),await this.readSyncMessage(r,e,t,n,i!==I5.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case I5.Awareness:N5(e.awareness,r.readVarUint8Array(),t??null);break;case I5.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case I5.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:w5(r.decoder)});break;case I5.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case I5.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case I5.Auth:if(r.readVarUint()===Y8.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(jOe(e.decoder,e.encoder,t),r&&i)r(new L5(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new L5(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(Eie(jv(t),x5(e.decoder))){let e=new L5(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new L5(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}P5(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new L5(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new L5(o).writeSyncStatus(!1).toUint8Array());break}NOe(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new L5(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new L5(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},IOe=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===Q8.Closing||this.webSocket.readyState===Q8.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new L5(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new L5(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new L5(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new L5(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new T5(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new FOe(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:X8.code,reason:`reason`in e?e.reason:X8.reason})}this.messageQueue.shift()}}},LOe=class extends q_{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new aOe,this.lastChangeTime=0,this.name=e,this.awareness=new DOe(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{lv(this,fv(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&M5(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return N5(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new L5(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new L5(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},ROe=`4.0.0-rc.1`;function R5(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var zOe=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=Su.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ZDe)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Z8,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===Q8.Closing||this.websocket.readyState===Q8.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new T5(e);if(w5(r.decoder),!(C5(r.decoder)===I5.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),C5(r.decoder);let i=w5(r.decoder),a=null;xOe(r.decoder)&&(a=w5(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new L5(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||XDe,r=new L5(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(X8.code,X8.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=w5(new T5(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:R5(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Z8.code,Z8.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new IOe(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:R5(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:R5(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},BOe=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Bte}),await this.instance.unloadDocument(this.document)),null)}};const VOe=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},HOe={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var UOe=class{constructor(e){this.configuration={...HOe,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=VOe(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:+(n<r)}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:ROe,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(X8)})})}handleConnection(e,t,n={}){let r=new zOe(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=F5(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=F5(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:R5(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),POe(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=R5(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new LOe(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof q_?lv(l,fv(e)):e instanceof Uint8Array&&lv(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:F5(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:QDe(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof $De){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new BOe(await this.createDocument(e,new Request(`http://localhost`),Su.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},z5=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),B5=kl(import.meta.url),V5=z5(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),H5=z5(((e,t)=>{let{EMPTY_BUFFER:n}=V5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=B5(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),WOe=z5(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),U5=z5(((e,t)=>{let n=B5(`zlib`),r=H5(),i=WOe(),{kStatusCode:a}=V5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),W5=z5(((e,t)=>{let{isUtf8:n}=B5(`buffer`),{hasBlob:r}=V5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=B5(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),G5=z5(((e,t)=>{let{Writable:n}=B5(`stream`),r=U5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=V5(),{concat:c,toArrayBuffer:l,unmask:u}=H5(),{isValidStatusCode:d,isValidUTF8:f}=W5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),K5=z5(((e,t)=>{let{Duplex:n}=B5(`stream`),{randomFillSync:r}=B5(`crypto`),i=U5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=V5(),{isBlob:c,isValidStatusCode:l}=W5(),{mask:u,toBuffer:d}=H5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),GOe=z5(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=V5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),q5=z5(((e,t)=>{let{tokenChars:n}=W5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),J5=z5(((e,t)=>{let n=B5(`events`),r=B5(`https`),i=B5(`http`),a=B5(`net`),o=B5(`tls`),{randomBytes:s,createHash:c}=B5(`crypto`),{Duplex:l,Readable:u}=B5(`stream`),{URL:d}=B5(`url`),f=U5(),p=G5(),m=K5(),{isBlob:h}=W5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=V5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=GOe(),{format:ee,parse:te}=q5(),{toBuffer:D}=H5(),O=Symbol(`kAborted`),k=[8,13],A=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ne=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var re=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ie(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,le),i.on(`drain`,ue),i.on(`error`,de),i.on(`message`,pe),i.on(`ping`,me),i.on(`pong`,he),a.onerror=_e,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,N),t.on(`data`,ve),t.on(`end`,ye),t.on(`error`,be),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),M(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(re.prototype,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(re,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(re.prototype,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(re,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(re.prototype,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(re,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),Object.defineProperty(re.prototype,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(re.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(re.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),re.prototype.addEventListener=T,re.prototype.removeEventListener=E,t.exports=re;function ie(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:k[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!k.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${k.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ae(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?se:oe),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=ee({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ne.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{j(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[O]||(S=e._req=null,ae(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){j(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ae(e,SyntaxError(`Invalid URL: ${i}`));return}ie(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||j(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==re.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){j(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){j(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){j(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){j(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=te(u)}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){j(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ae(e,t){e._readyState=re.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function oe(e){return e.path=e.socketPath,a.connect(e)}function se(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function j(e,t,n){e._readyState=re.CLOSING;let r=Error(n);Error.captureStackTrace(r,j),t.setHeader?(t[O]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ae,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ce(e,t,n){if(t){let n=h(t)?t.size:D(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${A[e.readyState]})`);process.nextTick(n,t)}}function le(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,ve),process.nextTick(ge,n._socket),e===1005?n.close():n.close(e,t))}function ue(){let e=this[C];e.isPaused||e._socket.resume()}function de(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,ve),process.nextTick(ge,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function fe(){this[C].emitClose()}function pe(e,t){this[C].emit(`message`,e,t)}function me(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function he(e){this[C].emit(`pong`,e)}function ge(e){e.resume()}function _e(e){let t=this[C];t.readyState!==re.CLOSED&&(t.readyState===re.OPEN&&(t._readyState=re.CLOSING,M(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function M(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function N(){let e=this[C];if(this.removeListener(`close`,N),this.removeListener(`data`,ve),this.removeListener(`end`,ye),e._readyState=re.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,fe),e._receiver.on(`finish`,fe))}function ve(e){this[C]._receiver.write(e)||this.pause()}function ye(){let e=this[C];e._readyState=re.CLOSING,e._receiver.end(),this.end()}function be(){let e=this[C];this.removeListener(`error`,be),this.on(`error`,w),e&&(e._readyState=re.CLOSING,this.destroy())}})),KOe=z5(((e,t)=>{J5();let{Duplex:n}=B5(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),qOe=z5(((e,t)=>{let{tokenChars:n}=W5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),JOe=z5(((e,t)=>{let n=B5(`events`),r=B5(`http`),{Duplex:i}=B5(`stream`),{createHash:a}=B5(`crypto`),o=q5(),s=U5(),c=qOe(),l=J5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=V5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
2017
+ `),y={brokenLinks:h};return d&&(y.hints=d),f&&(y.summary=f),m&&(y.warnings=m),s.templateHint&&(y.templateHint=s.templateHint),PO(v,AO(l,u?G2(l,o):void 0,y))}function HDe(e,t){let n={path:u().describe('Document path. The slashes are the folder it lands in; missing parent folders are created. Example: "meetings/2026-06-03-standup". An optional `.md`/`.mdx` suffix selects the file format (default `.md`); prefer the `extension` field for that. The docName itself is always extension-less.'),content:u().optional().describe("The full Markdown body. Mutually exclusive with `template`."),extension:nxe.optional(),template:u().min(1).optional().describe("Instantiate the new doc from a folder template (resolved against the parent folder's templates_available, leaf→root walk-up; closest-wins). Mutually exclusive with `content`. Inspect the menu with an `exec` listing of the folder."),frontmatter:$2.optional().describe("The doc's OWN frontmatter (YAML). Written inline on create; for an existing doc prefer `edit`."),position:txe.optional()};e.registerTool(`write`,{description:jDe,inputSchema:{document:N(n).optional().describe(`Create or overwrite a DOCUMENT. Example: { document: { path: "meetings/standup", content: "# Standup\\n..." } }`),folder:N({path:u().describe(`Folder path. Example: "meetings".`),frontmatter:$2.optional().describe("The folder's OWN frontmatter (open-shape; `title`/`description`/`tags` are the conventional keys). Describes the folder only — does NOT flow into docs inside it.")}).optional().describe('Create a NEW folder (errors with 409 if it exists — use `edit` to change an existing folder). Example: { folder: { path: "ideas" } }'),template:N({path:u().describe(t4),content:u().describe("Starter content — the Markdown a new document becomes. A leading `---…---` frontmatter block here sets the STARTING PROPERTIES every doc created from this template gets (e.g. `type`, `status`, `tags`); the markdown below it is the body. The template's own picker identity (title/description) is the separate `frontmatter` field, NOT this block — it is stripped at instantiation and never copied onto created docs. (On disk this composes to one frontmatter block with the identity under a reserved `template:` key; you don't author that — just give the starter content here.) Only the `{{date}}` and `{{user}}` substitution tokens are allowed; any other `{{...}}` token hard-errors at write time."),frontmatter:N({title:u().min(1).describe(`Required — the label shown when an agent picks this template.`),description:u().optional().describe(`Optional — shown beside the title in the template menu.`),tags:P(u()).optional().describe(`Optional — tags for the template.`)}).describe("Template metadata. Only `title` (required), `description`, and `tags` are persisted (unlike open-shape doc/folder frontmatter).")}).optional().describe(`Create a TEMPLATE (a reusable starting shape for new docs in a folder). Example: { template: { path: "fishing-log/trip-log", content: "# {{date}}\\n", frontmatter: { title: "Trip Log" } } }`),skill:N({name:u().describe(r4),description:u().optional().describe(`${i4} Optional when writing ONLY \`files\` into an existing skill (omit to leave SKILL.md untouched).`),body:u().optional().describe("SKILL.md body (markdown guidance). Authored WITHOUT frontmatter — `name` + `description` are passed separately and composed server-side. Keep under ~500 lines; move depth into one-level-deep `references/`."),files:P(N({path:u().describe(`Skill-relative path, e.g. "references/tiers.md" or "assets/logo.svg". Must stay inside the skill dir.`),content:u().describe(`Full text of the bundle file.`)})).optional().describe('Bundle files to write beside `SKILL.md`, as an ARRAY of `{ path, content }` (consistent with `documents`/`asset`). `path` is SKILL-RELATIVE and must stay inside the skill dir (e.g. "references/tiers.md", "scripts/run.sh", "assets/logo.svg") — no `../`, no absolute paths. `content` is the full text. Text only (no binary). Independent of `body`: write one reference without resending SKILL.md.'),scope:a4.optional()}).optional().describe('Create or overwrite an agent SKILL bundle (a NEW skill lands at the project\'s default skill home, e.g. `.agents/skills/<name>/`). SKILL.md is authored via `description`+`body`; bundle files via the `files` array — any skill-relative path that stays inside the skill dir (`references/**` and `scripts/**` are the conventional homes; `assets/` and per-harness dirs are accepted because published skills ship them). Example: { skill: { name: "trip-log", description: "Use when logging a fishing trip.", body: "# Steps\\n...", files: [{ path: "references/gear.md", content: "..." }] } }'),asset:N({path:u().describe(`Asset path incl. extension — the slashes are the folder. Example: "images/diagram.png".`),content:u().optional().describe(`Base64 of the binary. Use for small files.`),source:u().optional().describe(`Local filesystem path the server reads. Use for large files.`)}).optional().describe("Upload a binary asset (image/file) via the media route. Exactly one of `content` | `source`."),documents:P(N({...n,summary:vO})).min(1).optional().describe("Batch: documents to write in one call. Mutually exclusive with the single targets. Each entry may carry its own `summary`."),summary:vO,cwd:u().optional().describe(_O)},outputSchema:NO({document:N({hints:TO.optional().describe(`Server-provided write hints, when any.`),...kO}).optional().describe("Single-document write result. Always present on a successful single-doc write — it carries `brokenLinks` (possibly `[]`) plus any `summary`/`hints`/`warnings`."),folder:N({ok:D(),path:u(),frontmatterError:u().optional().describe("Present when the folder was created but its frontmatter write failed — retry only the properties via `edit({ folder: { frontmatter } })`.")}).optional().describe(`Folder-create result.`),template:N({ok:D(),path:u(),created:D().describe(`true if created, false if an existing template updated.`)}).optional().describe(`Template-create result.`),skill:N({ok:D(),path:u().optional(),created:D().optional().describe(`true if created, false if an existing skill was overwritten.`),files:TO.optional().describe("Per-bundle-file results `{ path, kind, created, ok, error? }`.")}).optional().describe(`Skill-create result (SKILL.md and/or bundle files).`),asset:N({ok:D(),src:u().optional().describe(`The reference src to embed in a doc.`),path:u().optional(),deduped:D().optional().describe(`true when identical bytes already existed (no new file written).`)}).optional().describe(`Asset-upload result.`),documents:TO.optional().describe("Batch write: per-doc result `{ docName, ok, position?, previewUrl?, warnings?, brokenLinks, error? }`. `brokenLinks` (possibly `[]`) is present on each successful entry, same as a single-doc write."),previewUrl:xO.optional(),previewUrlSource:SO,warning:EO})},async e=>{let n=await BO(t.resolveCwd,t.config,t.serverUrl,e.cwd);if(!n.ok)return Y(`Error: ${n.error}`,!0);let{cwd:r,config:i,url:a}=n,o=fO(r),s=uO(i,r),c=i.appearance.preview.autoOpen;if(e.documents!==void 0){let n=c4(e,[`document`,`folder`,`template`,`skill`,`asset`,`documents`]);return n?Y(`Error: ${n}`,!0):a?BDe(e.documents,r,s,a,t,o,c):Y(FO,!0)}let l=c4(e,[`document`,`folder`,`template`,`skill`,`asset`]);return l?Y(`Error: ${l}`,!0):e.document===void 0?e.folder===void 0?e.template===void 0?e.skill===void 0?RDe(e.asset,r,a,t):zDe(e.skill,e.summary,a,t,o):LDe(e.template,e.summary,a,t):IDe(e.folder,e.summary,a,t):a?VDe({...e.document,summary:e.summary},r,s,a,t,o,c):Y(FO,!0)})}function R8(e,t){let n=t.logger,r=Lbe(e,{logger:t.logger,identityRef:t.identityRef}),i=e=>async r=>{try{let i=await t.resolveCwd(r);return(F2()??n)?.debug(`tool cwd resolved`,{tool:e,cwd:i,...r?{explicit:r}:{}}),i}catch(t){throw(F2()??n)?.warn(`tool call failed`,{tool:e,err:t,...r?{explicit:r}:{}}),t}};sEe(r,{resolveCwd:i(`exec`),serverUrl:t.serverUrl,config:t.config}),dDe(r,{resolveCwd:i(`search`),config:t.config,serverUrl:t.serverUrl,localApi:t.localApi}),wEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`links`),localApi:t.localApi}),PEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`lint`),identityRef:t.identityRef}),zbe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`audit`)}),HDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`write`),identityRef:t.identityRef,localApi:t.localApi}),Mxe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`edit`),identityRef:t.identityRef}),cxe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`delete`),identityRef:t.identityRef,localApi:t.localApi}),UEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`move`),identityRef:t.identityRef}),SEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`install`),identityRef:t.identityRef,localApi:t.localApi}),yEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`import`),identityRef:t.identityRef,localApi:t.localApi}),_Ee(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`history`)}),ADe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`skills`)}),Hbe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`checkpoint`),identityRef:t.identityRef,localApi:t.localApi}),eDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`restore_version`),identityRef:t.identityRef}),YEe(r,{resolveCwd:i(`palette`),config:t.config}),qbe(r,{config:t.config,resolveCwd:i(`config`)}),mEe(r,{config:t.config,resolveCwd:i(`preview_url`),serverUrl:t.serverUrl,isHostedAgent:t.isHostedAgent,...t.serverUrl?{ensureSingleFileSession:bbe()}:{}}),Ybe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`conflicts`)}),QEe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`resolve_conflict`)}),yDe(r,{serverUrl:t.serverUrl,config:t.config,resolveCwd:i(`share_link`)})}function z8(e){return Array.isArray(e)?e[0]:e}function B8(e,t,n){e.writableEnded||(e.statusCode=t,e.setHeader(`Content-Type`,`text/plain; charset=utf-8`),e.end(n))}function UDe(e,t,n,r){let i=e.config,a=new G0({name:He,version:Vs});C2(a);let o=n??wu(),s={current:{connectionId:o,displayName:o,colorSeed:o}};a.server.oninitialized=()=>{let e=a.server.getClientVersion(),t=Pw(e?.name,o);s.current={connectionId:o,clientInfo:e?{name:t,version:e.version}:void 0,displayName:Fi(t),colorSeed:t}};let c=e.projectDir??e.contentDir;return R8(a,{serverUrl:async()=>e.getServerUrl(),localApi:e.localApi,resolveCwd:async e=>{if(e===void 0)return c;let t=hO(c,e);if(!t.ok)throw Error(`cwd "${e}" is not within the configured project root: ${t.reason}`);return t.abs},config:i,identityRef:s,isHostedAgent:r}),{server:a,transport:t}}function V8(e){let t=new Map,n=e.sessionTtlMs??1800*1e3,r=e.maxSessions??100;async function i(n,r){let i=t.get(n);if(!i)return;t.delete(n),i.ttlTimer!==void 0&&clearTimeout(i.ttlTimer);let a=await Promise.allSettled([i.server.close(),i.transport.close()]);for(let t of a)t.status===`rejected`&&e.log?.warn?.({err:t.reason,sessionId:n,reason:r},`MCP HTTP session close failed`);e.log?.info?.({sessionId:n,reason:r},`MCP HTTP session closed`)}function a(t,r){r.ttlTimer!==void 0&&clearTimeout(r.ttlTimer),r.ttlTimer=setTimeout(()=>{i(t,`ttl-expired`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP session TTL cleanup failed`)})},n),r.ttlTimer.unref?.()}return{async handle(n,o){let s=z8(n.headers[`mcp-session-id`]);if(s){let e=t.get(s);if(!e){B8(o,404,`MCP session not found`);return}a(s,e),await e.transport.handleRequest(n,o);return}if(n.method!==`POST`){B8(o,400,`Missing MCP session. Initialize with POST /mcp first.`);return}if(t.size>=r){e.log?.warn?.({activeSessions:t.size,maxSessions:r},`MCP HTTP session cap reached`),B8(o,503,`Too many active MCP sessions`);return}let c=z8(n.headers[Mw]),l=rh(c)??void 0;c!==void 0&&l===void 0&&e.log?.warn?.({headerLength:c.length},`MCP HTTP forwarded connectionId header failed validation; falling back to randomUUID`);let u=z8(n.headers[Nw])===`1`,d=new tbe({sessionIdGenerator:()=>wu(),enableJsonResponse:!0,onsessioninitialized:async n=>{try{let r=UDe(e,d,l,u);await r.server.connect(d),t.set(n,r),a(n,r),e.log?.info?.({sessionId:n},`MCP HTTP session initialized`)}catch(r){throw t.delete(n),e.log?.error?.({err:r,sessionId:n},`MCP HTTP session initialization failed`),r}}});d.onerror=t=>{e.log?.warn?.({err:t},`MCP HTTP transport error`)},d.onclose=()=>{let t=d.sessionId;if(!t){e.log?.info?.({sessionId:t,reason:`transport-closed`},`MCP HTTP session closed`);return}i(t,`transport-closed`).catch(n=>{e.log?.warn?.({err:n,sessionId:t},`MCP HTTP transport-close cleanup failed`)})},await d.handleRequest(n,o)},async close(){let e=[...t.entries()];await Promise.allSettled(e.map(([e])=>i(e,`handler-close`)))}}}const H8=1024*1024;function U8(e){if(!e)return null;try{return rh(new URL(e,`http://localhost`).searchParams.get(`connectionId`))}catch{return null}}function W8(e){return e===null||e.length===0||e.length>256||/[\u0000-\u001f\u007f]/.test(e)?null:e}function WDe(e){if(!e)return null;try{let t=new URL(e,`http://localhost`),n=W8(t.searchParams.get(`displayName`)),r=W8(t.searchParams.get(`clientName`)),i=W8(t.searchParams.get(`colorSeed`));return n===null||r===null||i===null?null:{displayName:n,clientName:r,colorSeed:i}}catch{return null}}function G8(e){let{hocuspocus:t,log:n,sessionManager:r,agentFocusBroadcaster:i,agentPresenceBroadcaster:a,maintenanceCoordinator:o,acpThreadManager:s}=e,c=e.ingressPolicy??KB({}),l=e.keepaliveGraceMs??1e4,u=new Lte.default({noServer:!0,maxPayload:H8}),d=new Map,f=new Set,p=new Set,m=!1,h;u.on(`error`,e=>n.error({err:e},`WebSocketServer error`));let g=e=>qB(e.socket.remoteAddress,c)&&YB(Array.isArray(e.headers.host)?e.headers.host[0]:e.headers.host,c),_=(e,t)=>{e.on(`error`,e=>{sx(e)||n.error({err:e},`${t} socket error`)}),p.add(e),e.once(`close`,()=>p.delete(e))},v=(e,t,r,i,a)=>{try{u.handleUpgrade(e,t,r,a)}catch(r){n.error({err:r,url:e.url},`[collab] ${i} handleUpgrade threw`);try{t.destroy()}catch{}}},y=(e,t,s)=>{if(!g(e)||e.headers.origin!==void 0&&!XB(e.headers.origin,c)){n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/keepalive upgrade refused`),t.destroy();return}_(t,`MCP keepalive`),v(e,t,s,`keepalive`,t=>{let s=U8(e.url);if(s){let e=d.get(s);e!==void 0&&(clearTimeout(e),d.delete(s),n.info({connectionId:s},`[keepalive] reconnect during grace — timer cancelled`))}if(s&&a){let t=WDe(e.url);if(t)try{let e=qr(t.clientName);a.setPresence(ih(s),{displayName:t.displayName,icon:e,color:xa[e]??Ui(t.colorSeed),currentDoc:`(connected)`,mode:`idle`,ts:Date.now()})}catch(e){n.error({err:e,connectionId:s},`[keepalive] presence bootstrap failed`)}}let c=setInterval(()=>{try{t.ping()}catch{}},3e4);c.unref?.();let u=s?setInterval(()=>a?.bumpPresenceTs(ih(s)),3e3):null;u?.unref?.(),t.on(`close`,()=>{if(clearInterval(c),u!==null&&clearInterval(u),!s||m)return;let e=setTimeout(()=>{if(d.delete(s),m)return;let e=(async()=>{n.info({connectionId:s},`[keepalive] grace expired — cleaning up sessions`);try{await r?.closeAllForAgent(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] closeAllForAgent failed`)}try{i?.clearFocus(s)}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearFocus failed`)}try{a?.clearPresence(ih(s))}catch(e){n.error({err:e,connectionId:s},`[keepalive] clearPresence failed`)}try{await o?.onSessionClose()}catch(e){n.error({err:e,connectionId:s},`[keepalive] maintenance onSessionClose failed`)}})();f.add(e),e.finally(()=>f.delete(e))},l);e.unref?.(),d.set(s,e),n.info({connectionId:s,graceMs:l},`[keepalive] disconnected — grace timer started`)}),t.on(`error`,e=>{sx(e)||n.error({err:e},`MCP keepalive WS error`),t.terminate()})})};return{wss:u,handleUpgrade:(e,r,i)=>{if(!e.url?.startsWith(`/collab`))return!1;if(n.info({url:e.url,protocol:e.headers[`sec-websocket-protocol`]??`none`,host:e.headers.host??`none`,origin:e.headers.origin??`none`},`[collab] upgrade received`),$B(e,{}),ZB(e,c))return n.warn({url:e.url,host:e.headers.host},"[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL, or start with `ok start --remote <url>`"),r.destroy(),!0;if(e.url.startsWith(`/collab/thread`))return s==null||!g(e)||e.headers.origin!==void 0&&!XB(e.headers.origin,c)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab/thread upgrade refused`),r.destroy(),!0):(_(r,`ACP thread`),v(e,r,i,`thread`,e=>TE(e,s,n)),!0);if(e.url.startsWith(`/collab/keepalive`))return y(e,r,i),!0;let a=e.headers.origin!==void 0&&!XB(e.headers.origin,c),o=c.allowExternal;return a||o&&!g(e)?(n.debug({url:e.url,host:e.headers.host,origin:e.headers.origin},`[collab] /collab upgrade refused`),r.destroy(),!0):(_(r,`Upgrade`),n.info({url:e.url},`[collab] handleUpgrade starting`),v(e,r,i,`collaboration`,r=>{let i=t.getConnectionsCount?.()??-1,a=t.handleConnection(r,e);n.info({url:e.url,connectionsBefore:i},`[collab] handshake complete`);let o=!1;r.on(`message`,e=>{if(!o){if(e.byteLength>H8){o=!0,ox(),n.warn({event:`collab-message-too-large`,bytes:e.byteLength,limit:H8},`Collab WebSocket message rejected before Yjs processing`),r.close(1009,`Message Too Big`);return}a.handleMessage(new Uint8Array(e))}}),r.on(`close`,(e,t)=>a.handleClose({code:e,reason:t.toString()})),r.on(`error`,e=>{e.code===`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`?(ox(),n.warn({event:`collab-message-too-large`,limit:H8},`Collab WebSocket frame rejected by ws maxPayload before Yjs processing`)):sx(e)||n.error({err:e},`WebSocket error`),r.terminate()})}),!0)},shutdown:()=>(h??=(async()=>{m=!0;for(let e of p)try{e.destroy()}catch{}p.clear();for(let e of d.values())clearTimeout(e);d.clear(),await Promise.allSettled(f)})(),h)}}const GDe={"Access-Control-Allow-Methods":`GET, POST, DELETE, OPTIONS`,"Access-Control-Allow-Headers":`Content-Type, Authorization, traceparent, tracestate, baggage, mcp-session-id, mcp-protocol-version`,"Access-Control-Max-Age":`86400`};function K8(e){let{httpServer:t,hocuspocus:n,mcpHttpHandler:r,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,contentAssetMiddleware:l,reactShellMiddleware:u,ephemeral:d}=e,f=e.ingressPolicy??KB({}),p=G8({hocuspocus:n,log:i,sessionManager:a,agentFocusBroadcaster:o,agentPresenceBroadcaster:s,maintenanceCoordinator:c,keepaliveGraceMs:e.keepaliveGraceMs,acpThreadManager:e.acpThreadManager,ingressPolicy:f}),m=(e,t)=>{let a=e.url?.split(`?`)[0];if(!nW(e,t,f,`mcp-mount`))return;if(r!==void 0&&a===`/mcp`){let n=e.headers.origin,a=Array.isArray(e.headers[`mcp-session-id`])?e.headers[`mcp-session-id`][0]:e.headers[`mcp-session-id`];if(!qB(e.socket.remoteAddress,f)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`mcp`});return}if(!YB(e.headers.host,f)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`mcp`,detail:HB});return}if(n!==void 0&&!XB(n,f)){K(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`mcp`});return}n!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,n),t.setHeader(`Vary`,`Origin`));for(let[e,n]of Object.entries(GDe))t.setHeader(e,n);if(e.method===`OPTIONS`){t.writeHead(204),t.end();return}r.handle(e,t).catch(e=>{i.error({err:e,sessionId:a},`Unhandled MCP HTTP error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp`,cause:e}):t.writableEnded||t.end()});return}if(a?.startsWith(`/api/`)){n.hooks(`onRequest`,{request:e,response:t}).then(()=>{t.writableEnded||t.headersSent||K(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`mcp-mount`,detail:`No handler for ${e.method??`GET`} ${a}`})}).catch(e=>{i.error({err:e},`Unhandled onRequest error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()});return}let o=(n,r,a)=>{if(n===void 0){a();return}try{n(e,t,()=>{t.writableEnded||t.headersSent||a()})}catch(e){i.error({err:e},`Unhandled ${r} middleware error`),!t.writableEnded&&!t.headersSent?K(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`mcp-mount`,cause:e}):t.writableEnded||t.end()}},s=n=>{if(d===!0&&l!==void 0){if(!qB(e.socket.remoteAddress,f)){K(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`content-asset-gate`});return}if(!YB(e.headers.host,f)){K(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`content-asset-gate`,detail:HB});return}}o(l,`content-asset`,n)},c=e=>o(u,`react-shell`,e),p=()=>{t.writableEnded||t.headersSent||K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`${u===void 0?"This server is running without the web UI. Restart it with plain `ok start` to serve the editor. ":``}No handler for ${a??`/`}`})};if(u!==void 0&&a?.startsWith(`/assets/`)){c(()=>s(p));return}if(l!==void 0||u!==void 0){s(()=>c(p));return}K(t,404,`urn:ok:error:not-found`,`Not found.`,{handler:`mcp-mount`,detail:`This server is running without the web UI. Restart it with plain \`ok start\` to serve the editor. No handler for ${a??`/`}`})},h=(e,t,n)=>{p.handleUpgrade(e,t,n)||(ZB(e,f)&&i.warn({url:e.url,host:e.headers.host},"[remote] refused proxied WS upgrade; consent with OK_ALLOW_EXTERNAL=1 + OK_EXTERNAL_URL, or start with `ok start --remote <url>`"),t.destroy())},{requestListener:g}=aW({health:e.health,nativeApi:e.nativeApi,ingressPolicy:f,legacyDispatch:m,log:i});t.on(`request`,g),t.on(`upgrade`,h);let _;return{wss:p.wss,shutdown:()=>(_??=(async()=>{t.off(`upgrade`,h),await p.shutdown()})(),_)}}const q8=`OpenKnowledge config not found at .ok/config.yml. Run ok init to scaffold OK in this directory.`;var J8=class extends Error{kind;projectDir;constructor(e,t,n){super(q8,n),this.name=`MissingOkConfigError`,this.kind=e,this.projectDir=t}};function KDe(e,t){return{crdt:{hocuspocus:e.hocuspocus,durabilityState:e.durabilityState,cc1Broadcaster:e.cc1Broadcaster,serverInstanceId:e.serverInstanceId},content:{contentDir:t.contentDir,projectDir:t.projectDir,contentFilter:e.contentFilter},indexes:{basenameIndex:e.basenameIndex,resolveEmbed:e.resolveEmbed},git:{get syncEngine(){return e.syncEngine}},agents:{sessionManager:e.sessionManager,agentFocusBroadcaster:e.agentFocusBroadcaster,agentPresenceBroadcaster:e.agentPresenceBroadcaster,acpRegistry:e.acpRegistry,acpPermissions:e.acpPermissions},background:{maintenanceCoordinator:e.maintenanceCoordinator},config:{getLinkPreviewsEnabled:e.getLinkPreviewsEnabled},ready:e.ready,get degraded(){return e.degraded},destroy:e.destroy}}let Y8=function(e){return e[e.Token=0]=`Token`,e[e.PermissionDenied=1]=`PermissionDenied`,e[e.Authenticated=2]=`Authenticated`,e}({});const qDe=(e,t)=>{Gh(e,Y8.PermissionDenied),Yh(e,t)},JDe=(e,t)=>{Gh(e,Y8.Authenticated),Yh(e,t)},YDe=e=>{Gh(e,Y8.Token)},X8={code:4205,reason:`Reset Connection`},Z8={code:4401,reason:`Unauthorized`},XDe={code:4403,reason:`Forbidden`},ZDe={code:4408,reason:`Connection Timeout`},QDe=e=>Array.from(e.entries()).map(([e,t])=>({clientId:e,...t}));var $De=class extends Error{constructor(e){super(e??`Further hooks skipped`),this.name=`SkipFurtherHooksError`}};let Q8=function(e){return e[e.Connecting=0]=`Connecting`,e[e.Open=1]=`Open`,e[e.Closing=2]=`Closing`,e[e.Closed=3]=`Closed`,e}({});const eOe=Error(`request for lock canceled`);var tOe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},nOe=class{constructor(e,t=eOe){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return new Promise((n,r)=>{let i={resolve:n,reject:r,weight:e,priority:t},a=$8(this._queue,e=>t<=e.priority);a===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(a+1,0,i)})}runExclusive(e){return tOe(this,arguments,void 0,function*(e,t=1,n=0){let[r,i]=yield this.acquire(t,n);try{return yield e(r)}finally{i()}})}waitForUnlock(e=1,t=0){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),rOe(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){let t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){let t=this._weightedWaiters[e-1];t&&(t.forEach(e=>e.resolve()),this._weightedWaiters[e-1]=[])}else{let e=this._queue[0].priority;for(let t=this._value;t>0;t--){let n=this._weightedWaiters[t-1];if(!n)continue;let r=n.findIndex(t=>t.priority<=e);(r===-1?n:n.splice(0,r)).forEach((e=>e.resolve()))}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}};function rOe(e,t){let n=$8(e,e=>t.priority<=e.priority);e.splice(n+1,0,t)}function $8(e,t){for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1}var iOe=function(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})},aOe=class{constructor(e){this._semaphore=new nOe(1,e)}acquire(){return iOe(this,arguments,void 0,function*(e=0){let[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}};let e5,t5,n5,r5,i5=!0;typeof process<`u`&&({FORCE_COLOR:e5,NODE_DISABLE_COLORS:t5,NO_COLOR:n5,TERM:r5}=process.env||{},i5=process.stdout&&process.stdout.isTTY);const a5={enabled:!t5&&n5==null&&r5!==`dumb`&&(e5!=null&&e5!==`0`||i5),reset:s5(0,0),bold:s5(1,22),dim:s5(2,22),italic:s5(3,23),underline:s5(4,24),inverse:s5(7,27),hidden:s5(8,28),strikethrough:s5(9,29),black:s5(30,39),red:s5(31,39),green:s5(32,39),yellow:s5(33,39),blue:s5(34,39),magenta:s5(35,39),cyan:s5(36,39),white:s5(37,39),gray:s5(90,39),grey:s5(90,39),bgBlack:s5(40,49),bgRed:s5(41,49),bgGreen:s5(42,49),bgYellow:s5(43,49),bgBlue:s5(44,49),bgMagenta:s5(45,49),bgCyan:s5(46,49),bgWhite:s5(47,49)};function o5(e,t){let n=0,r,i=``,a=``;for(;n<e.length;n++)r=e[n],i+=r.open,a+=r.close,~t.indexOf(r.close)&&(t=t.replace(r.rgx,r.close+r.open));return i+t+a}function oOe(e,t){let n={has:e,keys:t};return n.reset=a5.reset.bind(n),n.bold=a5.bold.bind(n),n.dim=a5.dim.bind(n),n.italic=a5.italic.bind(n),n.underline=a5.underline.bind(n),n.inverse=a5.inverse.bind(n),n.hidden=a5.hidden.bind(n),n.strikethrough=a5.strikethrough.bind(n),n.black=a5.black.bind(n),n.red=a5.red.bind(n),n.green=a5.green.bind(n),n.yellow=a5.yellow.bind(n),n.blue=a5.blue.bind(n),n.magenta=a5.magenta.bind(n),n.cyan=a5.cyan.bind(n),n.white=a5.white.bind(n),n.gray=a5.gray.bind(n),n.grey=a5.grey.bind(n),n.bgBlack=a5.bgBlack.bind(n),n.bgRed=a5.bgRed.bind(n),n.bgGreen=a5.bgGreen.bind(n),n.bgYellow=a5.bgYellow.bind(n),n.bgBlue=a5.bgBlue.bind(n),n.bgMagenta=a5.bgMagenta.bind(n),n.bgCyan=a5.bgCyan.bind(n),n.bgWhite=a5.bgWhite.bind(n),n}function s5(e,t){let n={open:`\x1b[${e}m`,close:`\x1b[${t}m`,rgx:RegExp(`\\x1b\\[${t}m`,`g`)};return function(t){return this!==void 0&&this.has!==void 0?(~this.has.indexOf(e)||(this.has.push(e),this.keys.push(n)),t===void 0?this:a5.enabled?o5(this.keys,t+``):t+``):t===void 0?oOe([e],[n]):a5.enabled?o5([n],t+``):t+``}}const c5=Math.floor,sOe=(e,t)=>e<t?e:t,cOe=(e,t)=>e>t?e:t;Number.isNaN;const lOe=2**53-1;Number.isInteger,Number.isNaN,Number.parseInt;const uOe=()=>new Set,dOe=Array.from;Array.isArray;const fOe=String.fromCharCode;String.fromCodePoint,fOe(65535);const pOe=e=>{let t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r},l5=typeof TextEncoder<`u`?new TextEncoder:null,mOe=l5?e=>l5.encode(e):pOe;let u5=typeof TextDecoder>`u`?null:new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0});u5&&u5.decode(new Uint8Array).length===1&&(u5=null);const d5=e=>Error(e);var hOe=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const f5=()=>new hOe,p5=e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t},m5=e=>{let t=new Uint8Array(p5(e)),n=0;for(let r=0;r<e.bufs.length;r++){let i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},h5=(e,t)=>{let n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(n*2),e.cpos=0),e.cbuf[e.cpos++]=t},g5=(e,t)=>{for(;t>127;)h5(e,128|127&t),t=c5(t/128);h5(e,127&t)},_5=new Uint8Array(3e4),gOe=_5.length/3,v5=l5&&l5.encodeInto?(e,t)=>{if(t.length<gOe){let n=l5.encodeInto(t,_5).written||0;g5(e,n);for(let t=0;t<n;t++)h5(e,_5[t])}else y5(e,mOe(t))}:(e,t)=>{let n=unescape(encodeURIComponent(t)),r=n.length;g5(e,r);for(let t=0;t<r;t++)h5(e,n.codePointAt(t))},_Oe=(e,t)=>{let n=e.cbuf.length,r=e.cpos,i=sOe(n-r,t.length),a=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,a>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(cOe(n*2,a)),e.cbuf.set(t.subarray(i)),e.cpos=a)},y5=(e,t)=>{g5(e,t.byteLength),_Oe(e,t)},vOe=d5(`Unexpected end of array`),yOe=d5(`Integer out of Range`);var bOe=class{constructor(e){this.arr=e,this.pos=0}};const b5=e=>new bOe(e),xOe=e=>e.pos!==e.arr.length,SOe=(e,t)=>{let n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n},x5=e=>SOe(e,C5(e)),S5=e=>e.arr[e.pos++],C5=e=>{let t=0,n=1,r=e.arr.length;for(;e.pos<r;){let r=e.arr[e.pos++];if(t+=(r&127)*n,n*=128,r<128)return t;if(t>lOe)throw yOe}throw vOe},w5=u5?e=>u5.decode(x5(e)):e=>{let t=C5(e);if(t===0)return``;{let n=String.fromCodePoint(S5(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(S5(e));else for(;t>0;){let r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}};var T5=class{constructor(e){e instanceof Uint8Array||(e=new Uint8Array(e)),this.decoder=b5(e)}get encoder(){return this.encoderInternal||=f5(),this.encoderInternal}readVarUint8Array(){return x5(this.decoder)}peekVarUint8Array(){let{pos:e}=this.decoder,t=x5(this.decoder);return this.decoder.pos=e,t}readVarUint(){return C5(this.decoder)}readVarString(){return w5(this.decoder)}toUint8Array(){return m5(this.encoder)}writeVarUint(e){g5(this.encoder,e)}writeVarString(e){v5(this.encoder,e)}get length(){return p5(this.encoder)}};const E5=Date.now,D5=()=>new Map,COe=(e,t,n)=>{let r=e.get(t);return r===void 0&&e.set(t,r=n()),r};var wOe=class{constructor(){this._observers=D5()}on(e,t){COe(this._observers,e,uOe).add(t)}once(e,t){let n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){let n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return dOe((this._observers.get(e)||D5()).values()).forEach(e=>e(...t))}destroy(){this._observers=D5()}};const O5=Symbol(`Equality`),TOe=Object.keys,k5=e=>TOe(e).length,EOe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),A5=(e,t)=>{if(e===t)return!0;if(e==null||t==null||e.constructor!==t.constructor&&(e.constructor||Object)!==(t.constructor||Object))return!1;if(e[O5]!=null)return e[O5](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(let n of e.keys())if(!t.has(n)||!A5(e.get(n),t.get(n)))return!1;break;case void 0:case Object:if(k5(e)!==k5(t))return!1;for(let n in e)if(!EOe(e,n)||!A5(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!A5(e[n],t[n]))return!1;break;default:return!1}return!0},j5=3e4;var DOe=class extends wOe{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=E5();this.getLocalState()!==null&&j5/2<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&j5<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&M5(this,t,`timeout`)},c5(j5/10)),e.on(`destroy`,()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit(`destroy`,[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,n=this.meta.get(t),r=n===void 0?0:n.clock+1,i=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:E5()});let a=[],o=[],s=[],c=[];e===null?c.push(t):i==null?e!=null&&a.push(t):(o.push(t),A5(i,e)||s.push(t)),(a.length>0||s.length>0||c.length>0)&&this.emit(`change`,[{added:a,updated:s,removed:c},`local`]),this.emit(`update`,[{added:a,updated:o,removed:c},`local`])}setLocalStateField(e,t){let n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}};const M5=(e,t,n)=>{let r=[];for(let n=0;n<t.length;n++){let i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:E5()})}r.push(i)}}r.length>0&&(e.emit(`change`,[{added:[],updated:[],removed:r},n]),e.emit(`update`,[{added:[],updated:[],removed:r},n]))},OOe=(e,t,n=e.states)=>{let r=t.length,i=f5();g5(i,r);for(let a=0;a<r;a++){let r=t[a],o=n.get(r)||null,s=e.meta.get(r).clock;g5(i,r),g5(i,s),v5(i,JSON.stringify(o))}return m5(i)},N5=(e,t,n)=>{let r=b5(t),i=E5(),a=[],o=[],s=[],c=[],l=C5(r);for(let t=0;t<l;t++){let t=C5(r),n=C5(r),l=JSON.parse(w5(r)),u=e.meta.get(t),d=e.states.get(t),f=u===void 0?0:u.clock;(f<n||f===n&&l===null&&e.states.has(t))&&(l===null?t===e.clientID&&e.getLocalState()!=null?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),u===void 0&&l!==null?a.push(t):u!==void 0&&l===null?c.push(t):l!==null&&(A5(l,d)||s.push(t),o.push(t)))}(a.length>0||s.length>0||c.length>0)&&e.emit(`change`,[{added:a,updated:s,removed:c},n]),(a.length>0||o.length>0||c.length>0)&&e.emit(`update`,[{added:a,updated:o,removed:c},n])},kOe=(e,t)=>{g5(e,0),y5(e,vv(t))},AOe=(e,t,n)=>{g5(e,1),y5(e,fv(t,n))},jOe=(e,t,n)=>AOe(t,n,x5(e)),P5=(e,t,n,r)=>{try{lv(t,x5(e),n)}catch(e){r?.(e),console.error(`Caught error while handling a Yjs update`,e)}},MOe=(e,t)=>{g5(e,2),y5(e,t)},NOe=P5;function F5(e){return typeof e==`object`&&!!e&&`source`in e&&(e.source===`connection`||e.source===`redis`||e.source===`local`)}function POe(e){if(!F5(e))return!1;switch(e.source){case`connection`:return!1;case`redis`:return!0;case`local`:return e.skipStoreHooks??!1}}let I5=function(e){return e[e.Unknown=-1]=`Unknown`,e[e.Sync=0]=`Sync`,e[e.Awareness=1]=`Awareness`,e[e.Auth=2]=`Auth`,e[e.QueryAwareness=3]=`QueryAwareness`,e[e.SyncReply=4]=`SyncReply`,e[e.Stateless=5]=`Stateless`,e[e.BroadcastStateless=6]=`BroadcastStateless`,e[e.CLOSE=7]=`CLOSE`,e[e.SyncStatus=8]=`SyncStatus`,e[e.Ping=9]=`Ping`,e[e.Pong=10]=`Pong`,e}({});var L5=class{constructor(e){this.encoder=f5(),v5(this.encoder,e)}createSyncMessage(){return this.type=I5.Sync,g5(this.encoder,I5.Sync),this}createSyncReplyMessage(){return this.type=I5.SyncReply,g5(this.encoder,I5.SyncReply),this}createAwarenessUpdateMessage(e,t){this.type=I5.Awareness,this.category=`Update`;let n=OOe(e,t||Array.from(e.getStates().keys()));return g5(this.encoder,I5.Awareness),y5(this.encoder,n),this}writeQueryAwareness(){return this.type=I5.QueryAwareness,this.category=`Update`,g5(this.encoder,I5.QueryAwareness),this}writeTokenSyncRequest(){return this.type=I5.Auth,this.category=`TokenSync`,g5(this.encoder,I5.Auth),YDe(this.encoder),this}writeAuthenticated(e){return this.type=I5.Auth,this.category=`Authenticated`,g5(this.encoder,I5.Auth),JDe(this.encoder,e?`readonly`:`read-write`),this}writePermissionDenied(e){return this.type=I5.Auth,this.category=`PermissionDenied`,g5(this.encoder,I5.Auth),qDe(this.encoder,e),this}writeFirstSyncStepFor(e){return this.category=`SyncStep1`,kOe(this.encoder,e),this}writeUpdate(e){return this.category=`Update`,MOe(this.encoder,e),this}writeStateless(e){return this.category=`Stateless`,g5(this.encoder,I5.Stateless),v5(this.encoder,e),this}writeBroadcastStateless(e){return this.category=`Stateless`,g5(this.encoder,I5.BroadcastStateless),v5(this.encoder,e),this}writeSyncStatus(e){return this.category=`SyncStatus`,g5(this.encoder,I5.SyncStatus),g5(this.encoder,+!!e),this}writeCloseMessage(e){return this.type=I5.CLOSE,g5(this.encoder,I5.CLOSE),v5(this.encoder,e),this}toUint8Array(){return m5(this.encoder)}},FOe=class{constructor(e,t){this.message=e,this.defaultTransactionOrigin=t}async apply(e,t,n){let{message:r}=this,i=r.readVarUint(),a=r.length;switch(i){case I5.Sync:case I5.SyncReply:r.writeVarUint(I5.Sync),await this.readSyncMessage(r,e,t,n,i!==I5.SyncReply),r.length>a+1&&(n?n(r.toUint8Array()):t&&t.send(r.toUint8Array()));break;case I5.Awareness:N5(e.awareness,r.readVarUint8Array(),t??null);break;case I5.QueryAwareness:this.applyQueryAwarenessMessage(e,t,n);break;case I5.Stateless:t?.callbacks.statelessCallback({connection:t,documentName:e.name,document:e,payload:w5(r.decoder)});break;case I5.BroadcastStateless:{let t=r.readVarString();e.getConnections().forEach(e=>{e.sendStateless(t)});break}case I5.CLOSE:t?.close({code:1e3,reason:`provider_initiated`});break;case I5.Auth:if(r.readVarUint()===Y8.Token){t?.callbacks.onTokenSyncCallback({token:r.readVarString()});break}console.error(`Received an authentication message on a connection that is already fully authenticated. Probably your provider has been destroyed + recreated really fast.`);break;default:console.error(`Unable to handle message of type ${i}: no handler defined! Are your provider/server versions aligned?`)}}async readSyncMessage(e,t,n,r,i=!0){let a=e.readVarUint(),o=n?.messageAddress??t.name;switch(n&&await n.callbacks.beforeSync(n,{type:a,payload:e.peekVarUint8Array()}),a){case 0:if(jOe(e.decoder,e.encoder,t),r&&i)r(new L5(o).createSyncReplyMessage().writeFirstSyncStepFor(t).toUint8Array());else if(n){let e=new L5(o).createSyncMessage().writeFirstSyncStepFor(t);n.send(e.toUint8Array())}break;case 1:if(n?.readOnly){if(Eie(jv(t),x5(e.decoder))){let e=new L5(o).writeSyncStatus(!0);n.send(e.toUint8Array())}else{let e=new L5(o).writeSyncStatus(!1);n.send(e.toUint8Array())}break}P5(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new L5(o).writeSyncStatus(!0).toUint8Array());break;case 2:if(n?.readOnly){n.send(new L5(o).writeSyncStatus(!1).toUint8Array());break}NOe(e.decoder,t,n?{source:`connection`,connection:n}:this.defaultTransactionOrigin??{source:`local`}),n&&n.send(new L5(o).writeSyncStatus(!0).toUint8Array());break;default:throw Error(`Received a message with an unknown type: ${a}`)}return a}applyQueryAwarenessMessage(e,t,n){let r=new L5(t?.messageAddress??e.name).createAwarenessUpdateMessage(e.awareness);n&&n(r.toUint8Array())}},IOe=class{get messageAddress(){return this.sessionId?`${this.document.name}\0${this.sessionId}`:this.document.name}constructor(e,t,n,r,i,a=!1,o,s){this.callbacks={onClose:[(e,t)=>{}],beforeHandleMessage:(e,t)=>Promise.resolve(),beforeSync:(e,t)=>Promise.resolve(),statelessCallback:e=>Promise.resolve(),onTokenSyncCallback:e=>Promise.resolve()},this.messageQueue=[],this.processingPromise=Promise.resolve(),this.webSocket=e,this.context=i,this.document=n,this.request=t,this.socketId=r,this.readOnly=a,this.sessionId=o??null,this.providerVersion=s??null,this.document.addConnection(this),this.sendCurrentAwareness()}onClose(e){return this.callbacks.onClose.push(e),this}onStatelessCallback(e){return this.callbacks.statelessCallback=e,this}beforeHandleMessage(e){return this.callbacks.beforeHandleMessage=e,this}beforeSync(e){return this.callbacks.beforeSync=e,this}onTokenSyncCallback(e){return this.callbacks.onTokenSyncCallback=e,this}waitForPendingMessages(){return this.processingPromise}send(e){if(this.webSocket.readyState===Q8.Closing||this.webSocket.readyState===Q8.Closed){this.close();return}try{this.webSocket.send(e)}catch{this.close()}}sendStateless(e){let t=new L5(this.messageAddress).writeStateless(e);this.send(t.toUint8Array())}requestToken(){let e=new L5(this.messageAddress).writeTokenSyncRequest();this.send(e.toUint8Array())}close(e){if(this.document.hasConnection(this)){this.document.removeConnection(this),this.callbacks.onClose.forEach(t=>t(this.document,e));let t=new L5(this.messageAddress);t.writeCloseMessage(e?.reason??`Server closed the connection`),this.send(t.toUint8Array())}}sendCurrentAwareness(){if(!this.document.hasAwarenessStates())return;let e=new L5(this.messageAddress).createAwarenessUpdateMessage(this.document.awareness);this.send(e.toUint8Array())}handleMessage(e){this.messageQueue.push(e),this.messageQueue.length===1&&(this.processingPromise=this.processMessages())}async processMessages(){for(;this.messageQueue.length>0;){let e=this.messageQueue.at(0),t=new T5(e),n=t.readVarString(),r=n.indexOf(`\0`),i=r===-1?n:n.substring(0,r);if(i!==this.document.name){this.messageQueue.shift();continue}t.writeVarString(this.messageAddress);try{await this.callbacks.beforeHandleMessage(this,e),await new FOe(t).apply(this.document,this)}catch(e){console.error(`closing connection ${this.socketId} (while handling ${i}) because of exception`,e),this.close({code:`code`in e&&typeof e.code==`number`?e.code:X8.code,reason:`reason`in e?e.reason:X8.reason})}this.messageQueue.shift()}}},LOe=class extends q_{constructor(e,t){super(t),this.callbacks={onUpdate:(e,t,n)=>{},beforeBroadcastStateless:(e,t)=>{}},this.connections=new Map,this.directConnectionsCount=0,this.isDestroyed=!1,this.saveMutex=new aOe,this.lastChangeTime=0,this.name=e,this.awareness=new DOe(this),this.awareness.setLocalState(null),this.awareness.on(`update`,this.handleAwarenessUpdate.bind(this)),this.on(`update`,this.handleUpdate.bind(this)),this.isLoading=!0}isEmpty(e){return!this.get(e)._start&&!this.get(e)._map.size}merge(e){return(Array.isArray(e)?e:[e]).forEach(e=>{lv(this,fv(e))}),this}onUpdate(e){return this.callbacks.onUpdate=e,this}beforeBroadcastStateless(e){return this.callbacks.beforeBroadcastStateless=e,this}addConnection(e){return this.connections.set(e,{clients:new Set}),this}hasConnection(e){return this.connections.has(e)}removeConnection(e){let t=this.connections.get(e);return t&&M5(this.awareness,Array.from(t.clients),null),this.connections.delete(e),this}addDirectConnection(){return this.directConnectionsCount+=1,this}removeDirectConnection(){return this.directConnectionsCount>0&&--this.directConnectionsCount,this}getConnectionsCount(){return this.connections.size+this.directConnectionsCount}getConnections(){return Array.from(this.connections.keys())}getClients(e){let t=this.connections.get(e);return t?.clients===void 0?new Set:t.clients}hasAwarenessStates(){return this.awareness.getStates().size>0}applyAwarenessUpdate(e,t){return N5(this.awareness,t,e),this}handleAwarenessUpdate({added:e,updated:t,removed:n},r){let i=e.concat(t,n);if(r!==null){let t=this.connections.get(r);t&&(e.forEach(e=>t.clients.add(e)),n.forEach(e=>t.clients.delete(e)))}for(let e of this.getConnections()){let t=new L5(e.messageAddress).createAwarenessUpdateMessage(this.awareness,i);e.send(t.toUint8Array())}return this}handleUpdate(e,t){this.callbacks.onUpdate(this,t,e);for(let t of this.getConnections()){let n=new L5(t.messageAddress).createSyncMessage().writeUpdate(e);t.send(n.toUint8Array())}return this}broadcastStateless(e,t){this.callbacks.beforeBroadcastStateless(this,e),(t?this.getConnections().filter(t):this.getConnections()).forEach(t=>{t.sendStateless(e)})}destroy(){super.destroy(),this.isDestroyed=!0}},ROe=`4.0.0-rc.1`;function R5(e){let t=e?.url;return t?t.includes(`://`)?new URL(t).searchParams:new URLSearchParams(t.split(`?`)[1]||``):new URLSearchParams}var zOe=class{constructor(e,t,n,r,i,a={}){this.websocket=e,this.request=t,this.documentProvider=n,this.hooks=r,this.opts=i,this.defaultContext=a,this.documentConnections={},this.incomingMessageQueue={},this.documentConnectionsEstablished=new Set,this.hookPayloads={},this.callbacks={onClose:[(e,t)=>{}]},this.socketId=Su.randomUUID(),this.lastMessageReceivedAt=Date.now(),this.check=()=>{Date.now()-this.lastMessageReceivedAt>this.timeout&&this.close(ZDe)},this.setUpNewConnection=async(e,t,n)=>{let r=this.hookPayloads[e],i=await this.documentProvider.createDocument(t,r.request,r.socketId,r.connectionConfig,r.context),a=this.createConnection(this.websocket,i,r,n,r.providerVersion);if(a.onClose((t,n)=>{delete this.hookPayloads[e],delete this.documentConnections[e],delete this.incomingMessageQueue[e],this.documentConnectionsEstablished.delete(e)}),a.onTokenSyncCallback(async e=>{try{return await this.hooks(`onTokenSync`,{...r,...e,document:i,connection:a,documentName:t},e=>{r.context={...r.context,...e}})}catch(e){console.error(e);let t={...Z8,...e};a.close({code:t.code,reason:t.reason})}}),this.documentConnections[e]=a,this.websocket.readyState===Q8.Closing||this.websocket.readyState===Q8.Closed){this.close();return}this.incomingMessageQueue[e]?.forEach(e=>{a.handleMessage(e)}),await this.hooks(`connected`,{...r,documentName:t,context:r.context,connection:a})},this.handleQueueingMessage=async(e,t,n)=>{try{let r=new T5(e);if(w5(r.decoder),!(C5(r.decoder)===I5.Auth&&!this.documentConnectionsEstablished.has(t))){this.incomingMessageQueue[t].push(e);return}this.documentConnectionsEstablished.add(t),C5(r.decoder);let i=w5(r.decoder),a=null;xOe(r.decoder)&&(a=w5(r.decoder));let o=t.indexOf(`\0`),s=o===-1?null:t.substring(o+1),c=t;try{let e=this.hookPayloads[t];e.providerVersion=a,await this.hooks(`onConnect`,{...e,documentName:n},t=>{e.context={...e.context,...t}}),await this.hooks(`onAuthenticate`,{token:i,...e,documentName:n},t=>{e.context={...e.context,...t}}),e.connectionConfig.isAuthenticated=!0;let r=new L5(c).writeAuthenticated(e.connectionConfig.readOnly);this.websocket.send(r.toUint8Array()),await this.setUpNewConnection(t,n,s)}catch(e){let n=e||XDe,r=new L5(c).writePermissionDenied(n.reason??`permission-denied`);this.websocket.send(r.toUint8Array()),this.documentConnectionsEstablished.delete(t),delete this.hookPayloads[t],delete this.incomingMessageQueue[t]}}catch(e){console.error(e),this.websocket.close(X8.code,X8.reason)}},this.handleMessage=e=>{this.lastMessageReceivedAt=Date.now();try{let t=w5(new T5(e).decoder),n=t.indexOf(`\0`),r=n===-1?t:t.substring(0,n),i=this.documentConnections[t]??this.documentConnections[r];if(i){i.handleMessage(e);return}if(this.incomingMessageQueue[t]===void 0){if(this.incomingMessageQueue[t]=[],this.hookPayloads[t])throw Error(`first message, but hookPayloads exists`);this.hookPayloads[t]={instance:this.documentProvider,request:this.request,connectionConfig:{readOnly:!1,isAuthenticated:!1},requestHeaders:this.request.headers,requestParameters:R5(this.request),socketId:this.socketId,context:{...this.defaultContext},providerVersion:null}}this.handleQueueingMessage(e,t,r)}catch(e){console.error(e),this.websocket.close(Z8.code,Z8.reason)}},this.timeout=i.timeout,this.pingInterval=setInterval(this.check,this.timeout)}handleClose(e){this.close(e),clearInterval(this.pingInterval)}close(e){Object.values(this.documentConnections).forEach(t=>t.close(e))}onClose(e){return this.callbacks.onClose.push(e),this}createConnection(e,t,n,r,i){let a=new IOe(e,n.request,t,n.socketId,n.context,n.connectionConfig.readOnly,r,i);return a.onClose(async(e,t)=>{await a.waitForPendingMessages();let r={instance:this.documentProvider,clientsCount:e.getConnectionsCount(),context:n.context,document:e,socketId:n.socketId,documentName:e.name,requestHeaders:n.request.headers,requestParameters:R5(n.request)};await this.hooks(`onDisconnect`,r),this.callbacks.onClose.forEach(t=>t(e,r))}),a.onStatelessCallback(async e=>{try{return await this.hooks(`onStateless`,e)}catch(e){if(e?.message)throw e}}),a.beforeHandleMessage((e,r)=>{let i={instance:this.documentProvider,clientsCount:t.getConnectionsCount(),context:n.context,document:t,socketId:n.socketId,connection:e,documentName:t.name,requestHeaders:n.request.headers,requestParameters:R5(n.request),update:r};return this.hooks(`beforeHandleMessage`,i)}),a.beforeSync((e,r)=>{let i={clientsCount:t.getConnectionsCount(),context:n.context,document:t,documentName:t.name,connection:e,type:r.type,payload:r.payload};return this.hooks(`beforeSync`,i)}),a}},BOe=class{constructor(e,t,n){this.document=null,this.document=e,this.instance=t,this.context=n??{},this.document.addDirectConnection()}async transact(e){if(!this.document)throw Error(`direct connection closed`);this.document.transact(t=>{e(this.document)},{source:`local`,context:this.context})}async disconnect(){this.document&&=(this.document?.removeDirectConnection(),await this.instance.storeDocumentHooks(this.document,{clientsCount:this.document.getConnectionsCount(),lastContext:this.context,lastTransactionOrigin:{source:`local`,context:this.context},document:this.document,documentName:this.document.name,instance:this.instance},!0),this.document.getConnectionsCount()===0&&!this.document.saveMutex.isLocked()&&(await this.instance.hooks(`onDisconnect`,{instance:this.instance,clientsCount:this.document.getConnectionsCount(),context:this.context,document:this.document,socketId:`server`,documentName:this.document.name,requestHeaders:new Headers,requestParameters:new Bte}),await this.instance.unloadDocument(this.document)),null)}};const VOe=()=>{let e=new Map,t=new Map;return{debounce:async(n,r,i,a)=>{let o=e.get(n),s=o?.start||Date.now(),c=async()=>{t.has(n)&&await t.get(n),e.delete(n);let i=r();t.set(n,i);let a=await i;return t.delete(n),a};if(o?.timeout&&clearTimeout(o.timeout),i===0||Date.now()-s>=a)return c();e.set(n,{start:s,timeout:setTimeout(c,i),func:c})},isDebounced:t=>e.has(t),isCurrentlyExecuting:e=>t.has(e),executeNow:t=>{let n=e.get(t);if(n)return clearTimeout(n.timeout),n.func()}}},HOe={name:null,timeout:6e4,debounce:2e3,maxDebounce:1e4,quiet:!1,yDocOptions:{gc:!0,gcFilter:()=>!0},unloadImmediately:!0};var UOe=class{constructor(e){this.configuration={...HOe,extensions:[],onConfigure:()=>new Promise(e=>e(null)),onListen:()=>new Promise(e=>e(null)),onUpgrade:()=>new Promise(e=>e(null)),onConnect:()=>new Promise(e=>e(null)),connected:()=>new Promise(e=>e(null)),beforeHandleMessage:()=>new Promise(e=>e(null)),beforeSync:()=>new Promise(e=>e(null)),beforeBroadcastStateless:()=>new Promise(e=>e(null)),onStateless:()=>new Promise(e=>e(null)),onChange:()=>new Promise(e=>e(null)),onCreateDocument:()=>new Promise(e=>e(null)),onLoadDocument:()=>new Promise(e=>e(null)),onStoreDocument:()=>new Promise(e=>e(null)),afterStoreDocument:()=>new Promise(e=>e(null)),onAwarenessUpdate:()=>new Promise(e=>e(null)),onRequest:()=>new Promise(e=>e(null)),onDisconnect:()=>new Promise(e=>e(null)),onDestroy:()=>new Promise(e=>e(null))},this.loadingDocuments=new Map,this.unloadingDocuments=new Map,this.documents=new Map,this.debouncer=VOe(),e&&this.configure(e)}configure(e){return this.configuration={...this.configuration,...e},this.configuration.extensions.sort((e,t)=>{let n=e.priority===void 0?100:e.priority,r=t.priority===void 0?100:t.priority;return n>r?-1:+(n<r)}),this.configuration.extensions.push({onConfigure:this.configuration.onConfigure,onListen:this.configuration.onListen,onUpgrade:this.configuration.onUpgrade,onConnect:this.configuration.onConnect,connected:this.configuration.connected,onAuthenticate:this.configuration.onAuthenticate,onTokenSync:this.configuration.onTokenSync,onLoadDocument:this.configuration.onLoadDocument,afterLoadDocument:this.configuration.afterLoadDocument,beforeHandleMessage:this.configuration.beforeHandleMessage,beforeBroadcastStateless:this.configuration.beforeBroadcastStateless,beforeSync:this.configuration.beforeSync,onStateless:this.configuration.onStateless,onChange:this.configuration.onChange,onStoreDocument:this.configuration.onStoreDocument,afterStoreDocument:this.configuration.afterStoreDocument,onAwarenessUpdate:this.configuration.onAwarenessUpdate,onRequest:this.configuration.onRequest,beforeUnloadDocument:this.configuration.beforeUnloadDocument,afterUnloadDocument:this.configuration.afterUnloadDocument,onDisconnect:this.configuration.onDisconnect,onDestroy:this.configuration.onDestroy}),this.hooks(`onConfigure`,{configuration:this.configuration,version:ROe,instance:this}),this}getDocumentsCount(){return this.documents.size}getConnectionsCount(){let e=new Set,t=Array.from(this.documents.values()).reduce((t,n)=>(n.getConnections().forEach(({socketId:t})=>{e.add(t)}),t+n.directConnectionsCount),0);return e.size+t}flushPendingStores(){this.documents.forEach(e=>{let t=`onStoreDocument-${e.name}`;!e.isLoading&&this.debouncer.isDebounced(t)&&this.debouncer.executeNow(t)})}closeConnections(e){this.documents.forEach(t=>{e&&t.name!==e||t.connections.forEach((e,t)=>{t.close(X8)})})}handleConnection(e,t,n={}){let r=new zOe(e,t,this,this.hooks.bind(this),{timeout:this.configuration.timeout},n);return r.onClose((e,t)=>{e.getConnectionsCount()>0||(!e.isLoading&&this.debouncer.isDebounced(`onStoreDocument-${e.name}`)?this.configuration.unloadImmediately&&this.debouncer.executeNow(`onStoreDocument-${e.name}`):this.unloadDocument(e))}),r}handleDocumentUpdate(e,t,n){let r=F5(t)&&t.source===`connection`?t.connection:void 0,i=r?.request,a=F5(t)?t.source===`connection`?t.connection.context:t.source===`local`?t.context??{}:{}:{},o={instance:this,clientsCount:e.getConnectionsCount(),document:e,documentName:e.name,requestHeaders:i?.headers??new Headers,requestParameters:R5(i),socketId:r?.socketId??``,update:n,transactionOrigin:t,connection:r,context:a};if(this.hooks(`onChange`,o),POe(t))return;let s={instance:this,clientsCount:e.getConnectionsCount(),document:e,lastContext:a,lastTransactionOrigin:t,documentName:e.name};this.storeDocumentHooks(e,s)}async createDocument(e,t,n,r,i){if(!e.trim())throw Error(`Document name must not be empty`);let a=this.loadingDocuments.get(e);if(a)return a;let o=this.documents.get(e);if(o)return Promise.resolve(o);let s=this.loadDocument(e,t,n,r,i);this.loadingDocuments.set(e,s);try{let t=await s;return this.documents.set(e,t),this.loadingDocuments.delete(e),t}catch(t){throw this.loadingDocuments.delete(e),t}}async loadDocument(e,t,n,r,i){let a=t.headers,o=R5(t),s=i??{},c=await this.hooks(`onCreateDocument`,{documentName:e,requestHeaders:a,requestParameters:o,connectionConfig:r,context:s,socketId:n,instance:this}),l=new LOe(e,{...this.configuration.yDocOptions,...c}),u={instance:this,context:s,connectionConfig:r,document:l,documentName:e,socketId:n,requestHeaders:a,requestParameters:o};try{await this.hooks(`onLoadDocument`,u,e=>{e instanceof q_?lv(l,fv(e)):e instanceof Uint8Array&&lv(l,e)})}catch(t){throw this.closeConnections(e),this.unloadDocument(l),t}return l.isLoading=!1,l.onUpdate((e,t,n)=>{e.lastChangeTime=Date.now(),this.handleDocumentUpdate(e,t,n)}),await this.hooks(`afterLoadDocument`,u),l.beforeBroadcastStateless((e,t)=>{let n={document:e,documentName:e.name,payload:t};this.hooks(`beforeBroadcastStateless`,n)}),l.awareness.on(`update`,(t,n)=>{this.hooks(`onAwarenessUpdate`,{document:l,documentName:e,instance:this,...t,transactionOrigin:n,connection:F5(n)&&n.source===`connection`?n.connection:void 0,awareness:l.awareness,states:QDe(l.awareness.getStates())})}),l}storeDocumentHooks(e,t,n){let r=`onStoreDocument-${e.name}`;return this.debouncer.debounce(r,async()=>{try{await e.saveMutex.runExclusive(async()=>{await this.hooks(`onStoreDocument`,t),await this.hooks(`afterStoreDocument`,t)})}catch(t){if(t instanceof $De){setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0);return}console.error(`Caught error during storeDocumentHooks. Document stays in memory to avoid data loss`,t);return}setTimeout(()=>{this.shouldUnloadDocument(e)&&this.unloadDocument(e)},0)},n?0:this.configuration.debounce,this.configuration.maxDebounce)}hooks(e,t,n=null){let{extensions:r}=this.configuration,i=Promise.resolve();return r.filter(t=>typeof t[e]==`function`).forEach(r=>{i=i.then(()=>r[e]?.(t)).catch(t=>{throw t?.message&&console.error(`[${e}]`,t.message),t}),n&&(i=i.then((...e)=>n(...e)))}),i}shouldUnloadDocument(e){return(this.debouncer.isDebounced(`onStoreDocument-${e.name}`)||this.debouncer.isCurrentlyExecuting(`onStoreDocument-${e.name}`)||e.saveMutex.isLocked())===!1&&e.getConnectionsCount()===0}async unloadDocument(e){let t=e.name;if(!this.shouldUnloadDocument(e)||!this.documents.has(t))return;if(this.unloadingDocuments.has(t))return this.unloadingDocuments.get(t);let n=(async()=>{try{await this.hooks(`beforeUnloadDocument`,{instance:this,documentName:t,document:e})}catch{return}this.shouldUnloadDocument(e)&&(this.documents.delete(t),e.destroy(),await this.hooks(`afterUnloadDocument`,{instance:this,documentName:t}))})();this.unloadingDocuments.set(t,Promise.resolve(n)),await n,this.unloadingDocuments.delete(t)}async openDirectConnection(e,t){return new BOe(await this.createDocument(e,new Request(`http://localhost`),Su.randomUUID(),{isAuthenticated:!0,readOnly:!1},t),this,t)}},z5=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),B5=kl(import.meta.url),V5=z5(((e,t)=>{let n=[`nodebuffer`,`arraybuffer`,`fragments`],r=typeof Blob<`u`;r&&n.push(`blob`),t.exports={BINARY_TYPES:n,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:`258EAFA5-E914-47DA-95CA-C5AB0DC85B11`,hasBlob:r,kForOnEventAttribute:Symbol(`kIsForOnEventAttribute`),kListener:Symbol(`kListener`),kStatusCode:Symbol(`status-code`),kWebSocket:Symbol(`websocket`),NOOP:()=>{}}})),H5=z5(((e,t)=>{let{EMPTY_BUFFER:n}=V5(),r=Buffer[Symbol.species];function i(e,t){if(e.length===0)return n;if(e.length===1)return e[0];let i=Buffer.allocUnsafe(t),a=0;for(let t=0;t<e.length;t++){let n=e[t];i.set(n,a),a+=n.length}return a<t?new r(i.buffer,i.byteOffset,a):i}function a(e,t,n,r,i){for(let a=0;a<i;a++)n[r+a]=e[a]^t[a&3]}function o(e,t){for(let n=0;n<e.length;n++)e[n]^=t[n&3]}function s(e){return e.length===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.length)}function c(e){if(c.readOnly=!0,Buffer.isBuffer(e))return e;let t;return e instanceof ArrayBuffer?t=new r(e):ArrayBuffer.isView(e)?t=new r(e.buffer,e.byteOffset,e.byteLength):(t=Buffer.from(e),c.readOnly=!1),t}if(t.exports={concat:i,mask:a,toArrayBuffer:s,toBuffer:c,unmask:o},!process.env.WS_NO_BUFFER_UTIL)try{let e=B5(`bufferutil`);t.exports.mask=function(t,n,r,i,o){o<48?a(t,n,r,i,o):e.mask(t,n,r,i,o)},t.exports.unmask=function(t,n){t.length<32?o(t,n):e.unmask(t,n)}}catch{}})),WOe=z5(((e,t)=>{let n=Symbol(`kDone`),r=Symbol(`kRun`);t.exports=class{constructor(e){this[n]=()=>{this.pending--,this[r]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[r]()}[r](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[n])}}}})),U5=z5(((e,t)=>{let n=B5(`zlib`),r=H5(),i=WOe(),{kStatusCode:a}=V5(),o=Buffer[Symbol.species],s=Buffer.from([0,0,255,255]),c=Symbol(`permessage-deflate`),l=Symbol(`total-length`),u=Symbol(`callback`),d=Symbol(`buffers`),f=Symbol(`error`),p;t.exports=class{constructor(e,t,n){this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold===void 0?1024:this._options.threshold,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,p||=new i(this._options.concurrencyLimit===void 0?10:this._options.concurrencyLimit)}static get extensionName(){return`permessage-deflate`}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits??(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&=(this._inflate.close(),null),this._deflate){let e=this._deflate[u];this._deflate.close(),this._deflate=null,e&&e(Error(`The deflate stream was closed while data was being processed`))}}acceptAsServer(e){let t=this._options,n=e.find(e=>!(t.serverNoContextTakeover===!1&&e.server_no_context_takeover||e.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits==`number`&&t.serverMaxWindowBits>e.server_max_window_bits)||typeof t.clientMaxWindowBits==`number`&&!e.client_max_window_bits));if(!n)throw Error(`None of the extension offers can be accepted`);return t.serverNoContextTakeover&&(n.server_no_context_takeover=!0),t.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof t.serverMaxWindowBits==`number`&&(n.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits==`number`?n.client_max_window_bits=t.clientMaxWindowBits:(n.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw Error(`Unexpected parameter "client_no_context_takeover"`);if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits==`number`&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==`number`&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw Error(`Unexpected or invalid parameter "client_max_window_bits"`);return t}normalizeParams(e){return e.forEach(e=>{Object.keys(e).forEach(t=>{let n=e[t];if(n.length>1)throw Error(`Parameter "${t}" must have only a single value`);if(n=n[0],t===`client_max_window_bits`){if(n!==!0){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else if(t===`server_max_window_bits`){let e=+n;if(!Number.isInteger(e)||e<8||e>15)throw TypeError(`Invalid value for parameter "${t}": ${n}`);n=e}else if(t===`client_no_context_takeover`||t===`server_no_context_takeover`){if(n!==!0)throw TypeError(`Invalid value for parameter "${t}": ${n}`)}else throw Error(`Unknown parameter "${t}"`);e[t]=n})}),e}decompress(e,t,n){p.add(r=>{this._decompress(e,t,(e,t)=>{r(),n(e,t)})})}compress(e,t,n){p.add(r=>{this._compress(e,t,(e,t)=>{r(),n(e,t)})})}_decompress(e,t,i){let a=this._isServer?`client`:`server`;if(!this._inflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._inflate=n.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[c]=this,this._inflate[l]=0,this._inflate[d]=[],this._inflate.on(`error`,g),this._inflate.on(`data`,h)}this._inflate[u]=i,this._inflate.write(e),t&&this._inflate.write(s),this._inflate.flush(()=>{let e=this._inflate[f];if(e){this._inflate.close(),this._inflate=null,i(e);return}let n=r.concat(this._inflate[d],this._inflate[l]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[l]=0,this._inflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._inflate.reset()),i(null,n)})}_compress(e,t,i){let a=this._isServer?`server`:`client`;if(!this._deflate){let e=`${a}_max_window_bits`,t=typeof this.params[e]==`number`?this.params[e]:n.Z_DEFAULT_WINDOWBITS;this._deflate=n.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[l]=0,this._deflate[d]=[],this._deflate.on(`data`,m)}this._deflate[u]=i,this._deflate.write(e),this._deflate.flush(n.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let e=r.concat(this._deflate[d],this._deflate[l]);t&&(e=new o(e.buffer,e.byteOffset,e.length-4)),this._deflate[u]=null,this._deflate[l]=0,this._deflate[d]=[],t&&this.params[`${a}_no_context_takeover`]&&this._deflate.reset(),i(null,e)})}};function m(e){this[d].push(e),this[l]+=e.length}function h(e){if(this[l]+=e.length,this[c]._maxPayload<1||this[l]<=this[c]._maxPayload){this[d].push(e);return}this[f]=RangeError(`Max payload size exceeded`),this[f].code=`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`,this[f][a]=1009,this.removeListener(`data`,h),this.reset()}function g(e){if(this[c]._inflate=null,this[f]){this[u](this[f]);return}e[a]=1007,this[u](e)}})),W5=z5(((e,t)=>{let{isUtf8:n}=B5(`buffer`),{hasBlob:r}=V5(),i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function a(e){return e>=1e3&&e<=1014&&e!==1004&&e!==1005&&e!==1006||e>=3e3&&e<=4999}function o(e){let t=e.length,n=0;for(;n<t;)if(!(e[n]&128))n++;else if((e[n]&224)==192){if(n+1===t||(e[n+1]&192)!=128||(e[n]&254)==192)return!1;n+=2}else if((e[n]&240)==224){if(n+2>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||e[n]===224&&(e[n+1]&224)==128||e[n]===237&&(e[n+1]&224)==160)return!1;n+=3}else if((e[n]&248)==240){if(n+3>=t||(e[n+1]&192)!=128||(e[n+2]&192)!=128||(e[n+3]&192)!=128||e[n]===240&&(e[n+1]&240)==128||e[n]===244&&e[n+1]>143||e[n]>244)return!1;n+=4}else return!1;return!0}function s(e){return r&&typeof e==`object`&&typeof e.arrayBuffer==`function`&&typeof e.type==`string`&&typeof e.stream==`function`&&(e[Symbol.toStringTag]===`Blob`||e[Symbol.toStringTag]===`File`)}if(t.exports={isBlob:s,isValidStatusCode:a,isValidUTF8:o,tokenChars:i},n)t.exports.isValidUTF8=function(e){return e.length<24?o(e):n(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let e=B5(`utf-8-validate`);t.exports.isValidUTF8=function(t){return t.length<32?o(t):e(t)}}catch{}})),G5=z5(((e,t)=>{let{Writable:n}=B5(`stream`),r=U5(),{BINARY_TYPES:i,EMPTY_BUFFER:a,kStatusCode:o,kWebSocket:s}=V5(),{concat:c,toArrayBuffer:l,unmask:u}=H5(),{isValidStatusCode:d,isValidUTF8:f}=W5(),p=Buffer[Symbol.species];t.exports=class extends n{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents===void 0?!0:e.allowSynchronousEvents,this._binaryType=e.binaryType||i[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[s]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,n){if(this._opcode===8&&this._state==0)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let t=this._buffers[0];return this._buffers[0]=new p(t.buffer,t.byteOffset+e,t.length-e),new p(t.buffer,t.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let n=this._buffers[0],r=t.length-e;e>=n.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(n.buffer,n.byteOffset,e),r),this._buffers[0]=new p(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if(t[0]&48){e(this.createError(RangeError,`RSV2 and RSV3 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_2_3`));return}let n=(t[0]&64)==64;if(n&&!this._extensions[r.extensionName]){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._fin=(t[0]&128)==128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(!this._fragmented){e(this.createError(RangeError,`invalid opcode 0`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){e(this.createError(RangeError,`FIN must be set`,!0,1002,`WS_ERR_EXPECTED_FIN`));return}if(n){e(this.createError(RangeError,`RSV1 must be clear`,!0,1002,`WS_ERR_UNEXPECTED_RSV_1`));return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,`WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH`));return}}else{e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,`WS_ERR_INVALID_OPCODE`));return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)==128,this._isServer){if(!this._masked){e(this.createError(RangeError,`MASK must be set`,!0,1002,`WS_ERR_EXPECTED_MASK`));return}}else if(this._masked){e(this.createError(RangeError,`MASK must be clear`,!0,1002,`WS_ERR_UNEXPECTED_MASK`));return}this._payloadLength===126?this._state=1:this._payloadLength===127?this._state=2:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),n=t.readUInt32BE(0);if(n>2**21-1){e(this.createError(RangeError,`Unsupported WebSocket frame: payload length > 2^53 - 1`,!1,1009,`WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH`));return}this._payloadLength=n*2**32+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._masked?this._state=3:this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(e){let t=a;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&u(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=5,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[r.extensionName].decompress(e,this._fin,(e,n)=>{if(e)return t(e);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){t(this.createError(RangeError,`Max payload size exceeded`,!1,1009,`WS_ERR_UNSUPPORTED_MESSAGE_LENGTH`));return}this._fragments.push(n)}this.dataMessage(t),this._state===0&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=0;return}let t=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;r=this._binaryType===`nodebuffer`?c(n,t):this._binaryType===`arraybuffer`?l(c(n,t)):this._binaryType===`blob`?new Blob(n):n,this._allowSynchronousEvents?(this.emit(`message`,r,!0),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!0),this._state=0,this.startLoop(e)}))}else{let r=c(n,t);if(!this._skipUTF8Validation&&!f(r)){e(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._state===5||this._allowSynchronousEvents?(this.emit(`message`,r,!1),this._state=0):(this._state=6,setImmediate(()=>{this.emit(`message`,r,!1),this._state=0,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit(`conclude`,1005,a),this.end();else{let n=e.readUInt16BE(0);if(!d(n)){t(this.createError(RangeError,`invalid status code ${n}`,!0,1002,`WS_ERR_INVALID_CLOSE_CODE`));return}let r=new p(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!f(r)){t(this.createError(Error,`invalid UTF-8 sequence`,!0,1007,`WS_ERR_INVALID_UTF8`));return}this._loop=!1,this.emit(`conclude`,n,r),this.end()}this._state=0;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0):(this._state=6,setImmediate(()=>{this.emit(this._opcode===9?`ping`:`pong`,e),this._state=0,this.startLoop(t)}))}createError(e,t,n,r,i){this._loop=!1,this._errored=!0;let a=new e(n?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(a,this.createError),a.code=i,a[o]=r,a}}})),K5=z5(((e,t)=>{let{Duplex:n}=B5(`stream`),{randomFillSync:r}=B5(`crypto`),i=U5(),{EMPTY_BUFFER:a,kWebSocket:o,NOOP:s}=V5(),{isBlob:c,isValidStatusCode:l}=W5(),{mask:u,toBuffer:d}=H5(),f=Symbol(`kByteLength`),p=Buffer.alloc(4),m=8*1024,h,g=m;t.exports=class e{constructor(e,t,n){this._extensions=t||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=s,this[o]=void 0}static frame(e,t){let n,i=!1,a=2,o=!1;t.mask&&(n=t.maskBuffer||p,t.generateMask?t.generateMask(n):(g===m&&(h===void 0&&(h=Buffer.alloc(m)),r(h,0,m),g=0),n[0]=h[g++],n[1]=h[g++],n[2]=h[g++],n[3]=h[g++]),o=(n[0]|n[1]|n[2]|n[3])===0,a=6);let s;typeof e==`string`?(!t.mask||o)&&t[f]!==void 0?s=t[f]:(e=Buffer.from(e),s=e.length):(s=e.length,i=t.mask&&t.readOnly&&!o);let c=s;s>=65536?(a+=8,c=127):s>125&&(a+=2,c=126);let l=Buffer.allocUnsafe(i?s+a:a);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(s,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(s,4,6)),!t.mask||(l[1]|=128,l[a-4]=n[0],l[a-3]=n[1],l[a-2]=n[2],l[a-1]=n[3],o)?[l,e]:i?(u(e,n,l,a,s),[l]):(u(e,n,e,0,s),[l,e])}close(t,n,r,i){let o;if(t===void 0)o=a;else if(typeof t!=`number`||!l(t))throw TypeError(`First argument must be a valid error code number`);else if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(t,0);else{let e=Buffer.byteLength(n);if(e>123)throw RangeError(`The message must not be greater than 123 bytes`);o=Buffer.allocUnsafe(2+e),o.writeUInt16BE(t,0),typeof n==`string`?o.write(n,2):o.set(n,2)}let s={[f]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state===0?this.sendFrame(e.frame(o,s),i):this.enqueue([this.dispatch,o,!1,s,i])}ping(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}pong(t,n,r){let i,a;if(typeof t==`string`?(i=Buffer.byteLength(t),a=!1):c(t)?(i=t.size,a=!1):(t=d(t),i=t.length,a=d.readOnly),i>125)throw RangeError(`The data size must not be greater than 125 bytes`);let o={[f]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:a,rsv1:!1};c(t)?this._state===0?this.getBlobData(t,!1,o,r):this.enqueue([this.getBlobData,t,!1,o,r]):this._state===0?this.sendFrame(e.frame(t,o),r):this.enqueue([this.dispatch,t,!1,o,r])}send(e,t,n){let r=this._extensions[i.extensionName],a=t.binary?2:1,o=t.compress,s,l;typeof e==`string`?(s=Buffer.byteLength(e),l=!1):c(e)?(s=e.size,l=!1):(e=d(e),s=e.length,l=d.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?`server_no_context_takeover`:`client_no_context_takeover`]&&(o=s>=r._threshold),this._compress=o):(o=!1,a=0),t.fin&&(this._firstFragment=!0);let u={[f]:s,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:a,readOnly:l,rsv1:o};c(e)?this._state===0?this.getBlobData(e,this._compress,u,n):this.enqueue([this.getBlobData,e,this._compress,u,n]):this._state===0?this.dispatch(e,this._compress,u,n):this.enqueue([this.dispatch,e,this._compress,u,n])}getBlobData(t,n,r,i){this._bufferedBytes+=r[f],this._state=2,t.arrayBuffer().then(t=>{if(this._socket.destroyed){let e=Error(`The socket was closed while the blob was being read`);process.nextTick(_,this,e,i);return}this._bufferedBytes-=r[f];let a=d(t);n?this.dispatch(a,n,r,i):(this._state=0,this.sendFrame(e.frame(a,r),i),this.dequeue())}).catch(e=>{process.nextTick(v,this,e,i)})}dispatch(t,n,r,a){if(!n){this.sendFrame(e.frame(t,r),a);return}let o=this._extensions[i.extensionName];this._bufferedBytes+=r[f],this._state=1,o.compress(t,r.fin,(t,n)=>{if(this._socket.destroyed){_(this,Error(`The socket was closed while data was being compressed`),a);return}this._bufferedBytes-=r[f],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(n,r),a),this.dequeue()})}dequeue(){for(;this._state===0&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][f],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][f],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function _(e,t,n){typeof n==`function`&&n(t);for(let n=0;n<e._queue.length;n++){let r=e._queue[n],i=r[r.length-1];typeof i==`function`&&i(t)}}function v(e,t,n){_(e,t,n),e.onerror(t)}})),GOe=z5(((e,t)=>{let{kForOnEventAttribute:n,kListener:r}=V5(),i=Symbol(`kCode`),a=Symbol(`kData`),o=Symbol(`kError`),s=Symbol(`kMessage`),c=Symbol(`kReason`),l=Symbol(`kTarget`),u=Symbol(`kType`),d=Symbol(`kWasClean`);var f=class{constructor(e){this[l]=null,this[u]=e}get target(){return this[l]}get type(){return this[u]}};Object.defineProperty(f.prototype,`target`,{enumerable:!0}),Object.defineProperty(f.prototype,`type`,{enumerable:!0});var p=class extends f{constructor(e,t={}){super(e),this[i]=t.code===void 0?0:t.code,this[c]=t.reason===void 0?``:t.reason,this[d]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[i]}get reason(){return this[c]}get wasClean(){return this[d]}};Object.defineProperty(p.prototype,`code`,{enumerable:!0}),Object.defineProperty(p.prototype,`reason`,{enumerable:!0}),Object.defineProperty(p.prototype,`wasClean`,{enumerable:!0});var m=class extends f{constructor(e,t={}){super(e),this[o]=t.error===void 0?null:t.error,this[s]=t.message===void 0?``:t.message}get error(){return this[o]}get message(){return this[s]}};Object.defineProperty(m.prototype,`error`,{enumerable:!0}),Object.defineProperty(m.prototype,`message`,{enumerable:!0});var h=class extends f{constructor(e,t={}){super(e),this[a]=t.data===void 0?null:t.data}get data(){return this[a]}};Object.defineProperty(h.prototype,`data`,{enumerable:!0}),t.exports={CloseEvent:p,ErrorEvent:m,Event:f,EventTarget:{addEventListener(e,t,i={}){for(let a of this.listeners(e))if(!i[n]&&a[r]===t&&!a[n])return;let a;if(e===`message`)a=function(e,n){let r=new h(`message`,{data:n?e:e.toString()});r[l]=this,g(t,this,r)};else if(e===`close`)a=function(e,n){let r=new p(`close`,{code:e,reason:n.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});r[l]=this,g(t,this,r)};else if(e===`error`)a=function(e){let n=new m(`error`,{error:e,message:e.message});n[l]=this,g(t,this,n)};else if(e===`open`)a=function(){let e=new f(`open`);e[l]=this,g(t,this,e)};else return;a[n]=!!i[n],a[r]=t,i.once?this.once(e,a):this.on(e,a)},removeEventListener(e,t){for(let i of this.listeners(e))if(i[r]===t&&!i[n]){this.removeListener(e,i);break}}},MessageEvent:h};function g(e,t,n){typeof e==`object`&&e.handleEvent?e.handleEvent.call(e,n):e.call(t,n)}})),q5=z5(((e,t)=>{let{tokenChars:n}=W5();function r(e,t,n){e[t]===void 0?e[t]=[n]:e[t].push(n)}function i(e){let t=Object.create(null),i=Object.create(null),a=!1,o=!1,s=!1,c,l,u=-1,d=-1,f=-1,p=0;for(;p<e.length;p++)if(d=e.charCodeAt(p),c===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(p!==0&&(d===32||d===9))f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);d===44?(r(t,n,i),i=Object.create(null)):c=n,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);else if(l===void 0)if(f===-1&&n[d]===1)u===-1&&(u=p);else if(d===32||d===9)f===-1&&u!==-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p),r(i,e.slice(u,f),!0),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),u=f=-1}else if(d===61&&u!==-1&&f===-1)l=e.slice(u,p),u=f=-1;else throw SyntaxError(`Unexpected character at index ${p}`);else if(o){if(n[d]!==1)throw SyntaxError(`Unexpected character at index ${p}`);u===-1?u=p:a||=!0,o=!1}else if(s)if(n[d]===1)u===-1&&(u=p);else if(d===34&&u!==-1)s=!1,f=p;else if(d===92)o=!0;else throw SyntaxError(`Unexpected character at index ${p}`);else if(d===34&&e.charCodeAt(p-1)===61)s=!0;else if(f===-1&&n[d]===1)u===-1&&(u=p);else if(u!==-1&&(d===32||d===9))f===-1&&(f=p);else if(d===59||d===44){if(u===-1)throw SyntaxError(`Unexpected character at index ${p}`);f===-1&&(f=p);let n=e.slice(u,f);a&&=(n=n.replace(/\\/g,``),!1),r(i,l,n),d===44&&(r(t,c,i),i=Object.create(null),c=void 0),l=void 0,u=f=-1}else throw SyntaxError(`Unexpected character at index ${p}`);if(u===-1||s||d===32||d===9)throw SyntaxError(`Unexpected end of input`);f===-1&&(f=p);let m=e.slice(u,f);return c===void 0?r(t,m,i):(l===void 0?r(i,m,!0):a?r(i,l,m.replace(/\\/g,``)):r(i,l,m),r(t,c,i)),t}function a(e){return Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>[t].concat(Object.keys(e).map(t=>{let n=e[t];return Array.isArray(n)||(n=[n]),n.map(e=>e===!0?t:`${t}=${e}`).join(`; `)})).join(`; `)).join(`, `)}).join(`, `)}t.exports={format:a,parse:i}})),J5=z5(((e,t)=>{let n=B5(`events`),r=B5(`https`),i=B5(`http`),a=B5(`net`),o=B5(`tls`),{randomBytes:s,createHash:c}=B5(`crypto`),{Duplex:l,Readable:u}=B5(`stream`),{URL:d}=B5(`url`),f=U5(),p=G5(),m=K5(),{isBlob:h}=W5(),{BINARY_TYPES:g,CLOSE_TIMEOUT:_,EMPTY_BUFFER:v,GUID:y,kForOnEventAttribute:b,kListener:x,kStatusCode:S,kWebSocket:C,NOOP:w}=V5(),{EventTarget:{addEventListener:T,removeEventListener:E}}=GOe(),{format:ee,parse:te}=q5(),{toBuffer:D}=H5(),O=Symbol(`kAborted`),k=[8,13],A=[`CONNECTING`,`OPEN`,`CLOSING`,`CLOSED`],ne=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;var re=class e extends n{constructor(t,n,r){super(),this._binaryType=g[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=v,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol=``,this._readyState=e.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t===null?(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0):(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n==`object`&&n?(r=n,n=[]):n=[n]),ie(this,t,n,r))}get binaryType(){return this._binaryType}set binaryType(e){g.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,n,r){let i=new p({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),a=new m(t,this._extensions,r.generateMask);this._receiver=i,this._sender=a,this._socket=t,i[C]=this,a[C]=this,t[C]=this,i.on(`conclude`,le),i.on(`drain`,ue),i.on(`error`,de),i.on(`message`,pe),i.on(`ping`,me),i.on(`pong`,he),a.onerror=_e,t.setTimeout&&t.setTimeout(0),t.setNoDelay&&t.setNoDelay(),n.length>0&&t.unshift(n),t.on(`close`,N),t.on(`data`,ve),t.on(`end`,ye),t.on(`error`,be),this._readyState=e.OPEN,this.emit(`open`)}emitClose(){if(!this._socket){this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage);return}this._extensions[f.extensionName]&&this._extensions[f.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=e.CLOSED,this.emit(`close`,this._closeCode,this._closeMessage)}close(t,n){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}if(this.readyState===e.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=e.CLOSING,this._sender.close(t,n,!this._isServer,e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),M(this)}}pause(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!0,this._socket.pause())}ping(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(t||v,n,r)}pong(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof t==`function`?(r=t,t=n=void 0):typeof n==`function`&&(r=n,n=void 0),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(t||v,n,r)}resume(){this.readyState===e.CONNECTING||this.readyState===e.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(t,n,r){if(this.readyState===e.CONNECTING)throw Error(`WebSocket is not open: readyState 0 (CONNECTING)`);if(typeof n==`function`&&(r=n,n={}),typeof t==`number`&&(t=t.toString()),this.readyState!==e.OPEN){ce(this,t,r);return}let i={binary:typeof t!=`string`,mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[f.extensionName]||(i.compress=!1),this._sender.send(t||v,i,r)}terminate(){if(this.readyState!==e.CLOSED){if(this.readyState===e.CONNECTING){j(this,this._req,`WebSocket was closed before the connection was established`);return}this._socket&&(this._readyState=e.CLOSING,this._socket.destroy())}}};Object.defineProperty(re,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(re.prototype,`CONNECTING`,{enumerable:!0,value:A.indexOf(`CONNECTING`)}),Object.defineProperty(re,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(re.prototype,`OPEN`,{enumerable:!0,value:A.indexOf(`OPEN`)}),Object.defineProperty(re,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(re.prototype,`CLOSING`,{enumerable:!0,value:A.indexOf(`CLOSING`)}),Object.defineProperty(re,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),Object.defineProperty(re.prototype,`CLOSED`,{enumerable:!0,value:A.indexOf(`CLOSED`)}),[`binaryType`,`bufferedAmount`,`extensions`,`isPaused`,`protocol`,`readyState`,`url`].forEach(e=>{Object.defineProperty(re.prototype,e,{enumerable:!0})}),[`open`,`error`,`close`,`message`].forEach(e=>{Object.defineProperty(re.prototype,`on${e}`,{enumerable:!0,get(){for(let t of this.listeners(e))if(t[b])return t[x];return null},set(t){for(let t of this.listeners(e))if(t[b]){this.removeListener(e,t);break}typeof t==`function`&&this.addEventListener(e,t,{[b]:!0})}})}),re.prototype.addEventListener=T,re.prototype.removeEventListener=E,t.exports=re;function ie(e,t,n,a){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:_,protocolVersion:k[1],maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...a,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:`GET`,host:void 0,path:void 0,port:void 0};if(e._autoPong=o.autoPong,e._closeTimeout=o.closeTimeout,!k.includes(o.protocolVersion))throw RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${k.join(`, `)})`);let l;if(t instanceof d)l=t;else try{l=new d(t)}catch{throw SyntaxError(`Invalid URL: ${t}`)}l.protocol===`http:`?l.protocol=`ws:`:l.protocol===`https:`&&(l.protocol=`wss:`),e._url=l.href;let u=l.protocol===`wss:`,p=l.protocol===`ws+unix:`,m;if(l.protocol!==`ws:`&&!u&&!p?m=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:p&&!l.pathname?m=`The URL's pathname is empty`:l.hash&&(m=`The URL contains a fragment identifier`),m){let t=SyntaxError(m);if(e._redirects===0)throw t;ae(e,t);return}let h=u?443:80,g=s(16).toString(`base64`),v=u?r.request:i.request,b=new Set,x;if(o.createConnection=o.createConnection||(u?se:oe),o.defaultPort=o.defaultPort||h,o.port=l.port||h,o.host=l.hostname.startsWith(`[`)?l.hostname.slice(1,-1):l.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":g,Connection:`Upgrade`,Upgrade:`websocket`},o.path=l.pathname+l.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(x=new f(o.perMessageDeflate===!0?{}:o.perMessageDeflate,!1,o.maxPayload),o.headers[`Sec-WebSocket-Extensions`]=ee({[f.extensionName]:x.offer()})),n.length){for(let e of n){if(typeof e!=`string`||!ne.test(e)||b.has(e))throw SyntaxError(`An invalid or duplicated subprotocol was specified`);b.add(e)}o.headers[`Sec-WebSocket-Protocol`]=n.join(`,`)}if(o.origin&&(o.protocolVersion<13?o.headers[`Sec-WebSocket-Origin`]=o.origin:o.headers.Origin=o.origin),(l.username||l.password)&&(o.auth=`${l.username}:${l.password}`),p){let e=o.path.split(`:`);o.socketPath=e[0],o.path=e[1]}let S;if(o.followRedirects){if(e._redirects===0){e._originalIpc=p,e._originalSecure=u,e._originalHostOrSocketPath=p?o.socketPath:l.host;let t=a&&a.headers;if(a={...a,headers:{}},t)for(let[e,n]of Object.entries(t))a.headers[e.toLowerCase()]=n}else if(e.listenerCount(`redirect`)===0){let t=p?e._originalIpc?o.socketPath===e._originalHostOrSocketPath:!1:e._originalIpc?!1:l.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!u)&&(delete o.headers.authorization,delete o.headers.cookie,t||delete o.headers.host,o.auth=void 0)}o.auth&&!a.headers.authorization&&(a.headers.authorization=`Basic `+Buffer.from(o.auth).toString(`base64`)),S=e._req=v(o),e._redirects&&e.emit(`redirect`,e.url,S)}else S=e._req=v(o);o.timeout&&S.on(`timeout`,()=>{j(e,S,`Opening handshake has timed out`)}),S.on(`error`,t=>{S===null||S[O]||(S=e._req=null,ae(e,t))}),S.on(`response`,r=>{let i=r.headers.location,s=r.statusCode;if(i&&o.followRedirects&&s>=300&&s<400){if(++e._redirects>o.maxRedirects){j(e,S,`Maximum redirects exceeded`);return}S.abort();let r;try{r=new d(i,t)}catch{ae(e,SyntaxError(`Invalid URL: ${i}`));return}ie(e,r,n,a)}else e.emit(`unexpected-response`,S,r)||j(e,S,`Unexpected server response: ${r.statusCode}`)}),S.on(`upgrade`,(t,n,r)=>{if(e.emit(`upgrade`,t),e.readyState!==re.CONNECTING)return;S=e._req=null;let i=t.headers.upgrade;if(i===void 0||i.toLowerCase()!==`websocket`){j(e,n,`Invalid Upgrade header`);return}let a=c(`sha1`).update(g+y).digest(`base64`);if(t.headers[`sec-websocket-accept`]!==a){j(e,n,`Invalid Sec-WebSocket-Accept header`);return}let s=t.headers[`sec-websocket-protocol`],l;if(s===void 0?b.size&&(l=`Server sent no subprotocol`):b.size?b.has(s)||(l=`Server sent an invalid subprotocol`):l=`Server sent a subprotocol but none was requested`,l){j(e,n,l);return}s&&(e._protocol=s);let u=t.headers[`sec-websocket-extensions`];if(u!==void 0){if(!x){j(e,n,`Server sent a Sec-WebSocket-Extensions header but no extension was requested`);return}let t;try{t=te(u)}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}let r=Object.keys(t);if(r.length!==1||r[0]!==f.extensionName){j(e,n,`Server indicated an extension that was not requested`);return}try{x.accept(t[f.extensionName])}catch{j(e,n,`Invalid Sec-WebSocket-Extensions header`);return}e._extensions[f.extensionName]=x}e.setSocket(n,r,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(S,e):S.end()}function ae(e,t){e._readyState=re.CLOSING,e._errorEmitted=!0,e.emit(`error`,t),e.emitClose()}function oe(e){return e.path=e.socketPath,a.connect(e)}function se(e){return e.path=void 0,!e.servername&&e.servername!==``&&(e.servername=a.isIP(e.host)?``:e.host),o.connect(e)}function j(e,t,n){e._readyState=re.CLOSING;let r=Error(n);Error.captureStackTrace(r,j),t.setHeader?(t[O]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(ae,e,r)):(t.destroy(r),t.once(`error`,e.emit.bind(e,`error`)),t.once(`close`,e.emitClose.bind(e)))}function ce(e,t,n){if(t){let n=h(t)?t.size:D(t).length;e._socket?e._sender._bufferedBytes+=n:e._bufferedAmount+=n}if(n){let t=Error(`WebSocket is not open: readyState ${e.readyState} (${A[e.readyState]})`);process.nextTick(n,t)}}function le(e,t){let n=this[C];n._closeFrameReceived=!0,n._closeMessage=t,n._closeCode=e,n._socket[C]!==void 0&&(n._socket.removeListener(`data`,ve),process.nextTick(ge,n._socket),e===1005?n.close():n.close(e,t))}function ue(){let e=this[C];e.isPaused||e._socket.resume()}function de(e){let t=this[C];t._socket[C]!==void 0&&(t._socket.removeListener(`data`,ve),process.nextTick(ge,t._socket),t.close(e[S])),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e))}function fe(){this[C].emitClose()}function pe(e,t){this[C].emit(`message`,e,t)}function me(e){let t=this[C];t._autoPong&&t.pong(e,!this._isServer,w),t.emit(`ping`,e)}function he(e){this[C].emit(`pong`,e)}function ge(e){e.resume()}function _e(e){let t=this[C];t.readyState!==re.CLOSED&&(t.readyState===re.OPEN&&(t._readyState=re.CLOSING,M(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit(`error`,e)))}function M(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),e._closeTimeout)}function N(){let e=this[C];if(this.removeListener(`close`,N),this.removeListener(`data`,ve),this.removeListener(`end`,ye),e._readyState=re.CLOSING,!this._readableState.endEmitted&&!e._closeFrameReceived&&!e._receiver._writableState.errorEmitted&&this._readableState.length!==0){let t=this.read(this._readableState.length);e._receiver.write(t)}e._receiver.end(),this[C]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on(`error`,fe),e._receiver.on(`finish`,fe))}function ve(e){this[C]._receiver.write(e)||this.pause()}function ye(){let e=this[C];e._readyState=re.CLOSING,e._receiver.end(),this.end()}function be(){let e=this[C];this.removeListener(`error`,be),this.on(`error`,w),e&&(e._readyState=re.CLOSING,this.destroy())}})),KOe=z5(((e,t)=>{J5();let{Duplex:n}=B5(`stream`);function r(e){e.emit(`close`)}function i(){!this.destroyed&&this._writableState.finished&&this.destroy()}function a(e){this.removeListener(`error`,a),this.destroy(),this.listenerCount(`error`)===0&&this.emit(`error`,e)}function o(e,t){let o=!0,s=new n({...t,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return e.on(`message`,function(t,n){let r=!n&&s._readableState.objectMode?t.toString():t;s.push(r)||e.pause()}),e.once(`error`,function(e){s.destroyed||(o=!1,s.destroy(e))}),e.once(`close`,function(){s.destroyed||s.push(null)}),s._destroy=function(t,n){if(e.readyState===e.CLOSED){n(t),process.nextTick(r,s);return}let i=!1;e.once(`error`,function(e){i=!0,n(e)}),e.once(`close`,function(){i||n(t),process.nextTick(r,s)}),o&&e.terminate()},s._final=function(t){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._final(t)});return}e._socket!==null&&(e._socket._writableState.finished?(t(),s._readableState.endEmitted&&s.destroy()):(e._socket.once(`finish`,function(){t()}),e.close()))},s._read=function(){e.isPaused&&e.resume()},s._write=function(t,n,r){if(e.readyState===e.CONNECTING){e.once(`open`,function(){s._write(t,n,r)});return}e.send(t,r)},s.on(`end`,i),s.on(`error`,a),s}t.exports=o})),qOe=z5(((e,t)=>{let{tokenChars:n}=W5();function r(e){let t=new Set,r=-1,i=-1,a=0;for(;a<e.length;a++){let o=e.charCodeAt(a);if(i===-1&&n[o]===1)r===-1&&(r=a);else if(a!==0&&(o===32||o===9))i===-1&&r!==-1&&(i=a);else if(o===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${a}`);i===-1&&(i=a);let n=e.slice(r,i);if(t.has(n))throw SyntaxError(`The "${n}" subprotocol is duplicated`);t.add(n),r=i=-1}else throw SyntaxError(`Unexpected character at index ${a}`)}if(r===-1||i!==-1)throw SyntaxError(`Unexpected end of input`);let o=e.slice(r,a);if(t.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return t.add(o),t}t.exports={parse:r}})),JOe=z5(((e,t)=>{let n=B5(`events`),r=B5(`http`),{Duplex:i}=B5(`stream`),{createHash:a}=B5(`crypto`),o=q5(),s=U5(),c=qOe(),l=J5(),{CLOSE_TIMEOUT:u,GUID:d,kWebSocket:f}=V5(),p=/^[+/0-9A-Za-z]{22}==$/;t.exports=class extends n{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:u,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:l,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw TypeError(`One and only one of the "port", "server", or "noServer" options must be specified`);if(e.port==null?e.server&&(this._server=e.server):(this._server=r.createServer((e,t)=>{let n=r.STATUS_CODES[426];t.writeHead(426,{"Content-Length":n.length,"Content-Type":`text/plain`}),t.end(n)}),this._server.listen(e.port,e.host,e.backlog,t)),this._server){let e=this.emit.bind(this,`connection`);this._removeListeners=m(this._server,{listening:this.emit.bind(this,`listening`),error:this.emit.bind(this,`error`),upgrade:(t,n,r)=>{this.handleUpgrade(t,n,r,e)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=0}address(){if(this.options.noServer)throw Error(`The server is operating in "noServer" mode`);return this._server?this._server.address():null}close(e){if(this._state===2){e&&this.once(`close`,()=>{e(Error(`The server is not running`))}),process.nextTick(h,this);return}if(e&&this.once(`close`,e),this._state!==1)if(this._state=1,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients&&this.clients.size?this._shouldEmitClose=!0:process.nextTick(h,this);else{let e=this._server;this._removeListeners(),this._removeListeners=this._server=null,e.close(()=>{h(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf(`?`);if((t===-1?e.url:e.url.slice(0,t))!==this.options.path)return!1}return!0}handleUpgrade(e,t,n,r){t.on(`error`,g);let i=e.headers[`sec-websocket-key`],a=e.headers.upgrade,l=+e.headers[`sec-websocket-version`];if(e.method!==`GET`){v(this,e,t,405,`Invalid HTTP method`);return}if(a===void 0||a.toLowerCase()!==`websocket`){v(this,e,t,400,`Invalid Upgrade header`);return}if(i===void 0||!p.test(i)){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Key header`);return}if(l!==13&&l!==8){v(this,e,t,400,`Missing or invalid Sec-WebSocket-Version header`,{"Sec-WebSocket-Version":`13, 8`});return}if(!this.shouldHandle(e)){_(t,400);return}let u=e.headers[`sec-websocket-protocol`],d=new Set;if(u!==void 0)try{d=c.parse(u)}catch{v(this,e,t,400,`Invalid Sec-WebSocket-Protocol header`);return}let f=e.headers[`sec-websocket-extensions`],m={};if(this.options.perMessageDeflate&&f!==void 0){let n=new s(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let e=o.parse(f);e[s.extensionName]&&(n.accept(e[s.extensionName]),m[s.extensionName]=n)}catch{v(this,e,t,400,`Invalid or unacceptable Sec-WebSocket-Extensions header`);return}}if(this.options.verifyClient){let a={origin:e.headers[`${l===8?`sec-websocket-origin`:`origin`}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(a,(a,o,s,c)=>{if(!a)return _(t,o||401,s,c);this.completeUpgrade(m,i,d,e,t,n,r)});return}if(!this.options.verifyClient(a))return _(t,401)}this.completeUpgrade(m,i,d,e,t,n,r)}completeUpgrade(e,t,n,r,i,c,l){if(!i.readable||!i.writable)return i.destroy();if(i[f])throw Error(`server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration`);if(this._state>0)return _(i,503);let u=[`HTTP/1.1 101 Switching Protocols`,`Upgrade: websocket`,`Connection: Upgrade`,`Sec-WebSocket-Accept: ${a(`sha1`).update(t+d).digest(`base64`)}`],p=new this.options.WebSocket(null,void 0,this.options);if(n.size){let e=this.options.handleProtocols?this.options.handleProtocols(n,r):n.values().next().value;e&&(u.push(`Sec-WebSocket-Protocol: ${e}`),p._protocol=e)}if(e[s.extensionName]){let t=e[s.extensionName].params,n=o.format({[s.extensionName]:[t]});u.push(`Sec-WebSocket-Extensions: ${n}`),p._extensions=e}this.emit(`headers`,u,r),i.write(u.concat(`\r
2018
2018
  `).join(`\r
2019
2019
  `)),i.removeListener(`error`,g),p.setSocket(i,c,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(p),p.on(`close`,()=>{this.clients.delete(p),this._shouldEmitClose&&!this.clients.size&&process.nextTick(h,this)})),l(p,r)}};function m(e,t){for(let n of Object.keys(t))e.on(n,t[n]);return function(){for(let n of Object.keys(t))e.removeListener(n,t[n])}}function h(e){e._state=2,e.emit(`close`)}function g(){this.destroy()}function _(e,t,n,i){n||=r.STATUS_CODES[t],i={Connection:`close`,"Content-Type":`text/html`,"Content-Length":Buffer.byteLength(n),...i},e.once(`finish`,e.destroy),e.end(`HTTP/1.1 ${t} ${r.STATUS_CODES[t]}\r\n`+Object.keys(i).map(e=>`${e}: ${i[e]}`).join(`\r
2020
2020
  `)+`\r
@@ -2034,7 +2034,7 @@ native-divergence-injected
2034
2034
  `,`utf-8`),o&&E!==void 0){let r=null;try{B(k)&&(r=V(k,`utf-8`))}catch(e){r=null,k7.warn({err:e,documentName:i},`[persistence] L3 disk-read failed; divergence check skipped for this store`)}if(r!==null&&Hi(r)!==Hi(E)){let a=r;console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":i,outcome:`reverted`,diskBytes:a.length,baseBytes:E.length,candidateBytes:S.length})),N(n,i,S,a);let o=e?.getLossRing?.(),s={baselineFullMd:a,report:e=>{try{let t=Lx(e);if(t.length===0)return;o?.record({event:Lb,docName:i,writerId:Tx.id,direction:`b`,site:de,lostLen:t.reduce((e,t)=>e+t.length,0),digest:_a(t.join(`
2035
2035
  `))})}catch(e){k7.warn({documentName:i,err:e},`[persistence] divergence-realign loss detection failed`)}}};try{n.transact(()=>{x(n,a,void 0,void 0,void 0,s)},uz)}catch(e){throw t.recordStoreFailure(i,M7(e)),C.delete(i),e}t.setReconciledBase(i,a),t.recordStoreDivergence(i),C.delete(i);return}}e?.isRecentlyRemoved?.(i)&&(aoe(),console.warn(JSON.stringify({event:`persistence-store-removed-doc`,"doc.name":i})));let A=`${k}.tmp.${crypto.randomUUID()}`;try{if(process.env.NODE_ENV===`test`&&process.env.OK_TEST_STORE_FAULT===i){let e=Error(`OK_TEST_STORE_FAULT: simulated disk failure for ${i}`);throw e.code=`ENOSPC`,e}await Qo(A,S,`utf-8`),await _s(A,k),Nz(k,Fz(S)),t.clearStoreFailure(i),uoe();try{d?.(i,f,S,E??null)}catch(e){k7.warn({err:e,documentName:i},`[persistence] onDiskFlush callback failed for ${i}`)}}catch(e){try{is(A)}catch{}throw C.delete(i),t.recordStoreFailure(i,M7(e)),k7.error({err:e,documentName:i},`[persistence] Failed to save ${i}`),e}k7.info({filePath:k,bytes:S.length},`[persistence] Wrote ${k} (${S.length} bytes)`),t.setReconciledBase(i,S),b.add(i),y.delete(i),C.delete(i);try{await s?.recordDurableStore(i,S)}catch(e){k7.warn({err:e,documentName:i},`[derived-index] durable-store projection failed; disk write remains authoritative`)}Wo({"persistence.bytes":S.length}),oe()}).finally(()=>{l!==void 0&&t.finishInFlightFlush(i,l),xe?.record((Date.now()-o)/1e3)})}function Te({document:e,documentName:n,lastTransactionOrigin:r}){ne.set(n,{branch:t.getActiveBranch(),document:e,lastTransactionOrigin:r})}async function Ee(e=`within-branch`){return A?(S=S===`discard-stale`||e===`discard-stale`?`discard-stale`:`within-branch`,A):(A=(async()=>{let n=e;for(;;){let e=[...ne.entries()];if(ne.clear(),n!==`discard-stale`){for(let[n,r]of e)if(r.branch===t.getActiveBranch())try{await we({document:r.document,documentName:n,lastTransactionOrigin:r.lastTransactionOrigin})}catch(e){let t=process.env.OK_TELEMETRY_VERBOSE===`1`,r=``;try{r=String(e?.message??``)}catch{r=``}let i=_a(r),a;try{a=Fke(e)}catch(e){let r=String(e?.message??``);console.warn(JSON.stringify({event:`deferred-store-classifier-failed`,"doc.name":n,classifyErrorHash:_a(r),errorMessageHash:i,...t?{classifyErrorMessage:r}:{},timestamp:new Date().toISOString()})),a=`unknown`}ose(),console.warn(JSON.stringify({event:`deferred-store-failed`,"doc.name":n,errorClass:a,errorMessageHash:i,...t?{errorMessage:r}:{},timestamp:new Date().toISOString()})),k7.error({err:e,documentName:n},`[persistence] Deferred store failed for ${n}`)}}let r=S;if(S=null,ne.size===0&&r===null)break;n=r??`within-branch`}})().finally(()=>{A=null}),A)}let De={async onLoadDocument({document:n,documentName:i,context:a}){if(b.delete(i),Zx(i))return;if(Qx(i)){$Oe(n,i,h);return}if($x(i)){hq(n,i,_);return}if(eS(i)||tS(i)){kke(n,i,v);return}Ce();let o=Date.now();return Zo(`persistence.onLoadDocument`,{attributes:{"doc.name":i}},async()=>{k7.info({documentName:i,connections:n.getConnectionsCount?.()??`?`},`[persistence] onLoadDocument called for ${i} (connections: ${n.getConnectionsCount?.()??`?`})`);let a=cN(i,r);if(!B(a))return;let o=a;try{let e=H(a);if(!lN(e,r)){k7.warn({path:a,canonical:e},`[persistence] symlink-escape on load: ${a} → ${e}, refusing`);return}o=e}catch(e){if(Us(e)===`ELOOP`){k7.warn({path:a},`[persistence] Symlink cycle on load: ${a}, refusing`);return}}let s=ou(o).size;if(s>524288)throw k7.warn({documentName:i,fileSize:s,limit:Vi},`[persistence] Document exceeds open byte limit; refusing to load`),new Nke(i,s);let c=V(a,`utf-8`),l=n.getXmlFragment(`default`);k7.info({documentName:i,fragmentLength:l.length},`[persistence] onLoadDocument ${i}: fragment.length=${l.length} before update`),l.length===0?(n.transact(()=>{dz(n,c,e?.resolveEmbed,i,e?.resolveSize),n.getMap(`lifecycle`).set(Zr,crypto.randomUUID())},uz),k7.info({filePath:a,children:l.length},`[persistence] Loaded ${a} into Y.Doc (${l.length} children)`),l.observeDeep(()=>{k7.info({documentName:i,fragmentLength:l.length},`[persistence] MUTATION on ${i}: fragment.length=${l.length}`)})):k7.info({documentName:i,children:l.length},`[persistence] Skipped load for ${i} — fragment already has ${l.length} children`),t.setReconciledBase(i,c)}).finally(()=>{be?.record((Date.now()-o)/1e3)})},async onStoreDocument({document:e,documentName:n,lastTransactionOrigin:r,lastContext:i}){if(!Zx(n)){if(Qx(n)){let t=await tke(e,n,r,h);if(t===`persisted`||t===`reconciled`)try{f?.(n)}catch(e){k7.warn({err:e,documentName:n},`[persistence] onConfigPersisted callback failed`)}return}if($x(n)){if(await vq(e,n,r,_)===`persisted`){let e=A7(r,c);if(e&&e.id!==Dx.id&&!e.id.startsWith(`agent-`)){let t=sq(n);t&&(ej(t.docKey,e.id,e.name,e.id,t.subject),oe())}}return}if(eS(n)||tS(n)){await Ake(e,n,r,v);return}if(t.isBatchInProgress()){Te({document:e,documentName:n,lastTransactionOrigin:r});return}return we({document:e,documentName:n,lastTransactionOrigin:r})}}};async function Oe(){O&&await O}async function ke(){if(O){await O;return}cj()!==0&&(O=re().finally(()=>{O=null,k&&(k=!1,oe())}),await O)}function Ae(){return{branchDeferred:ne.size,quiescenceDeferred:C.size}}async function je(e,n){if(!iS(n)){if(t.isBatchInProgress()){Te({document:e,documentName:n,lastTransactionOrigin:null});return}return we({document:e,documentName:n,lastTransactionOrigin:null})}}return{extension:De,durabilityState:t,flushDeferredStores:Ee,flushPendingGitCommit:se,flushContributors:ke,waitForPendingCommits:Oe,getQueueDepths:Ae,forceStore:je,configPersistenceCtx:h,managedArtifactCtx:_}}const P7=F(`persistence-staleness`);var F7=class extends Error{constructor(e){super(e),this.name=`StructuralDiskReadError`}};function Lke(e){let t=e.graceMs??3e5,n=e.sweepIntervalMs??6e4,r=e.now??Date.now,{getBase:i,isBatchActive:a,peekInFlight:o}=e,s=e.msSinceLastUserTx??QS,c=new Map,l=!1,u=null;function d(e){return j7(e)}function f(e){return e===void 0?void 0:Hi(e)}function p(e,t,n,r){return t===void 0?e!==``:e===t?r!==void 0&&Ca(r,n):!0}async function m(){if(l||a())return;let n=r(),u=0,m=0,h=0,g=0,_=new Set;for(let[n,v]of e.getLoadedDocuments()){if(l)return;if(_.add(n),iS(n)||hS(v)!==null||o(n)!==void 0)continue;u++;let y=v.getText(`source`).toString(),b=i(n);if(b!==void 0&&y===b){c.delete(n);continue}let x=d(y),S=f(b);if(!p(x,S,y,b)){c.delete(n);continue}m++;let C=r(),w=s(v,C);if(w!==null&&w<t)continue;let T=c.get(n);if(T&&T.fingerprint===x&&(T.declined||C-T.atMs<t))continue;let E=T?.fingerprint!==x;E&&woe();let ee=!E&&T?T.firstDetectedAtMs:C,te=C-ee,D=null,O=!1;try{let t=e.readDiskBytes(n);S===void 0?t!==null&&(D=`disk-file-never-loaded`):t===null?D=`disk-file-missing`:Hi(t)!==S&&(D=`disk-diverged-from-base`)}catch(e){e instanceof F7?(D=`disk-read-refused`,P7.error({err:e,docName:n},`[persistence-staleness] disk read refused; standing down until content changes`)):(D=`disk-read-failed`,O=!0,P7.warn({err:e,docName:n},`[persistence-staleness] disk read failed; standing down`))}if(D!==null){g++,Eoe(),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!O}),P7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`stood-down`,reason:D},`[persistence-staleness] Unflushed edits detected for ${n} but disk state is unverified or unreconciled; not overwriting`);continue}P7.warn({docName:n,ageMs:w,staleForMs:te,candidateBytes:x.length,baseBytes:b?.length??0,action:`forced-store`},`[persistence-staleness] Doc ${n} has unpersisted edits past the grace window with no pending store; forcing a store`),c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!1}),Toe(),h++;try{await e.forceStore(v,n)}catch(e){P7.error({err:e,docName:n,staleForMs:te},`[persistence-staleness] Forced store failed for ${n}; will retry`);continue}if(l||a())return;let k=v.getText(`source`).toString(),A=i(n),ne=d(k);p(ne,f(A),k,A)&&ne===x?(c.set(n,{fingerprint:x,atMs:C,firstDetectedAtMs:ee,declined:!0}),P7.info({docName:n},`[persistence-staleness] Store completed without clearing divergence for ${n}; suppressing until content changes`)):c.delete(n)}for(let e of c.keys())_.has(e)||c.delete(e);let v={scanned:u,divergent:m,forced:h,stoodDown:g,elapsedMs:r()-n};m>0||h>0||g>0?P7.info(v,`[persistence-staleness] sweep complete`):P7.debug(v,`[persistence-staleness] sweep complete`)}function h(){return u||(u=m().finally(()=>{u=null}),u)}let g=setInterval(()=>{h().catch(e=>{P7.error({err:e},`[persistence-staleness] sweep failed`)})},n);return g.unref?.(),{sweep:h,dispose:()=>(l=!0,clearInterval(g),u??Promise.resolve())}}async function Rke(e){try{let t=Ns({baseDir:e,timeout:{block:3e3}});return{name:(await t.raw(`config`,`--get`,`user.name`)).trim()||null,email:(await t.raw(`config`,`--get`,`user.email`)).trim()||null}}catch{return{name:null,email:null}}}async function I7(e){let t=dO(e),n=z(t,`principal.json`),{name:r,email:i}=await Rke(e);if(B(n)){let e;try{e=JSON.parse(V(n,`utf-8`))}catch{e={}}let t=typeof e.id==`string`&&e.id.startsWith(`principal-`)?e.id:`principal-${wu()}`,a=typeof e.created_at==`string`?e.created_at:new Date().toISOString(),o=t.slice(10,18),s={id:t,display_name:r?th(r):typeof e.display_name==`string`?e.display_name:`Local User`,display_email:i?th(i):typeof e.display_email==`string`?e.display_email:`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:a};return cu(n,JSON.stringify(s,null,2),`utf-8`),s}Xl(t,{recursive:!0});let a=`principal-${wu()}`,o=a.slice(10,18),s={id:a,display_name:r?th(r):`Local User`,display_email:i?th(i):`principal-${o}@openknowledge.local`,source:r||i?`git-config`:`synthesized`,created_at:new Date().toISOString()};return cu(n,JSON.stringify(s,null,2),`utf-8`),s}var zke=class{map=new Map;capacity;onEviction;onSizeChange;onMutate;now;constructor(e=1e4,t={}){this.capacity=Math.max(0,Math.floor(e)),this.onEviction=t.onEviction,this.onSizeChange=t.onSizeChange,this.onMutate=t.onMutate,this.now=t.now??Date.now}setRenamed(e,t){this.put(e,{kind:`renamed`,newDocName:t,addedAt:this.now()})}setDeleted(e){this.put(e,{kind:`deleted`,addedAt:this.now()})}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}has(e){return this.map.has(e)}peek(e){return this.map.get(e)}delete(e){this.map.delete(e)&&(this.onSizeChange?.(this.map.size),this.onMutate?.())}get size(){return this.map.size}entries(){return[...this.map.entries()]}restore(e,t){this.put(e,t)}put(e,t){if(this.capacity===0){this.onSizeChange?.(0);return}for(this.map.delete(e),this.map.set(e,t);this.map.size>this.capacity;){let e=this.map.keys().next().value;if(e===void 0)break;this.map.delete(e),this.onEviction?.()}this.onSizeChange?.(this.map.size),this.onMutate?.()}};const Bke=F(`recovered-file-target`);function Vke({watcher:e,contentDir:t,relativePath:n,exists:r,invalidateReferencedAssetsCache:i}){let a=L(t,n);if(!r){e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n}),i?.();return}try{let t=H(a),r=ou(t);e.mutateFileIndex({kind:`file-create`,path:t,relativePath:n,size:r.size,modifiedTs:r.mtimeMs,inode:r.ino})}catch(t){let r=t instanceof Error&&`code`in t&&typeof t.code==`string`?t.code:`UNKNOWN`;r!==`ENOENT`&&Bke.warn({code:r},`recovered file metadata unavailable; treating local target as deleted`),e.mutateFileIndex({kind:`file-delete`,path:a,relativePath:n})}i?.()}function L7(e,t){let n=e.resolveFilePath(t);return n!==null&&e.fileExists(n)}async function Hke(e,t){try{if(nS(e))return;let n=t.recentlyRemovedDocs.get(e);if(n===void 0)return;if(n.kind===`deleted`){if(L7(t,e)){t.recentlyRemovedDocs.delete(e);return}throw rx(),Wo({"auth.reason":`doc-deleted`}),new wQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`)}let r=new Set([e]),i=n.newDocName;for(;;){if(r.has(i)){use(),console.warn(JSON.stringify({event:`removal-redirect-chain-cycle`,documentName:e,target:i}));return}r.add(i);let n=t.recentlyRemovedDocs.get(i);if(n===void 0)throw nx(),Wo({"auth.reason":`rename-redirect`}),new wQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i);if(n.kind===`deleted`)throw L7(t,i)?(t.recentlyRemovedDocs.delete(i),nx(),Wo({"auth.reason":`rename-redirect`}),new wQ(`rename-redirect`,`removed-doc redirect for ${e} → ${i}`,i)):(rx(),Wo({"auth.reason":`doc-deleted`}),new wQ(`doc-deleted`,`removed-doc rejection for deleted ${e}`));i=n.newDocName}}catch(t){if(t instanceof wQ)throw t;lse(),console.warn(JSON.stringify({event:`removal-redirect-extension-error`,documentName:e,message:t instanceof Error?t.message:String(t)}))}}const R7=F(`removed-docs-journal`);function z7(e){return L(dO(e),`removed-docs.json`)}function Uke(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.docName!=`string`||t.docName.length===0||typeof t.addedAt!=`number`?!1:t.kind===`deleted`?!0:t.kind===`renamed`?typeof t.newDocName==`string`:!1}function Wke(e){let t=z7(e);if(!B(t))return[];try{let e=JSON.parse(V(t,`utf-8`));if(e.version!==1||!Array.isArray(e.entries))return R7.warn({path:t},`[removed-docs-journal] unrecognized journal shape — ignoring`),[];let n=[];for(let t of e.entries){if(!Uke(t))continue;let{docName:e,...r}=t;n.push([e,r])}return n}catch(e){return R7.warn({path:t,err:e},`[removed-docs-journal] failed to read journal — ignoring`),[]}}function B7(e,t){let n=z7(e),r={version:1,entries:t.map(([e,t])=>({docName:e,...t}))};ls(I(n),{recursive:!0});let i=`${n}.tmp`;vs(i,JSON.stringify(r),`utf-8`),ns(i,n)}const V7=F(`server-observers`);function H7(e){let t=new Map,n=new Map;return{async afterLoadDocument({documentName:r,document:i}){if(Zx(r)||Qx(r)||eS(r)||tS(r)||t.has(r))return;let a=i,o=a.getXmlFragment(`default`),s=a.getText(`source`),c=()=>{try{let n=pw({doc:a,xmlFragment:o,ytext:s,mdManager:e.mdManager,schema:e.schema,docName:r,shadow:e.shadowRef?()=>e.shadowRef?.current:void 0,getBranch:e.getCurrentBranch?()=>e.getCurrentBranch?.()??`main`:void 0,contentRoot:e.contentRoot,resolveEmbed:e.resolveEmbed,resolveSize:e.resolveSize,deferGuardEnabled:e.deferGuardEnabled,lossDetectorEnabled:e.lossDetectorEnabled,fixedPointBackstopEnabled:e.fixedPointBackstopEnabled,preDrainEnabled:e.preDrainEnabled,lossRing:e.lossRing});return t.set(r,n),!0}catch(e){return V7.error({docName:r,err:e},`[ServerObserverExtension] Failed to attach observers for '${r}'`),$b(`a`),$b(`b`),!1}};if(!c()){let e=setTimeout(()=>{n.delete(r),!t.has(r)&&(V7.warn({docName:r},`[ServerObserverExtension] Retrying observer attachment for '${r}'`),c())},5e3);n.set(r,e)}},async afterUnloadDocument({documentName:e}){let r=n.get(e);r&&(clearTimeout(r),n.delete(e));let i=t.get(e);i&&(i(),t.delete(e))},async onDestroy(){for(let e of n.values())clearTimeout(e);n.clear();for(let[e,n]of t.entries())try{n()}catch(t){V7.error({docName:e,err:t},`[ServerObserverExtension] Cleanup failed for '${e}'`)}t.clear()}}}const U7=`state.json`;function W7(e){return e.lockDir,B(e.shadowRepoDir)?`adopt`:`fresh`}function G7(e){return z(e,U7)}function Gke(e,t){return e===t||e===0&&t===1}var K7=class extends Error{kind;path;constructor(e){super(e.message),this.name=`StateManifestError`,this.kind=e.kind,this.path=e.path}};function Kke(e){if(!e||typeof e!=`object`)return!1;let t=e;if(typeof t.stateSchemaVersion!=`number`||typeof t.createdAt!=`string`||!t.createdBy||typeof t.createdBy!=`object`)return!1;let n=t.createdBy;return!(typeof n.runtimeVersion!=`string`||n.protocolVersion!==void 0&&typeof n.protocolVersion!=`number`)}function q7(e){let t=G7(e);if(!B(t))return{status:`absent`};let n;try{n=V(t,`utf-8`)}catch(e){throw new K7({kind:`corrupt`,path:t,message:`Failed to read state manifest at ${t}: ${e instanceof Error?e.message:String(e)}`})}let r;try{r=JSON.parse(n)}catch(e){throw new K7({kind:`corrupt`,path:t,message:`State manifest at ${t} is not valid JSON: ${e instanceof Error?e.message:String(e)}`})}if(!Kke(r))throw new K7({kind:`corrupt`,path:t,message:`State manifest at ${t} has invalid shape (missing or wrong-typed required fields)`});return{status:`present`,manifest:r}}function J7(e,t){let n=G7(e);Xl(I(n),{recursive:!0}),cu(n,JSON.stringify(t,null,2),{encoding:`utf-8`,mode:384})}function Y7(e){let t=F(`state-manifest`),n=e.currentStateSchemaVersion??1,r=e.currentRuntimeVersion??Vs,i=e.currentProtocolVersion??1,a=(e.now??(()=>new Date))().toISOString(),o=G7(e.lockDir),s=q7(e.lockDir);if(s.status===`present`){let c=s.manifest;if(!Gke(c.stateSchemaVersion,n))throw new K7({kind:`incompatible`,path:o,message:`State manifest at ${o} declares stateSchemaVersion=${c.stateSchemaVersion} but this binary supports ${n}. Refusing to boot — on-the-fly migration is out of scope. (Manifest written by runtime ${c.createdBy.runtimeVersion}, protocol ${c.createdBy.protocolVersion}.)`});try{let t={...c,lastWriteBy:{runtimeVersion:r,protocolVersion:i,at:a}};return J7(e.lockDir,t),t}catch(e){return t.warn({err:e},`[state-manifest] failed to update lastWriteBy — proceeding`),c}}if(W7({lockDir:e.lockDir,shadowRepoDir:e.shadowRepoDir})===`fresh`){let s={stateSchemaVersion:n,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i}};return J7(e.lockDir,s),t.info({path:o,stateSchemaVersion:n},`[state-manifest] fresh project — wrote manifest`),s}let c={stateSchemaVersion:0,createdAt:a,createdBy:{runtimeVersion:r,protocolVersion:i,adoptedAt:a}};return J7(e.lockDir,c),t.warn({path:o,runtimeVersion:r},`[state-manifest] adopting pre-versioned project — wrote schema-0 manifest. Future binaries with STATE_SCHEMA_VERSION>=2 may refuse if they cannot read schema-0 state.`),c}function qke(e,t){return e===`auth`&&t===`403`?`auth-403`:e===`auth`&&t===`401`?`auth-401`:e===`auth`&&t===`scope-mismatch`?`auth-scope-mismatch`:e===`auth`&&t===`no-credential`?`auth-no-credential`:e===`semantic`&&t===`protected-branch`?`semantic-protected-branch`:null}function Jke(e){return e.git?.toString()??e.message??``}function X7(e,t){return t.some(t=>t.test(e))}const Yke={"no-credential":`No GitHub credential available — reconnect to resume syncing`,401:`Authentication failed — token may be expired`,403:`Access denied (403)`,"scope-mismatch":`GitHub token missing required scopes`,"ssh-auth":`SSH authentication failed — check your SSH key or host-key trust`,"unknown-auth":`Authentication failed`},Xke=[/non-fast-forward/i,/rejected.*non-fast-forward/i,/would overwrite.*commits/i,/\[rejected\]/,/fetch first/i,/updates were rejected/i],Z7=[/protected branch/i,/refusing to allow/i,/at least \d+ approving review/i,/required status check/i,/branch policy/i,/GH001/i,/GH002/i,/GH003/i,/GH004/i,/push declined due to repository rule/i,/cannot push to a protected branch/i],Zke=[/\bmerge conflict\b/i,/automatic merge failed/i,/CONFLICT \(/,/\bconflict\b.*\bmerge\b/i,/(?:^|\n)CONFLICTS:\s/i],Qke=[/lfs.*quota/i,/exceeded.*bandwidth/i,/lfs storage/i],$ke=[/file.*too large/i,/exceeded.*file size/i,/push file size limit/i],eAe=[/pre-receive hook/i,/remote:.*rejected/i,/hook declined/i],tAe=[/secret.*detected/i,/push.*secret/i,/secret scanning/i,/leaking.*credentials/i,/token.*detected/i],nAe=[/\.git\/index\.lock/i,/another git process/i,/unable to create.*\.lock/i],rAe=[/dirty.*working tree/i,/working tree.*not clean/i,/untracked.*files.*would be overwritten/i,/local changes.*would be overwritten/i,/uncommitted changes/i,/changes.*not staged/i,/please.*commit.*changes/i,/please.*stash/i,/commit your changes or stash/i],iAe=[/no space left on device/i,/disk quota exceeded/i,/ENOSPC/i],aAe=[/could not resolve host/i,/name.*resolution/i,/connection.*timed out/i,/operation timed out/i,/connection refused/i,/network.*unreachable/i,/ssl.*handshake/i,/unable to connect/i,/getaddrinfo/i,/econnrefused/i,/enotfound/i,/etimedout/i,/ehostunreach/i],oAe=[/\bHTTP[\s/]*5[0-9]{2}\b/i,/\bstatus:?\s*5[0-9]{2}\b/i,/\berror\s*5[0-9]{2}\b/i,/\bresponse.*?\b5[0-9]{2}\b/i],sAe=[/\bHTTP[\s/]*429\b/i,/\bstatus:?\s*429\b/i,/\berror\s*429\b/i,/rate.?limit/i,/too many requests/i];function Q7(e){let t=cAe(e);return{...t,userFacingCode:qke(t.class,t.subclass)}}function cAe(e){let t=e instanceof Error?e:Error(String(e)),n=Jke(t),r=`${t.message}\n${n}`.toLowerCase();if(X7(r,nAe))return{class:`local`,subclass:`index-lock`,retryable:!0,message:`Git index locked by another process`,rawStderr:n};if(X7(r,rAe))return{class:`local`,subclass:`dirty-tree`,retryable:!0,message:`Working tree has uncommitted changes`,rawStderr:n};if(X7(r,iAe))return{class:`local`,subclass:`disk-full`,retryable:!0,message:`Disk full or quota exceeded`,rawStderr:n};let i=lt(t);return i.kind===`auth`?i.subclass===`403`&&X7(r,Z7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:{class:`auth`,subclass:i.subclass,retryable:!1,message:Yke[i.subclass],rawStderr:n}:X7(r,Z7)?{class:`semantic`,subclass:`protected-branch`,retryable:!1,message:`Push rejected — branch is protected`,rawStderr:n}:X7(r,Xke)?{class:`semantic`,subclass:`non-fast-forward`,retryable:!1,message:`Push rejected — remote has diverged (non-fast-forward)`,rawStderr:n}:X7(r,Zke)?{class:`semantic`,subclass:`merge-conflict`,retryable:!1,message:`Merge conflict — manual resolution required`,rawStderr:n}:X7(r,Qke)?{class:`structural`,subclass:`lfs-quota`,retryable:!1,message:`Git LFS quota exceeded`,rawStderr:n}:X7(r,$ke)?{class:`structural`,subclass:`large-file`,retryable:!1,message:`File exceeds size limit`,rawStderr:n}:X7(r,tAe)?{class:`structural`,subclass:`secret-detected`,retryable:!1,message:`Push blocked — secret or credential detected in content`,rawStderr:n}:X7(r,eAe)?{class:`structural`,subclass:`pre-receive-hook`,retryable:!1,message:`Push rejected by server pre-receive hook`,rawStderr:n}:X7(r,sAe)?{class:`network`,subclass:`429`,retryable:!0,message:`Rate limited — too many requests`,rawStderr:n}:X7(r,oAe)?{class:`network`,subclass:`5xx`,retryable:!0,message:`Server error (5xx)`,rawStderr:n}:X7(r,aAe)?/timed? out/i.test(r)?{class:`network`,subclass:`timeout`,retryable:!0,message:`Connection timed out`,rawStderr:n}:/refused/i.test(r)||/econnrefused/i.test(r)?{class:`network`,subclass:`connection-refused`,retryable:!0,message:`Connection refused`,rawStderr:n}:/resolve.*host/i.test(r)||/enotfound/i.test(r)||/getaddrinfo/i.test(r)?{class:`network`,subclass:`dns`,retryable:!0,message:`DNS resolution failed`,rawStderr:n}:{class:`network`,subclass:`unknown-network`,retryable:!0,message:`Network error`,rawStderr:n}:{class:`local`,subclass:`unknown-local`,retryable:!0,message:t.message||`Unknown git error`,rawStderr:n}}function lAe(e,t={}){let n=t.ttlMs??6e4,r=t.now??Date.now,i=new Map;return{get(t){if(!e)return null;let a=r(),o=i.get(t);if(o&&o.expiresAt>a)return o.token==null?null:{token:o.token,host:t};let s=e(t),c=s.available&&s.token?s.token:null;return i.set(t,{token:c,expiresAt:a+n}),c==null?null:{token:c,host:t}},invalidate(){i.clear()}}}const $7=F(`github-permissions`);function uAe(e){return e===`github.com`?`https://api.github.com`:`https://${e}/api/v3`}function dAe(e){let t={"User-Agent":`open-knowledge-server`,Accept:`application/vnd.github+json`};return e&&(t.Authorization=`Bearer ${e}`),t}function fAe(e){if(typeof e!=`object`||!e)return null;let t=e.permissions;if(typeof t!=`object`||!t)return null;let n=t.push;return typeof n==`boolean`?n:null}async function pAe(e,t){switch(e.status){case 200:{let t;try{t=await e.json()}catch(e){return $7.warn({err:e},`[permissions] probe got 200 with unparseable JSON body`),{kind:`unknown`,error:`malformed-response`}}let n=fAe(t);return n===null?($7.warn({bodyKeys:typeof t==`object`&&t?Object.keys(t):[]},`[permissions] probe got 200 without permissions.push field`),{kind:`unknown`,error:`malformed-response`}):n?{kind:`allowed`}:{kind:`denied`,reason:`no-collaborator`}}case 401:return{kind:`unknown`,error:`token-invalid`};case 403:return e.headers.get(`x-ratelimit-remaining`)===`0`?{kind:`unknown`,error:`rate-limit`}:{kind:`unknown`,error:`token-invalid`};case 429:return{kind:`unknown`,error:`rate-limit`};case 404:return t?{kind:`denied`,reason:`private-no-access`}:{kind:`denied`,reason:`repo-not-found`};default:return $7.warn({httpStatus:e.status},`[permissions] probe got unexpected HTTP status`),{kind:`unknown`,error:`malformed-response`}}}async function mAe(e,t,n){let r=t(e);if(r.available&&r.token)return{token:r.token,source:`gh`};if(n)try{let t=await n.get(e);if(t?.token)return{token:t.token,source:`token-store`}}catch(t){$7.warn({err:t,host:e},`[permissions] tokenStore.get threw; falling through to anonymous`)}return{token:void 0,source:`anonymous`}}async function hAe(e){let{owner:t,repo:n,host:r=`github.com`,transport:i=`https`,detectGh:a=()=>({available:!1}),tokenStore:o,_fetchFn:s=fetch,_timeoutMs:c=5e3}=e,{token:l,source:u}=await mAe(r,a,o);if(u===`anonymous`)return i===`ssh`||i===`git`?($7.info({host:r,transport:i},`[permissions] no credential resolved for ssh/git origin — abstaining (push auths with SSH keys, not tokens)`),{kind:`unknown`,error:`ssh-unverified`}):($7.info({host:r},`[permissions] no credential resolved — denying push (read-only)`),{kind:`denied`,reason:`not-authenticated`});let d=`${uAe(r)}/repos/${encodeURIComponent(t)}/${encodeURIComponent(n)}`;$7.info({host:r,tokenSource:u,tokenLen:l===void 0?0:l.length},`[permissions] probe starting`);let f=new AbortController,p=setTimeout(()=>f.abort(),c);try{let e=await s(d,{signal:f.signal,headers:dAe(l)}),t=await pAe(e,l!==void 0);return $7.info({host:r,tokenSource:u,httpStatus:e.status,kind:t.kind,reason:t.kind===`denied`?t.reason:void 0,error:t.kind===`unknown`?t.error:void 0},`[permissions] probe classified`),t}catch(e){return f.signal.aborted?($7.warn({host:r,timeoutMs:c},`[permissions] probe timed out`),{kind:`unknown`,error:`timeout`}):($7.warn({err:e,host:r},`[permissions] probe failed`),{kind:`unknown`,error:`network`})}finally{clearTimeout(p)}}async function gAe(e){let t=performance.now(),n=await hAe(e);return bAe(n,performance.now()-t),n}function _Ae(e){return{outcome:e.kind,denied_reason:e.kind===`denied`?e.reason:`none`,error_class:e.kind===`unknown`?e.error:`none`}}let e9=null;function vAe(){return e9||=xs().createCounter(`ok.permissions.probe.outcome_total`,{description:`Push-permission probe outcomes. Bounded labels: outcome ∈ {allowed,denied,unknown}; denied_reason ∈ {no-collaborator,private-no-access,repo-not-found,not-authenticated,none}; error_class ∈ {network,timeout,rate-limit,token-invalid,malformed-response,ssh-unverified,none}.`}),e9}let t9=null;function yAe(){return t9||=xs().createHistogram(`ok.permissions.probe.duration_ms`,{description:`Push-permission probe wall-clock duration.`,unit:`ms`}),t9}function bAe(e,t){let n=_Ae(e);vAe().add(1,n),yAe().record(t,{outcome:n.outcome})}function n9(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 xAe(e,t){return t===`anonymous`?Math.max(180,e):e}const r9=F(`sync-engine`),i9=/^[0-9a-f]{40}$/i,SAe=Au(Al);function CAe(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 wAe(e){return e.kind===`allowed`?{checkStatus:`allowed`}:e.kind===`denied`?{checkStatus:`denied`,deniedReason:e.reason}:{checkStatus:`unknown`,unknownError:e.error}}function a9(e,t){return e===t?!0:e===null||t===null||e.checkStatus!==t.checkStatus?!1:e.checkStatus===`denied`&&t.checkStatus===`denied`?e.deniedReason===t.deniedReason:e.checkStatus===`unknown`&&t.checkStatus===`unknown`?e.unknownError===t.unknownError:!0}function o9(e){let t=e*1e3,n=t*.15*(2*Math.random()-1);return Math.round(t+n)}function s9(e){let t=Pu(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 TAe(e){return e>=8?3600*1e3:e>=5?900*1e3:e>=3?300*1e3:0}const c9=12e4;var EAe=class{state=`dormant`;projectDir;contentDir;contentFilter;contentRoot;pullIntervalSeconds;pushIntervalSeconds;mode;credentialArgs;cc1Broadcaster;onStateChange;onContentConflictsDetected;onContentConflictsResolved;setBatchInProgress;onAutoDisable;checkpointBeforeStrandedConversion;checkpointBeforeOverlayRestore;detectGh;ghTokenSource;tokenStore;checkPushPermissionFn;pushPermission=null;pushPermissionProbeInFlight=!1;authTier=`unknown`;pullTimer=null;pushTimer=null;stateSaveTimer=null;lastSyncUtc=null;lastFetchUtc=null;lastPushedSha=null;lastPullUtc=null;lastPullOutcome=null;consecutiveFailures=0;ahead=0;behind=0;conflictCount=0;pushError;pushErrorCode;pullError;pullErrorCode;pausedReason;currentBranch=`main`;pullInFlight=!1;pushInFlight=!1;hasRemote=!1;identityUnresolved=!1;statePath;conflictStore;constructor(e){this.projectDir=e.projectDir,this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.contentRoot=e.contentRoot??``,this.pullIntervalSeconds=e.pullIntervalSeconds??30,this.pushIntervalSeconds=e.pushIntervalSeconds??60,this.mode=e.mode??(e.syncEnabled===!0?`full`:`off`),this.credentialArgs=e.credentialArgs??[],this.cc1Broadcaster=e.cc1Broadcaster??null,this.onStateChange=e.onStateChange,this.onContentConflictsDetected=e.onContentConflictsDetected,this.onContentConflictsResolved=e.onContentConflictsResolved,this.setBatchInProgress=e.setBatchInProgress,this.onAutoDisable=e.onAutoDisable,this.checkpointBeforeStrandedConversion=e.checkpointBeforeStrandedConversion,this.checkpointBeforeOverlayRestore=e.checkpointBeforeOverlayRestore,this.detectGh=e.detectGh,this.ghTokenSource=lAe(e.detectGh),this.tokenStore=e.tokenStore,this.checkPushPermissionFn=e.checkPushPermissionFn??gAe,this.statePath=z(dO(this.projectDir),`sync-state.json`),this.conflictStore=new OQ(this.projectDir,this.currentBranch)}syncGhTokenHost(){return GF(this.projectDir)}gitHandle(e){return Is(this.projectDir,{credentialArgs:this.credentialArgs,gitIndexFile:e,ghToken:this.ghTokenSource.get(this.syncGhTokenHost())??void 0,timeoutMs:12e4})}async start(){if(this.state!==`dormant`)return;this.loadState();let e=!1;try{let t=this.gitHandle();e=(await t.git.raw(`remote`,`-v`)).trim().length>0,this.hasRemote=e;try{let e=(await t.git.raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();e&&e!==`HEAD`&&(this.currentBranch=e,this.conflictStore.setBranch(e))}catch{}}catch(e){r9.warn({err:e},`[sync] remote detection failed`)}if(e&&this.probePushPermissionInternal(`start`),this.mode===`off`){e&&this.transitionTo(`disabled`),r9.info({hasRemote:e,mode:this.mode},`[sync] sync not enabled — staying inactive`);return}if(!e){r9.info({},`[sync] no remote detected — staying dormant`);return}this.transitionTo(`idle`);let t=Ku(this.projectDir),n=t?L(t,`MERGE_HEAD`):null,r=n!==null&&B(n);this.conflictCount=this.conflictStore.count();let i=()=>this.conflictStore.list().filter(e=>e.variant!==`working-tree`);if(i().length>0&&!r){r9.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 Wb(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&&r9.info({cleared:n-this.conflictCount,remaining:this.conflictCount},`[sync] reconciled conflicts.json against git unmerged index`)}catch(e){r9.warn({err:e},`[sync] failed to reconcile conflicts with git index`)}if(r&&i().length===0){r9.warn({},`[sync] stale MERGE_HEAD detected with no tracked conflicts — aborting merge`);try{await this.gitHandle().git.raw([`merge`,`--abort`])}catch(e){r9.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`),r9.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=n9(this.lastFetchUtc,this.currentPullIntervalSeconds()),s=n9(this.lastSyncUtc,this.pushIntervalSeconds);this.schedulePull(o>0?o:void 0),this.schedulePush(s>0?s:void 0),r9.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,r9.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){r9.warn({pullInFlight:this.pullInFlight,pushInFlight:this.pushInFlight},`[sync] drain: timed out waiting for in-flight cycle`);break}await ku(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){r9.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){r9.warn({err:e},`[sync] pull-only: stranded-commit checkpoint failed — proceeding`)}try{let n=(await e.git.raw([`merge-base`,`HEAD`,`origin/${this.currentBranch}`])).trim();this.setBatchInProgress?.(!0);try{await Ps(()=>e.git.raw([`reset`,`--mixed`,n]))}finally{this.setBatchInProgress?.(!1)}let r=await e.git.status();this.ahead=r.ahead,this.behind=r.behind,this.pausedReason=void 0,r9.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`,r9.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`?r9.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}`):r9.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 r9.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?fpe(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 NB(this.projectDir)===null;this.identityUnresolved!==e&&(this.identityUnresolved=e,this.cc1Broadcaster?.signal(`sync-status`))}async probePushPermissionInternal(e){if(!this.hasRemote||this.pushPermissionProbeInFlight)return null;let t=WF(this.projectDir);if(t.kind!==`ok`){let e={checkStatus:`unknown`},t=this.pushPermission;return this.pushPermission=e,a9(t,e)||this.cc1Broadcaster?.signal(`sync-status`),e}this.pushPermissionProbeInFlight=!0,r9.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){r9.warn({err:t,caller:e},`[sync] push-permission probe threw — recording unknown/network`),n={kind:`unknown`,error:`network`}}finally{this.pushPermissionProbeInFlight=!1}let r=wAe(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,r9.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,r9.info({caller:e,priorState:this.state},`[sync] push permission restored`)),!a&&!a9(i,r)&&this.cc1Broadcaster?.signal(`sync-status`),r}async refreshRemote(){this.hasRemote||await this.probeRemote()&&(this.hasRemote=!0,r9.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(!B(L(this.projectDir,`.git`)))return!1;try{return(await this.gitHandle().git.raw(`remote`,`-v`)).trim().length>0}catch(e){return r9.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=Ku(this.projectDir),r=n?L(n,`MERGE_HEAD`):null;if(r!==null&&B(r))try{let n=this.gitHandle(),r=new Set(await Wb(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&&r9.info({cleared:t-this.conflictCount,remaining:this.conflictCount},`[sync] external resolve detected (mid-merge) — pruned resolved entries`)}catch(e){r9.warn({err:e},`[sync] reconcileConflictsFromGit: git probe failed`);return}else{r9.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&&(r9.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=>{r9.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=>{r9.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){r9.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`?xAe(this.pullIntervalSeconds,this.authTier===`anonymous`?`anonymous`:`authenticated`):this.pullIntervalSeconds}effectivePullDelayMs(){let e=TAe(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`,r9.warn({},`[sync] detached HEAD — pausing sync`),`refused`;t=n,this.currentBranch=t}catch(e){return this.handleError(Q7(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=Q7(e instanceof Error?e:Error(String(e)));return this.handleError(t,`pull`),`error`}try{let t=await e.git.status();this.ahead=t.ahead,this.behind=t.behind}catch{}if(this.behind>0&&this.mode!==`full`){let n=await this.doPullCycleB1(e,t);return this.scheduleSaveState(),n}if(this.behind>0&&this.conflictCount===0){this.transitionTo(`pulling`),this.setBatchInProgress?.(!0);try{await this.commitDirtyContentFilesToHead(e);let n=await this.prepareForMerge(e,t);if(!n.proceed)return`refused`;try{await e.git.merge([`origin/${t}`]),this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`)}finally{n.needsStashPop&&await this.popPreMergeStash(e)}return this.scheduleSaveState(),`succeeded`}catch(e){let t=Q7(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`),r9.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 Wb(e.git,[`diff-index`,`--name-only`,`HEAD`]),a=new Set(await Wb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]));r=i.filter(e=>a.has(e))}catch(e){return this.handleError(Q7(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(Q7(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){r9.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 r9.warn({err:e},`[sync] pull-only: failed to restore overlay before fast-forward — skipping cycle`),this.handleError(Q7(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 r9.error({err:e,refusal:n.refusal},`[sync] pull-only: failed to restore overlay after fast-forward refusal`),this.handleError(Q7(e instanceof Error?e:Error(String(e))),`pull`),`error`}return n.timedOut?(r9.warn({},`[sync] pull-only: fast-forward timed out — backing off`),this.handleError(Q7(Error(`git merge --ff-only timed out after ${c9}ms`)),`pull`),`error`):(n.refusal===`divergence`&&(this.pausedReason=`diverged-local-commits`),this.transitionTo(`idle`),r9.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 r9.error({err:e},`[sync] pull-only: failed to apply overlay after fast-forward`),this.handleError(Q7(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 r9.error({},`[sync] pull-only: failed to persist conflict state after fast-forward — surfacing as error`),this.handleError(Q7(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 r9.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 SAe(`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:CAe({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(!B(L(this.projectDir,p))){try{await e.git.revparse([`origin/${t}:${p}`])}catch(e){if(this.classifyRefReadFailure(e)===`error`){s.push(p),r9.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=V(L(this.projectDir,p))}catch{continue}o.push({path:p,bytes:h});let g=h.toString(`utf-8`),_=null;try{_=await e.git.raw([`show`,`origin/${t}:${p}`])}catch(e){this.classifyRefReadFailure(e)===`error`&&r9.warn({err:e,path:p},`[sync] pull-only: unexpected error reading origin blob — keeping overlay, deferring reconcile`),_=null}if(_!==null&&_===g){m&&l.push(p);continue}if(_===null||!this.isContentConflictPath(p)){a.push({path:p,bytes:h});continue}let v=m?r.baseSha:await this.gitBlobSha(e,`${n}:${p}`),y=ui(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){r9.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=L(this.projectDir,t);CL(e,this.projectDir),vs(e,n)}for(let e of t){let t=L(this.projectDir,e);CL(t,this.projectDir);try{is(t)}catch(e){if(e.code!==`ENOENT`)throw e}}}isContentConflictPath(e){let t=L(this.projectDir,e),n=oN(R(this.contentDir,t));return!n.startsWith(`..`)&&zx(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 Wb(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=this.gatherContentFilesSync(),n=L(pu(),`ok-sync-idx-${process.pid}-${Date.now()}.idx`),r=null;this.transitionTo(`pushing`);try{await Ps(async()=>{let e=this.gitHandle(n);if(s9(this.projectDir)){r9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}let i;try{i=(await e.git.revparse(`HEAD`)).trim()}catch(e){let t=e instanceof Error?e.message:String(e),n=`${t}\n${e.git?.toString()??t}`;if(/unknown revision or path not in the working tree/i.test(n)||/ambiguous argument 'HEAD'/i.test(n)||/does not have any commits yet/i.test(n)){r9.info({},`[sync] repo has no commits yet — skipping push cycle`),this.transitionTo(`idle`);return}this.handleError(Q7(e instanceof Error?e:Error(String(e))),`push`);return}await e.git.raw([`read-tree`,i]);let a=await this.listHeadContentPaths(e,i),o=await this.stageContentFiles(e,t),s=new Set(o.map(e=>e.projectRelPath)),c=[...a].filter(e=>!s.has(e));await this.removePathsFromIndex(e,c);let l=(await e.git.raw([`write-tree`])).trim(),u=``;try{u=(await e.git.raw([`rev-parse`,`${i}^{tree}`])).trim()}catch{}if(u&&u===l){let n=null;try{n=(await e.git.raw([`rev-parse`,`origin/${this.currentBranch}`])).trim()}catch{}if(n===i){r9.info({contentFileCount:t.length,headSha:i},`[sync] push cycle: nothing to commit (tree unchanged, origin matches HEAD)`),this.lastPushedSha=i,this.lastSyncUtc=new Date().toISOString(),this.clearPushError(),this.transitionTo(`idle`);return}r9.info({headSha:i,upstreamSha:n},`[sync] push cycle: tree unchanged but local ahead of origin — pushing existing commits`);let a=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),a=!0}catch{}a?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=i;return}let d=[],f=[];try{let n=await Wb(e.git,[`diff-tree`,`--name-only`,`-r`,i,l]);if(n.length>0){let e=new Map(t.map(e=>[e.projectRelPath,e.contentRelPath]));for(let t of n){d.push(t);let n=e.get(t)??oN(R(this.contentDir,L(this.projectDir,t)));n&&!n.startsWith(`..`)&&f.push(n)}}}catch{d=t.map(e=>e.projectRelPath).concat(c),f=t.map(e=>e.contentRelPath)}let p=this.buildCommitMessage(f),m=await NB(this.projectDir),h=m===null;this.identityUnresolved!==h&&(this.identityUnresolved=h,this.cc1Broadcaster?.signal(`sync-status`));let g=m?.name??`OpenKnowledge`,_=m?.email??`sync@open-knowledge.local`;Rs(e,{GIT_AUTHOR_NAME:g,GIT_AUTHOR_EMAIL:_,GIT_COMMITTER_NAME:g,GIT_COMMITTER_EMAIL:_});let v=(await e.git.raw([`commit-tree`,l,`-p`,i,`-m`,p])).trim();if(!v||!i9.test(v)){r9.warn({raw:v},`[sync] commit-tree returned invalid SHA — aborting push`),this.transitionTo(`idle`);return}await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,v,i]),await this.resetRealIndexForPaths(d);let y=!1;try{await e.git.raw([`rev-parse`,`--abbrev-ref`,`${this.currentBranch}@{u}`]),y=!0}catch{}y?await e.git.raw([`push`,`origin`,this.currentBranch]):await e.git.raw([`push`,`--set-upstream`,`origin`,this.currentBranch]),r=v}),r&&(this.lastPushedSha=r,this.lastSyncUtc=new Date().toISOString(),this.ahead=0,this.clearPushError(),this.state===`pushing`&&this.transitionTo(`idle`),this.pausedReason===`dirty-tree`&&(this.pausedReason=void 0,this.clearPullError(),this.schedulePull(0)))}catch(t){let n=Q7(t instanceof Error?t:Error(String(t)));if(n.class===`semantic`&&n.subclass===`non-fast-forward`){if(e>0){r9.info({},`[sync] push rejected (non-fast-forward) — fetching, merging, retrying`);let e=this.gitHandle();this.setBatchInProgress?.(!0);try{await e.git.fetch(`origin`),await this.commitDirtyContentFilesToHead(e);let t=await this.prepareForMerge(e,this.currentBranch);if(!t.proceed){this.setBatchInProgress?.(!1);return}try{await e.git.merge([`origin/${this.currentBranch}`])}finally{t.needsStashPop&&await this.popPreMergeStash(e)}}catch(e){let t=Q7(e instanceof Error?e:Error(String(e)));t.class===`semantic`&&t.subclass===`merge-conflict`?await this.handleMergeConflict():this.handleError(t,`pull`),this.scheduleSaveState();return}finally{this.setBatchInProgress?.(!1)}await this.doPushCycle(0);return}r9.info({},`[sync] push still rejected after retry — waiting for next pull cycle`),this.consecutiveFailures++,this.state===`pushing`&&this.transitionTo(`idle`)}else this.handleError(n,`push`)}finally{try{su(n)}catch{}}this.scheduleSaveState()}async commitDirtyContentFilesToHead(e){if((await e.git.status()).files.length===0)return null;let t=(await e.git.revparse(`HEAD`)).trim(),n=this.gatherContentFilesSync(),r=await this.listHeadContentPaths(e,t);if(n.length===0&&r.size===0)return null;let i=L(pu(),`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 Wb(a.git,[`diff-tree`,`--name-only`,`-r`,t,c])}catch{l=n.map(e=>e.projectRelPath).concat(s)}let u=await NB(this.projectDir),d=u?.name??`OpenKnowledge`,f=u?.email??`sync@open-knowledge.local`;Rs(a,{GIT_AUTHOR_NAME:d,GIT_AUTHOR_EMAIL:f,GIT_COMMITTER_NAME:d,GIT_COMMITTER_EMAIL:f});let p=(await a.git.raw([`commit-tree`,c,`-p`,t,`-m`,`Auto-save: interim before merge`])).trim();return!p||!i9.test(p)?(r9.warn({raw:p},`[sync] commit-tree returned invalid SHA in commitDirtyContentFilesToHead`),null):(await e.git.raw([`update-ref`,`refs/heads/${this.currentBranch}`,p,t]),await this.resetRealIndexForPaths(l,e),p)}finally{try{su(i)}catch{}}}async prepareForMerge(e,t){let n;try{n=await Wb(e.git,[`diff-index`,`--name-only`,`HEAD`])}catch(e){return r9.warn({err:e,branch:t},`[sync] diff-index failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}if(n.length===0)return{proceed:!0,needsStashPop:!1};let r;try{r=new Set(await Wb(e.git,[`diff`,`--name-only`,`HEAD..origin/${t}`]))}catch(e){return r9.warn({err:e,branch:t},`[sync] merge-path diff failed — allowing merge attempt`),{proceed:!0,needsStashPop:!1}}let i=n.filter(e=>r.has(e));if(i.length>0){let e=i.slice(0,3).join(`, `),t=i.length>3?`, +${i.length-3} more`:``;return this.pullErrorCode=void 0,this.pullError=`Sync paused — your local changes to ${e}${t} conflict with incoming changes. Commit, stash, or discard them before syncing.`,this.pausedReason=`external-changes-pending`,this.consecutiveFailures=0,this.transitionTo(`idle`),this.scheduleSaveState(),r9.warn({files:i},`[sync] paused — dirty paths overlap incoming merge`),{proceed:!1,needsStashPop:!1}}let a=`ok-sync: pre-merge stash @ ${new Date().toISOString()}`;try{await e.git.raw([`stash`,`push`,`-m`,a])}catch(e){return r9.warn({err:e},`[sync] stash push failed — proceeding without stash`),{proceed:!0,needsStashPop:!1}}return{proceed:!0,needsStashPop:!0}}async popPreMergeStash(e){try{await e.git.raw([`stash`,`pop`])}catch(e){r9.warn({err:e},`[sync] stash pop failed — stash remains on stack`)}}async stageContentFiles(e,t){if(t.length===0)return t;let n=new Set,r=!0;for(let i=0;i<t.length;i+=100){let a=t.slice(i,i+100).map(e=>e.projectRelPath);try{let t=await Wb(e.git,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`--`,...a]);for(let e of t)n.add(e)}catch(e){r=!1,r9.warn({err:e},`[sync] ignored-path probe failed — staging unfiltered without -f`)}}n.size>0&&r9.info({count:n.size,sample:[...n].slice(0,5)},`[sync] skipping gitignored untracked path(s) — in content scope but excluded from git`);let i=r?t.filter(e=>!n.has(e.projectRelPath)):t,a=e=>e.startsWith(`.ok/`)||e.includes(`/.ok/`),o=r?i.filter(e=>a(e.projectRelPath)):[],s=r?i.filter(e=>!a(e.projectRelPath)):i;for(let[t,n]of[[[`add`,`--`],s],[[`add`,`-f`,`--`],o]])for(let r=0;r<n.length;r+=100){let i=n.slice(r,r+100).map(e=>e.projectRelPath);await e.git.raw([...t,...i])}return i}gatherContentFilesSync(){let e=[],t=n=>{let r;try{r=tu(n,{withFileTypes:!0})}catch{return}for(let i of r){let r=L(n,i.name);if(i.isDirectory()){let e=oN(R(this.contentDir,r));if(!e.startsWith(`..`)&&this.contentFilter.isDirExcluded(e))continue;t(r)}else if(i.isFile()||i.isSymbolicLink()){let t=oN(R(this.contentDir,r));if(!t.startsWith(`..`)&&!this.contentFilter.isExcluded(t)){let n=oN(R(this.projectDir,r));e.push({contentRelPath:t,projectRelPath:n})}}}};return B(this.contentDir)&&t(this.contentDir),e}async listHeadContentPaths(e,t){let n=new Set;try{let r=await Wb(e.git,[`ls-tree`,`-r`,`--name-only`,t]);for(let e of r){let t=L(this.projectDir,e),r=oN(R(this.contentDir,t));!r.startsWith(`..`)&&!this.contentFilter.isExcluded(r)&&n.add(e)}}catch{}return n}async removePathsFromIndex(e,t){if(t.length===0)return;let n=[...new Set(t)];for(let t=0;t<n.length;t+=100){let r=n.slice(t,t+100);await e.git.raw([`rm`,`--cached`,`--`,...r])}}async resetRealIndexForPaths(e,t){if(e.length===0)return;let n=t??this.gitHandle(),r=[...new Set(e)];for(let e=0;e<r.length;e+=100){let t=r.slice(e,e+100);try{await n.git.raw([`reset`,`HEAD`,`--`,...t])}catch{}}}buildCommitMessage(e){return e.length===0?`Auto-save: changes saved`:e.length<=3?`Auto-save: Updated ${e.join(`, `)}`:`Auto-save: ${e.length} files changed`}async handleMergeConflict(){let e=this.gitHandle(),t=[];try{t=await Wb(e.git,[`diff`,`--name-only`,`--diff-filter=U`])}catch(t){r9.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){r9.warn({err:e},`[sync] git merge --abort failed during cleanup`)}this.pullErrorCode=void 0,this.pullError=`Failed to detect conflict files — merge aborted`,this.pausedReason=void 0,this.transitionTo(`idle`);return}let n=[],r=[];for(let e of t){let t=L(this.projectDir,e),i=oN(R(this.contentDir,t));!i.startsWith(`..`)&&zx(i)&&!this.contentFilter.isExcluded(i)?n.push(e):r.push(e)}let i=[];for(let t of r)try{await e.git.raw([`checkout`,`--theirs`,`--`,t]),await e.git.raw([`add`,`--`,t]),r9.info({file:t},`[sync] auto-resolved non-content conflict with theirs`)}catch(e){r9.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){r9.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(),r9.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`),r9.warn({files:n},`[sync] content conflicts — sync paused until resolved`)}else{let t=!1;try{await e.git.raw([`commit`,`--no-edit`]);let n=Ku(this.projectDir);t=n===null||!B(L(n,`MERGE_HEAD`))}catch(e){r9.warn({err:e},`[sync] failed to commit after auto-resolving conflicts`)}if(t)this.lastSyncUtc=new Date().toISOString(),this.behind=0,this.transitionTo(`idle`),r9.info({},`[sync] all conflicts auto-resolved — merge committed`);else{try{await e.git.raw([`merge`,`--abort`])}catch(e){r9.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`),r9.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){r9.warn({err:t,files:e},`[sync] content conflict callback failed`)}}async notifyContentConflictsResolved(e){if(e.length!==0)try{await this.onContentConflictsResolved?.(e)}catch(t){r9.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),r9.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,r9.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)};cu(this.statePath,JSON.stringify(t,null,2),`utf-8`)}catch(e){r9.warn({err:e},`[sync] failed to persist sync state`)}}loadState(){if(B(this.statePath))try{let e=V(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){r9.warn({err:e},`[sync] failed to load sync state`)}}};zo();const DAe=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function OAe(){return{async afterLoadDocument({documentName:e,requestParameters:t}){if(Zx(e)||Qx(e))return;let n=t?.get(`mountId`)??void 0,r={"doc.name":e};n!==void 0&&DAe.test(n)&&(r[`mount.id`]=n);try{let e=()=>{Go(`sync.handshake`,{attributes:r},()=>{})},n=t?.get(`traceparent`);if(n!=null){let r={traceparent:n},i=t?.get(`tracestate`);i!=null&&(r.tracestate=i),Bo.with(Lo.extract(Bo.active(),r),e)}else e()}catch(e){F(`sync-handshake-span`).warn({err:e instanceof Error?e:Error(String(e))},`emission failed`)}}}}let l9=!1;function u9(){if(l9)return;let e=pne;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){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const kAe=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function AAe(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(_8).join(` `)} auth git-credential`]}function jAe(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=Ml(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],fN({cwd:e,encoding:`utf-8`,timeout:5e3}))}catch(e){return F(`upstream-attribution`).warn({err:e,oldHead:n,newHead:r},`git log spawn threw; upstream docs keep file-system attribution`),i}if(a.error||a.status!==0||typeof a.stdout!=`string`)return F(`upstream-attribution`).warn({err:a.error,status:a.status,signal:a.signal,stderr:typeof a.stderr==`string`?a.stderr.slice(0,500):void 0,oldHead:n,newHead:r},`git log failed; upstream docs keep file-system attribution`),i;let o=null;for(let n of a.stdout.split(`
2036
2036
  `)){let r=n.trim();if(r===``)continue;if(r.startsWith(`C\0`)){let[,e,t]=r.split(`\0`);o=e&&t?{name:e,email:t}:null;continue}if(!o||!r.endsWith(`.md`)&&!r.endsWith(`.mdx`))continue;let a=z(e,r);if(!lN(a,t))continue;let s=Kz(a,t);i.has(s)||B(a)&&i.set(s,o)}return i}function d9(e){u9();let t=e.ingressPolicy??KB({}),{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=F(`server`),x=new s7,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 D(){let e=Ko({absPath:cs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=me(e.error)&&e.error.code===`SCHEMA_INVALID`?e.error.issues.filter(e=>e.path.map(String).join(`.`)===`content.attachmentFolderPath`):[];if(t.length>0){let e=t.map(e=>e.message).join(`; `);throw Error(`Invalid content.attachmentFolderPath in project config: ${e}`)}b.warn({},`[config] committed content.attachmentFolderPath unavailable (project config invalid) — using default attachment placement`)}return e.value.content.attachmentFolderPath??`./`}function O(){let e=Ko({absPath:cs(`project-local`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=he(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=Ko({absPath:cs(`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:xe(n.value.autoSync?.default)??`off`,source:`committed-default`}}function k(){let e=Ko({absPath:cs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?so(e):kt}function A(){return Ko({absPath:cs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ne(){return cM(r,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function re(){let e=Ko({absPath:cs(`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 ie(){return Jo({cwd:r,homedirOverride:u,warn:e=>b.debug({message:e},`[config] diagnostics read`)})}function ae(){for(let e of ie().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 oe(e){return`${Vj(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function se(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=O();t=n.mode,vt?.setMode(n.mode,n.source).catch(t=>{b.warn({err:t,mode:n.mode,docName:e},`[sync] failed to apply autoSync mode from config`)})}let n=ne();Pe.applyConfig({enabled:n.enabled,providerFingerprint:oe(n)}),e===`__config__/project`&&De?.signal(`lint-config`),b.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}bs();let j=wu(),ce=dO(r),le=new Td({localDir:ce,log:F(`acp-registry`)}),ue=new gd(ce,F(`acp-permissions`));if(Xs(ce,{port:e.port??0,worktreeRoot:r,kind:e.lockKind??`interactive`,capabilities:e.capabilities??[`http`,`ws`]}),!_)try{Y7({lockDir:ce,shadowRepoDir:qu(r)})}catch(e){throw Hs(ce),e}let de=qa(),fe=(e,t)=>de.resolveEmbed(e,t),pe=(e,t)=>{let r=de.resolveEmbed(e,t);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(n,r);if(!sN(i,z(n)))return null;try{let e=ou(i);return e.isFile()?e.size:null}catch{return null}},ge,_e,M,N,ve,ye,Se,Ce,we,Te,Ee,De=null,Oe=null,ke=null,Ae=null,je=null,Me=null,Ne=ne(),Pe=new yM({loadEmbedder:e.embedderLoader??(()=>{let t=ne();return qj({keyStore:e.embeddingsKeyStore??null,projectDir:r,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(dO(r),`embeddings`),enabled:Ne.enabled,providerFingerprint:oe(Ne)}),P=null,Fe=new Set,Ie=!1,Le=[],Re,ze,Be,Ve=new Promise((e,t)=>{ze=e,Be=t}),He,Ue=new Promise(e=>{He=e});async function We(){let e,t=Symbol(`branch-scope-gate-timeout`),n=new Promise(n=>{e=setTimeout(()=>n(t),1e4),e.unref?.()});try{if(await Promise.race([Ue,n])!==t)return S()}finally{e&&clearTimeout(e)}try{return u7(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 Ge(e){De?.signal(e)}let Ke=null,qe=!1,Je=()=>{try{B7(r,Ye.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Ye=new zke(void 0,{onEviction:()=>sse(),onSizeChange:e=>cse(e),onMutate:()=>{!qe||Ke!==null||(Ke=setTimeout(()=>{Ke=null,Je()},2e3))}});for(let[e,t]of Wke(r))nS(e)||hQ(e)&&([`.md`,`.mdx`].some(t=>{let r=z(n,`${e}${t}`);return sN(r,z(n))&&B(r)})||Ye.restore(e,t));qe=!0;let Xe={current:null},Ze=(e,t)=>{nS(e)||Ye.setRenamed(e,t)},Qe=e=>{if(!nS(e)){if(Ye.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Ye.setDeleted(e),Xe.current?.deleted(e)}},$e=e=>{nS(e)||Ye.delete(e)};try{ge=lP({projectDir:r,contentDir:n,singleDocRelPath:v,inPlaceSkillDirs:SL(n),rescanInPlaceSkillDirs:()=>SL(n),onAfterRebuild:()=>{_e.refreshContentScope().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] derived-index rebuild failed after onAfterRebuild`)}),hB(gt).then(({prunedFiles:e,prunedFolders:t})=>{let n=e+t;n>0?F(`server-factory`).info({pruned:n,prunedFiles:e,prunedFolders:t},`[content-filter] reconciled file indexes after onAfterRebuild`):F(`server-factory`).debug({prunedFiles:e,prunedFolders:t},`[content-filter] file index reconcile completed after onAfterRebuild (no entries pruned; rescan may have added entries)`)}).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] file index reconcile failed after onAfterRebuild`)})}}),_e=new lz({projectDir:r,contentDir:n,contentFilter:ge,getGlobalSkillRoots:()=>lq(ve.managedArtifactCtx),signalChannel:Ge,getLocalTargetInventory:()=>rq(gt,n),onRecoveredFileTarget:(e,t)=>{gt&&Vke({watcher:gt,contentDir:n,relativePath:e,exists:t,invalidateReferencedAssetsCache:je})}}),M={current:f},N=s?Dke({getShadow:()=>M.current??null,getCurrentBranch:()=>_t?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Ku(r)??void 0,isWriterLive:e=>{if(!Ae&&!Ce)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(Ae?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of Ce?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,ve=N7({contentDir:n,projectDir:r,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:M,ephemeral:y,contentRoot:p,derivedDocumentIndex:_e,configHomedirOverride:u,getCurrentBranch:()=>_t?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:pe,getPrincipal:()=>P,onAgentCommit:()=>De?.signal(`session-activity`),onFlushCommit:()=>N?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{De?.emitDiskAck(e,t),!nS(e)&&dV(r,n)&&(je?.(),Ge(`files`))},onConfigRejected:(e,t)=>De?.emitConfigValidationRejected(e,t),onConfigPersisted:se,isRecentlyRemoved:e=>Ye.has(e),mdManager:e.mdManager,getLossRing:()=>ye,durabilityState:x}),Se=new UOe({quiet:i,debounce:a,maxDebounce:o,extensions:[ve.extension]});let m=Se;Le.push(yce(()=>m.documents.size),bce(()=>ve.getQueueDepths()),Sce(()=>{let e=0;for(let t of m.documents.values())e+=t.directConnectionsCount;return{websocket:m.getConnectionsCount()-e,direct:e}})),wce(),y||(Me=Lke({getLoadedDocuments:()=>m.documents,forceStore:(e,t)=>ve.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let t=cN(e,n),r,i;try{r=H(t),i=ou(r).size}catch(t){let n=Us(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new F7(`symlink cycle at content path: ${e}`):t}if(!lN(r,n))throw new F7(`symlink-escape: ${t} resolves outside the content dir`);if(i>524288)throw new F7(`document exceeds the open byte limit: ${e}`);try{return V(r,`utf-8`)}catch(e){if(Us(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let _=Se.shouldUnloadDocument.bind(Se);Se.shouldUnloadDocument=e=>{if(Fe.has(e)||Ie&&_(e))return!0;let t=e.name;return nS(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:_(e)},Re=async e=>{Fe.add(e);try{await Se.unloadDocument(e)}finally{Fe.delete(e)}},De=new aS(Se),ke=new EE(Se),Ae=new DE(Se),Ce=new jw(Se,e.agentSessionOptions);let S=Ce;Le.push(Cce(()=>({active:S.liveSessionCount,limit:S.sessionLimit})));let w=d7({derivedDocumentIndex:_e,onDocumentSettled:e=>Xe.current?.changed(e)});Se.configuration.extensions.push(w);function T(e,t,n={}){b.warn({reason:e,docName:t,...n},`[auth-rejection] ${e}`)}Se.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=TQ(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==j)throw T(`server-instance-mismatch`,e.documentName,{claimedServerInstanceId:r,currentServerInstanceId:j}),new wQ(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${j}`);let i=n?.expectedBranch;if(typeof i==`string`&&i.length>0){let t=await We();if(t!==null&&i!==t)throw T(`branch-mismatch`,e.documentName,{claimedBranch:i,currentBranch:t}),new wQ(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${t}`)}if(!n)return;let a=e.context;typeof n.principalId==`string`&&(P&&n.principalId===P.id?a.principalId=P.id:P?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:P.id})):a.principalId=n.principalId),typeof n.tabSessionId==`string`&&(a.tabSessionId=n.tabSessionId),a.kind=`human`}}),Se.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(e){if(!Qx(e.documentName)&&!$x(e.documentName))return;let n=e.request,r=n.socket?.remoteAddress;if(r!==void 0&&!qB(r,t))throw T(`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(!YB(a,t))throw T(`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 E=z(n);function ee(e){if(!hQ(e))return null;let t=z(E,Jx(e));return sN(t,E)?t:null}Se.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await Hke(e.documentName,{recentlyRemovedDocs:Ye,resolveFilePath:ee,fileExists:B})}}),Se.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=TQ(e.token);ake(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Se.documents.get(e)})}}),Se.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new T5(e.update);if(t.readVarString(),t.readVarUint()===I5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${ga} rejected — server-only channel`)}});let te=gQ({hocuspocus:Se,durabilityState:x,ingressPolicy:t,sessionManager:Ce,commentDocHooksRef:Xe,contentDir:n,contentFilter:ge,serverInstanceId:j,getFileIndex:()=>gt?gt.getFileIndex():new Map,getAttachmentFolderPath:D,getAllFilesIndex:()=>gt?gt.getAllFilesIndex():new Map,getFileIndexGeneration:()=>gt?.getFileIndexGeneration()??0,mutateFileIndex:e=>gt?.mutateFileIndex(e),getFolderIndex:()=>gt?gt.getFolderIndex():new Map,getAliasMap:()=>gt?gt.getAliasMap():new Map,getFolderAliasIndex:()=>gt?gt.getFolderAliasIndex():new Map,rescanFiles:()=>gt?.rescanFromDisk(),enableTestRoutes:d,shadowRef:M,flushGitCommit:()=>ve.flushPendingGitCommit(),flushContributors:()=>ve.flushContributors(),getCurrentBranch:()=>_t?.getLastKnownBranch()??null,getDiskAckSVs:()=>De?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,derivedDocumentIndex:_e,signalChannel:Ge,agentFocusBroadcaster:ke,agentPresenceBroadcaster:Ae,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>vt,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:r,resolveEmbed:fe,getBridgeLossReporter:()=>Ee,getPrincipal:()=>P,acpRegistry:le,loadAcpCustomAgents:()=>Ed(ce,F(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Re,ready:Ve,recentlyRemovedDocs:Ye,serializeDoc:it,evictManagedArtifactLkg:e=>{ve.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Pe,getSemanticSimilarityFloor:()=>ne().similarityFloor,getLinterBaseConfig:()=>k(),getLinksValidationSetting:()=>A(),getLinkPreviewsEnabled:re,getConfigDiagnostics:ie,embeddingsSecretsFile:eM(u),readSemanticProviderConfig:ne,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{je=e}});Se.configuration.extensions.push(te),we=te.nativeApi,Te=te.localApi;let O=Ko({absPath:cs(`project`,r),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),ae=O.value.bridge.deferGuard.enabled,oe=O.value.bridge.fixedPoint.enabled,ue=O.value.bridge.preDrain.enabled;ye=O.value.lossCapture.enabled?new Xae({projectDir:r,maxBytes:O.value.lossCapture.maxBytes}):void 0,O.value.bridge.lossDetector.enabled&&(Ee=Vse({shadow:()=>M.current,ring:ye,getBranch:()=>_t?.getLastKnownBranch()??`main`,contentRoot:p??``}),Ce.attachBridgeLossReporter(Ee)),Se.configuration.extensions.push(H7({mdManager:Ho,schema:Vo,shadowRef:M,contentRoot:p,getCurrentBranch:()=>_t?.getLastKnownBranch()??null,resolveEmbed:fe,resolveSize:pe,deferGuardEnabled:ae,lossDetectorEnabled:O.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:oe,preDrainEnabled:ue,lossRing:ye})),Se.configuration.extensions.push(OAe()),Se.configuration.extensions.push(ike({getSyncEngine:()=>vt,projectDir:r,contentDir:n}))}catch(e){for(let e of Le.splice(0))e();throw Me?.dispose(),Me=null,Hs(ce),e}let et=null,tt=new Map,nt=[];function rt(e,t){let n=z(e,`rescue`),r=z(n,Jx(t));return sN(r,n)?r:null}function it(e){let t=Se.documents.get(e);return t?Sz(t):null}let at=(e,t)=>yz(x,Se,e,t,fe,pe,Ee);function ot(e){if(!mS(e)||vt?.getConflicts().some(t=>o7(t,e.name,r,n)))return;let t=e.getMap(`lifecycle`);t.delete(`status`),t.delete(`reason`)}let st=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Se.documents){if(nS(n))continue;let r=Se.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{dz(r,i,fe,n)},uz)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},ct=null,lt=e=>{e&&(ct===null&&(ct=new Set,setImmediate(()=>{let e=ct;if(ct=null,e)try{for(let t of e)st(t)}catch(t){b.error({err:t,basenames:[...e]},`[asset-event] dedup rerender pass crashed`)}})),ct.add(e))};function ut(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 Oz(e)}}async function ft(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),await _e.recordDiskUpsert(e.docName,e.content),Ge(`files`),$e(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=Se.documents.get(t);if(!r){await _e.recordDiskUpsert(t,n);return}let i=C(t)??``,a=it(t)??i,o=hz({docName:t,base:i,ours:a,theirs:n}),s=Fz(i).slice(0,6),c=Fz(a).slice(0,6),l=Fz(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`:ot(r),await _e.recordDiskUpsert(t,n);break;case`clean`:{let e=!1;try{at(t,o.newContent),w(t,o.newContent),Gb(),ot(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),ot(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`merged`:{let e=!1;try{at(t,o.newContent),w(t,n),Gb(),ot(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),ot(r)}e&&await _e.recordDiskUpsert(t,n)}break;case`conflicts`:{let e=!1;try{at(t,o.newContent),w(t,o.newContent),Gb(),Kb(),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 _e.recordDiskUpsert(t,n);break}case`refused`:{Kb();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Se.documents.get(t);if(!n){await _e.recordDiskDelete(t),Ge(`files`),Qe(t),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:t,kind:`deleted`,source:`watcher-delete`}));return}let r=C(t)??``,i=it(t)??``,a=i!==r;if(a&&M.current){let e=M.current,n=_t?.getLastKnownBranch()??`main`;queueMicrotask(()=>{Mx(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{Jb(),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 _e.recordDiskDelete(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Se.closeConnections(t),await Re(n),Ge(`files`),Qe(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=Se.documents.get(t);if(T(t),w(n,r),await _e.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}`),Ge(`files`),Ze(t,n),console.info(JSON.stringify({event:`recently-removed-docs-populate`,from:t,to:n,kind:`renamed`,source:`watcher-rename`}));break}case`conflict`:{let{docName:t}=e,n=Se.documents.get(t);if(!n)return;let r=it(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`:de.add(e.relativePath),Ge(`files`),lt(Pl(e.relativePath));break;case`asset-delete`:de.remove(e.relativePath),Ge(`files`),lt(Pl(e.relativePath));break;case`folder-create`:case`folder-delete`:Ge(`files`);break;case`file-create`:case`file-update`:await _e.recordFileTargetUpsert(e.relativePath),je?.(),Ge(`files`);break;case`file-delete`:await _e.recordFileTargetDelete(e.relativePath),je?.(),Ge(`files`);break;default:Oz(e)}}catch(t){let n=ut(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let pt=[];async function mt(e){if(te()){pt.push(e);return}await ft(e)}async function ht(){let e=pt.splice(0,pt.length);for(let t of e)await ft(t)}let gt=null,_t=null,vt=null,yt=null;async function bt(e){if(Se.documents.size===0)return;let t=!1,n=new Promise(e=>{Se.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Se.documents.keys());Se.closeConnections(),Se.flushPendingStores();for(let e of Se.documents.values())e.getConnectionsCount()===0&&Se.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(Se.documents.keys()),i=[],o=[];if(M.current){for(let e of n)if(!nS(e))try{let t=it(e);if(t===null){b.warn({docName:e},`[rescue] skipping ${e} — document dropped from map mid-rescue`),o.push(e);continue}let n=rt(M.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:M.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Xl(I(n),{recursive:!0}),cu(n,t,`utf-8`),Jb(),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 xt(){return yt||(yt=(async()=>{let e=Date.now(),t=[];Ie=!0;for(let e of Le.splice(0))e();try{await Me?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Me=null;try{Qs(ce)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ke!==null&&(clearTimeout(Ke),Ke=null),qe)try{B7(r,Ye.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([Ve.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=Se.documents.size;N?.destroy();try{try{try{Oe&&=(clearTimeout(Oe),null),_t&&=(await _t.unsubscribe(),null),gt&&=(await gt.unsubscribe(),null);for(let{docName:e,cleanup:t}of nt)try{await t()}catch(t){b.warn({err:t,docName:e},`[server] failed to stop config-file-watcher for ${e}`)}nt.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{De?.destroy(),Ae?.destroy(),et&&=(await et.disconnect(),null);for(let[e,t]of tt)try{await t.disconnect()}catch(t){b.warn({err:t,docName:e},`[server] failed to disconnect ${e} during shutdown`)}tt.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 Ce.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 rce()}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 bt(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`)}_e.close();let e;try{await Promise.race([(async()=>{await ve.flushPendingGitCommit(),await ve.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),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{vt&&=(await vt.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(M.current){let e;try{await Promise.race([fx(M.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 Ns({baseDir:r,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&cu(z(M.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{Sse(M.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{Hs(ce,{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)})}}})(),yt)}let St=[];async function Ct(){try{P=await I7(r),b.info({principalId:P.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!M.current)try{M.current=await vx(r),b.info({gitDir:M.current.gitDir},`[server] history repo initialized at ${M.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),St.push(`shadow-repo`)}if(M.current){let e=null;try{e=$q(M.current.gitDir),SJ(M.current.gitDir,e),iJ(M.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(M.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 N?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(M.current)try{await gx(M.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{M.current=await vx(r)}catch(e){b.error({err:e},`[server] history repo reinit failed`),M.current=void 0,St.includes(`shadow-repo`)||St.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(M.current)try{let e=z(M.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let n=null;try{n=(await Ns({baseDir:r,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(n!==null){if(n!==t){let e=`main`;try{let t=(await Ns({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 kx(M.current,p??``,t,n,e),qb()}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{cu(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=zq(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`),St.push(`managed-rename-recovery`)}try{let e=NL(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`),St.push(`upload-tempfile-sweep`)}try{et=await Se.openDirectConnection(ga),De?.emitServerInfo(j,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),St.push(`cc1-push`)}let t=y?[]:li;for(let e of t)try{let t=await Se.openDirectConnection(e);tt.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),St.push(`config-doc:${e}`)}let i=new Map([[nr,cs(`project`,r)],[dt,cs(`project-local`,r)],[go,cs(`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 Y5(t,t=>{let n=Se.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=a7(n??null,e,t,ve.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),se(e)});nt.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}`),St.push(`config-file-watcher:${e}`)}}if(!y){let e=(e,t)=>{let n=mq(e,ve.managedArtifactCtx);if(!n)return;let r=yq(Se.documents.get(n)??null,n,t,ve.managedArtifactCtx);b.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Ge(`files`),Tn(n)&&_e.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})},t=e=>{let t=mq(e,ve.managedArtifactCtx);Ge(`files`),t&&Tn(t)&&_e.refreshGlobalSkillNodes().catch(e=>{b.warn({err:e,docName:t},`[backlinks] global skill bundle prune failed`)})};try{let n=lq(ve.managedArtifactCtx),r=await Oke(n,e,t);nt.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`),St.push(`managed-artifact-watcher:skills`)}try{let e=z(oq(ve.managedArtifactCtx),`.ok`,`skill-state.yml`),t=await Y5(e,()=>{Ge(`files`)});nt.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`),St.push(`skill-state-watcher`)}}try{let e=z(n,`.okignore`),t=z(r,`.gitignore`),i=null;try{let e=Ml(`git`,[`rev-parse`,`--git-common-dir`],fN({cwd:r,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(r,e.stdout.trim()),`info`,`exclude`);B(I(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 YOe(a,(t,n)=>{(async()=>{if(t===e)try{let e=a7(Se.documents.get(`__config__/okignore`)??null,yo,n,ve.configPersistenceCtx);o.info({docName:yo,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:R(r,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ge.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:R(r,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),De?.signal(`files`);else{let e=R(r,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),De?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(r,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(nt.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`),St.push(`ignore-files-watcher`)}let a=u7(r).branch??`main`;E(a),He();let o=_e.beginStartup(a),s=!1,c=performance.now();try{await Zo(`ok.boot.indexes`,void 0,async()=>{let{deletedDocNames:e,backlinkIndexDegraded:t}=await o.backlinksReady;t&&St.push(`backlink-index`);let i=0;for(let t of e)nS(t)||Ye.peek(t)?.kind!==`renamed`&&(Ye.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?SL(n):new Set,d=e=>{e.some(e=>c.test(R(n,e).split(Vl).join(`/`)))&&(Oe&&clearTimeout(Oe),Oe=setTimeout(()=>{Oe=null;try{XX(r,n).then(e=>{e>0&&(b.info({refreshed:e},`[in-place-skills] re-synced recorded copies`),De?.signal(`files`))}).catch(e=>b.warn({err:e},`[in-place-skills] copy re-sync failed`));let e=SL(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`),De?.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))};gt=await Zo(`ok.boot.seed-walk`,void 0,async()=>mB(n,mt,ge,{onRawBatch:d})),XX(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??uu();XX(e,e,bL(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`))}RL(`seedWalkMs`,Math.round(performance.now()-a));{let e=z(n),t=0;for(let[n]of Ye.entries()){if(!hQ(n))continue;let r=z(e,`${n}${Kx(n)}`);sN(r,e)&&B(r)&&(Ye.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 _e.settleStartupAfterWatcherSeed();s=!0,f.tagIndexDegraded&&St.push(`tag-index`);let p=0;try{v===void 0?await yQ({contentDir:n,contentFilter:ge,basenameIndex:de,onSkip:(e,t,n)=>{p++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):jge({contentDir:n,basenameIndex:de,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`),St.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),St.push(`basename-index`)}})}catch(e){if(b.error({err:e},`[server] disk bridge watcher failed to start`),St.push(`file-watcher`),!s){let e=await _e.settleStartupAfterWatcherSeed();s=!0,e.tagIndexDegraded&&St.push(`tag-index`)}}finally{RL(`indexesMs`,Math.round(performance.now()-c)),gt&&zL(`fileCount`,gt.getFileIndex().size)}try{_t=await uke(r,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),ioe(),Se.flushPendingStores(),await ve.flushPendingGitCommit(),ee(!0),M.current){let e=S(),t=u7(r).branch??e,n=[];for(let[e,t]of Se.documents){if(nS(e))continue;let r=null;if(t.transact(()=>{r=it(e)},kAe),r===null)continue;let i=C(e)??r;n.push({docName:e,markdown:r,diskSnapshot:i})}if(n.length>0)try{let r=await Mse(M.current,e,Dx.id,n,t);r&&(soe(),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=pt.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 ht(),e.headMoved&&e.newHead){let t=jAe(r,z(n),e.oldHead,e.newHead);if(t.size>0){tj(t.keys());for(let[e,n]of t)ej(e,Uu(n.email),n.name,n.email,sd(e));await ve.flushContributors()}}if(await ve.flushDeferredStores(`within-branch`),vt!==null)try{await vt.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{ooe(),pt.splice(0,pt.length);let t=!1,r;try{E(i),r=await _e.beginBranchSwitch(i),ge.rebuildDirCount();try{let e=0;de.clear(),await yQ({contentDir:n,contentFilter:ge,basenameIndex:de,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`),St.includes(`basename-index-partial`)||St.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,t]of Se.documents)if(!nS(e))try{let r=cN(e,n);if(!B(r)){let n=C(e)??``,r=it(e)??``;if(r!==n&&M.current){let t=M.current;queueMicrotask(()=>{Mx(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{Jb(),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=V(r,`utf-8`);at(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:Se.documents.size},`[branch-switch] loaded branch ${i} (${Se.documents.size} docs)`);try{await _e.settleBranchFromDisk(r)}catch(e){_e.abortBranchSwitch(r),b.error({err:e,branch:i},`[derived-index] branch-switch rebuild failed; relationship views may be stale`)}if(M.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Se.documents)if(!nS(t))try{let n=await Pse(M.current,i,Dx.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=hz({docName:t,base:n.diskSnapshot,ours:n.markdown,theirs:r});switch(a.kind){case`merged`:case`clean`:at(t,a.newContent),w(t,a.newContent),e++;break;case`conflicts`:at(t,a.newContent),w(t,a.newContent),Kb(),e++;{let e=Se.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-`)&&M.current)try{let t=gx(M.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await fx(M.current).withMutator(async()=>{for(let e of n.split(`
2037
- `))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 ve.flushDeferredStores(`discard-stale`),t=!0,De?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),t||(ee(!1),await ve.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&M.current&&t>0){let t=p??`.`;try{let n=await kx(M.current,t,e.oldHead,e.newHead,i);qb(),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`),St.push(`head-watcher`)}function l(e){for(let t of e)try{let e=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Vx(e),a=Se.documents.get(i);if(!a)continue;let o=it(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=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Se.documents.get(Vx(e));i&&ot(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=AAe(h),m=O();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{vt=new EAe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ve.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=M.current;n&&await jx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=M.current;n&&await jx(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 Uo({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:be(t.error),configPath:cs(`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 vt.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),vt=null}Ge(`files`),_e.announceReadyViews();let g=LL();g!==void 0&&RL(`readyMs`,g),ae()}return Ct().then(ze,e=>{_e.close(),He(),Be(e)}),{hocuspocus:Se,durabilityState:x,sessionManager:Ce,nativeApi:we,localApi:Te,cc1Broadcaster:De,agentFocusBroadcaster:ke,agentPresenceBroadcaster:Ae,maintenanceCoordinator:N,contentFilter:ge,basenameIndex:de,serverInstanceId:j,destroy:xt,ready:Ve,degraded:St,lockDir:ce,get syncEngine(){return vt},getLinkPreviewsEnabled:re,resolveEmbed:fe,acpRegistry:le,acpPermissions:ue}}function f9(e){return e/1048576}function MAe(){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;Xo(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function NAe(){if(p9)return;let e=xs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=MAe();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 PAe(){if(!m9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!_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=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=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=F(`skill-migrate`);function b9(e){return[{host:`agents`,root:vr},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=eD.indexOf(e.host),r=eD.indexOf(t.host);return(n===-1?eD.length:n)-(r===-1?eD.length:r)||e.host.localeCompare(t.host)})}const FAe=b9(io),IAe=b9(_i);function LAe(e,t){ls(I(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function RAe(e,t,n){let r=LI(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=H(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!H(z(e,t.dir)).startsWith(n+Vl)}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??FAe,a={migrated:[],skipped:[]};if(!B(n))return a;let o;try{o=tu(n)}catch{return a}let s=R(t,n).split(Vl).join(`/`),c=new Set;for(let[e,n]of Object.entries(qX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Wa.test(e)||iI.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=z(n,e);if(!B(L(o,`SKILL.md`)))continue;let s=JE(o)?.contentHash;if(s===void 0)continue;let l=H(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:GI(t,i),state:RAe(L(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&B(z(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ps(d.path,{recursive:!0,force:!0}),LAe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await VN(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=F(`skill-reconcile`),zAe=iI;function w9(){let e=[];for(let t of Pa){let n=io[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:vr,editor:null}),e}function BAe(e,t){let n=R(e,z(t));return Ll(n)?z(t):n}function T9(e){let{frontmatter:t,body:n}=jt(e),r={};if(t!==``)try{let e=(0,CD.parse)(Xt(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function VAe(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=L(e,o),c=L(t,o);if(i+=ou(s).size+ou(c).size,i>1048576)return!1;let l=V(s),u=V(c);if(!l.equals(u)&&(o!==`SKILL.md`||!VAe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of tu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(BAe(e,n),t,`dir`)}function k9(e,t){try{let n=nu(e);return z(Ll(n)?n:z(I(e),n))===z(t)}catch{return!1}}function HAe(e,t){try{let n=nu(e),r=Ll(n)?z(n):z(I(e),n);if(!B(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||Ll(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const UAe=[...Pa,`agents`];function WAe(e){for(let t of UAe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function GAe(e){let{projectDir:t,skillsRoot:n}=e;if(!B(n))return;let r;try{r=tu(n)}catch{return}let i=w9();for(let e of r){let r=WAe(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(B(o))try{let n=Yl(a);if(n.isSymbolicLink()||!n.isDirectory()||!B(L(a,`SKILL.md`))||!B(L(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(GI(t,r))continue;let i=L(r,e);k9(i,a)&&O9(r,i,o)}ps(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 KAe(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=z(t,e);if(!B(o)||GI(t,o))continue;let s;try{s=tu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(zAe.has(e))continue;let t=L(o,e),s=z(n,e),c=B(s);try{let l=Yl(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(HAe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Wa.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=RN(t);for(let[r,a]of i){let i=z(n,r);if(!B(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await BN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??BI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{GAe({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=dO(e);A9=new As({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ao(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,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){ao(null),await A9?.drain(),A9=null,j9=!1}zo();const qAe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],JAe=[`cache`,`tmp`];function YAe(e){let t=z(e,ge);if(!(()=>{if(!B(t))return!0;try{return tu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of qAe)B(z(e,t))&&n.push(t);for(let t of JAe){let r=z(e,t);try{B(r)&&ou(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function XAe(e){let t=Gu(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 ZAe(e){IL();let t=e.projectDir??e.contentDir,n=Rge({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Es.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),N9(t),NAe(),PAe();let{kind:r,gitdir:i}=XAe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=Ige(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Zo(`ok.boot`,{attributes:a},async()=>QAe(e)),l=()=>{if(s)try{let e=Lo.extract(Bo.active(),{traceparent:s});return Bo.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function QAe(e){let t=e.skipAutoInit??!1,n=e.log??F(`boot`),r=e.serverRuntime??{...Sr(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((fr(r)||!Gt(i))&&!r.allowExternal)throw new UB(`refusing to start: the server would bind a non-loopback address (${(Gt(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=KB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.publicUrlSource!==`server`&&(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.publicUrl — external requests will be REFUSED (403 host-not-allowed) because no external Host name is admitted. Set server.publicUrl 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.publicUrl — the bind-address literals are admitted as Host names (direct IP access). Set server.publicUrl 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-CDm0H6LS.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new J8(B(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);B(h)||F(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??yK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof gK||e instanceof _K){let t=e instanceof _K?e.detected:``,r=e instanceof _K?`too_old`:`not_available`;RK(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 _=YAe(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);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,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:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,k=()=>r.publicUrlSource===`server`&&r.publicUrl!==void 0?r.publicUrl.replace(/\/+$/,``):`http://${D}:${O}`,A=e.ephemeral?void 0:V8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:v.localApi,log:n}),ne=c();ne.headersTimeout=3e4,ne.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:_Q({contentFilter:v.contentFilter,contentSirv:ic(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_e,assetExtensions:w,blocklistExtensions:ke,ingressPolicy:a}),ie=!1;if(e.reactShellDistDir)try{xZ(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof bZ)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let ae=e.reactShellDistDir?ic(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new fE({contentDir:e.contentDir,localDir:C,globalDir:z(uu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,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:()=>k(),getMcpStdioCommand:()=>dE(e.localOpCliArgs,O),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let j=K8({httpServer:ne,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:A,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},le=null;e.idleShutdownMs!==null&&(le=jQ({httpServer:ne,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ce()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let ue=[...new Set(i)],de=ue[0],fe=async()=>{if(ie)try{wZ(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}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(ne,e.port??0,de??`127.0.0.1`)}catch(e){throw await fe(),e}let me=ne.address(),he=typeof me==`object`&&me?me.port:e.port??0,M=[];for(let e of ue.slice(1)){let t=c();t.headersTimeout=ne.headersTimeout,t.requestTimeout=ne.requestTimeout;for(let e of ne.listeners(`request`))t.on(`request`,e);for(let e of ne.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:M.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...M,ne])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await fe(),t}M.push(t)}let N=LL();N!==void 0&&RL(`httpListenMs`,N);let ve=ne.address(),ye=typeof ve==`object`&&ve?ve.port:e.port??0;O=ye;let be=`http://${D}:${ye}`;d(C,ye,be),ie&&SZ(C,ye,be);let xe=!1,Se=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)}};ce=async()=>{if(xe)return;xe=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await Se(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ie&&sge(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{le?.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 M)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`,()=>j.shutdown()),A!==void 0&&await t(`mcpHttpHandler.close`,()=>A.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{j.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ne.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ne.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ie&&await t(`releaseUiLock`,async()=>wZ(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>Es.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,yL(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=uu(),t=await S9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:IAe,inPlaceNames:x9(e,bL(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 KAe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ne,destroy:ce,lockDir:C,contentDir:e.contentDir,port:ye,ready:x,degraded:S,didAutoInit:f,serverInstance:v,runtime:KDe(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 OQ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=Ku(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Fs({baseDir:n,timeout:{block:5e3}});s=new Set(await Wb(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=Vx(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 $Ae=Me;function eje(e={}){let t=e.home??uu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?B(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?B(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(ks(),1);const R9=L(uu(),`.ok`,`logs`),tje=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function nje(){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 rje(e){Xl(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function ije(e){try{if(ou(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{ru(n,r)}catch{}}try{su(`${e}.3`)}catch{}}function aje(e){try{let t=Date.now(),n=10080*60*1e3,r=tu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ou(L(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{su(L(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{su(L(e,t.name)),a-=t.size}catch{}}}catch{}}function oje(e){rje(R9);let t=z9(),n=e.filePath??L(R9,`${e.name}.${t}.log`);ije(n),(e._setTimeout??setTimeout)(()=>aje(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:nje(),name:e.name,redact:{paths:tje,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 sje(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 cje(e){return L(R9,`${e}.${z9()}.log`)}function lje(){return R9}function uje(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=B(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const B9=Au(Al),V9=F(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function dje(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],fN({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function fje(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],fN({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 pje(e){let t=z(e,`packed-refs`);if(B(t))try{if(V(t,`utf-8`).split(`
2037
+ `))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 ve.flushDeferredStores(`discard-stale`),t=!0,De?.emitBranchSwitched(i)}finally{_e.abortBranchSwitch(r),t||(ee(!1),await ve.flushDeferredStores(`discard-stale`))}}if(e.headMoved&&e.newHead&&M.current&&t>0){let t=p??`.`;try{let n=await kx(M.current,t,e.oldHead,e.newHead,i);qb(),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`),St.push(`head-watcher`)}function l(e){for(let t of e)try{let e=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Vx(e),a=Se.documents.get(i);if(!a)continue;let o=it(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=oN(R(n,L(r,t)));if(e.startsWith(`..`))continue;let i=Se.documents.get(Vx(e));i&&ot(i)}catch(e){b.warn({err:e,file:t},`[sync] failed to clear resolved content conflict`)}}let f=AAe(h),m=O();m.mode!==`off`&&b.info({mode:m.mode,source:m.source},`[sync] mode active at boot`);try{vt=new EAe({projectDir:r,contentDir:n,contentFilter:ge,contentRoot:p,mode:m.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:f,cc1Broadcaster:De,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ee(e),e||ve.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=M.current;n&&await jx(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=M.current;n&&await jx(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 Uo({cwd:r,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:be(t.error),configPath:cs(`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 vt.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),vt=null}Ge(`files`),_e.announceReadyViews();let g=LL();g!==void 0&&RL(`readyMs`,g),ae()}return Ct().then(ze,e=>{_e.close(),He(),Be(e)}),{hocuspocus:Se,durabilityState:x,sessionManager:Ce,nativeApi:we,localApi:Te,cc1Broadcaster:De,agentFocusBroadcaster:ke,agentPresenceBroadcaster:Ae,maintenanceCoordinator:N,contentFilter:ge,basenameIndex:de,serverInstanceId:j,destroy:xt,ready:Ve,degraded:St,lockDir:ce,get syncEngine(){return vt},getLinkPreviewsEnabled:re,resolveEmbed:fe,acpRegistry:le,acpPermissions:ue}}function f9(e){return e/1048576}function MAe(){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;Xo(()=>{p9=null,m9=null,h9=null,_9?.disable(),_9=null,v9=null});function NAe(){if(p9)return;let e=xs().createObservableGauge(`ok.server.memory.usage_megabytes`,{description:`Server process memory by section. Bounded labels: section ∈ {heap_used, heap_total, rss, external, array_buffers}.`,unit:`MB`});e.addCallback(e=>{let{snapshot:t}=MAe();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 PAe(){if(!m9){let e=xs().createObservableGauge(`ok.server.event_loop.delay_ms`,{description:`Event-loop delay percentiles over the last export window. Bounded labels: stat ∈ {p50, p99}.`,unit:`ms`});e.addCallback(e=>{if(!_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=xs().createObservableGauge(`ok.server.cpu.utilization`,{description:`Process CPU time as a fraction of wall time since the previous export. Bounded labels: mode ∈ {user, system}.`,unit:`1`});e.addCallback(e=>{let t=process.cpuUsage(),n=process.hrtime.bigint(),r=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=F(`skill-migrate`);function b9(e){return[{host:`agents`,root:vr},...Object.entries(e).filter(e=>e[1]!==null).map(([e,t])=>({host:e,root:t}))].sort((e,t)=>{let n=eD.indexOf(e.host),r=eD.indexOf(t.host);return(n===-1?eD.length:n)-(r===-1?eD.length:r)||e.host.localeCompare(t.host)})}const FAe=b9(io),IAe=b9(_i);function LAe(e,t){ls(I(t),{recursive:!0});try{ns(e,t)}catch(n){if(!(n instanceof Error)||n.code!==`EXDEV`)throw n;fs(e,t,{recursive:!0}),ps(e,{recursive:!0,force:!0})}}function RAe(e,t,n){let r=LI(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=H(z(e,`.ok`,`skills`))}catch{n=z(e,`.ok`,`skills`)}return new Set(t.filter(t=>{try{return!H(z(e,t.dir)).startsWith(n+Vl)}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??FAe,a={migrated:[],skipped:[]};if(!B(n))return a;let o;try{o=tu(n)}catch{return a}let s=R(t,n).split(Vl).join(`/`),c=new Set;for(let[e,n]of Object.entries(qX(t)))for(let t of n)t.path.split(`/`).slice(0,-1).join(`/`)===s&&c.add(e);for(let e of o)try{if(!Wa.test(e)||iI.has(e))continue;if(r.has(e)){a.skipped.push({name:e,reason:`placement-of-in-place`});continue}if(c.has(e)){a.skipped.push({name:e,reason:`recorded-placement`});continue}let o=z(n,e);if(!B(L(o,`SKILL.md`)))continue;let s=JE(o)?.contentHash;if(s===void 0)continue;let l=H(o),u=i.map(({host:n,root:r})=>{let i=z(t,r);return{host:n,root:r,path:L(i,e),escapes:GI(t,i),state:RAe(L(i,e),l,s)}}).filter(e=>!e.escapes),d=u.find(e=>e.state.kind===`store-link`||e.state.kind===`same-copy`)??u.find(e=>e.state.kind===`absent`&&B(z(t,e.root)))??u.find(e=>e.host===`claude`);if(!d){a.skipped.push({name:e,reason:`no-usable-target`});continue}if(d.state.kind===`occupied`){a.skipped.push({name:e,reason:`target-occupied:${d.root} (${d.state.by})`});continue}d.state.kind===`same-copy`?ps(o,{recursive:!0,force:!0}):(d.state.kind===`store-link`&&ps(d.path,{recursive:!0,force:!0}),LAe(o,d.path));for(let e of u)e===d||e.state.kind!==`store-link`||(ps(e.path,{recursive:!0,force:!0}),fs(d.path,e.path,{recursive:!0}));await VN(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=F(`skill-reconcile`),zAe=iI;function w9(){let e=[];for(let t of Pa){let n=io[t];n!==null&&e.push({rel:n,editor:t})}return e.push({rel:vr,editor:null}),e}function BAe(e,t){let n=R(e,z(t));return Ll(n)?z(t):n}function T9(e){let{frontmatter:t,body:n}=jt(e),r={};if(t!==``)try{let e=(0,CD.parse)(Xt(t));e&&typeof e==`object`&&!Array.isArray(e)&&(r=e)}catch{}return{fm:r,body:n}}function VAe(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=L(e,o),c=L(t,o);if(i+=ou(s).size+ou(c).size,i>1048576)return!1;let l=V(s),u=V(c);if(!l.equals(u)&&(o!==`SKILL.md`||!VAe(l.toString(`utf8`),u.toString(`utf8`))))return!1}return!0}function D9(e,t=``){let n=[];for(let r of tu(e,{withFileTypes:!0})){let i=t?`${t}/${r.name}`:r.name;r.isDirectory()?n.push(...D9(L(e,r.name),i)):r.isFile()&&n.push(i)}return n.sort()}function O9(e,t,n){ps(t,{recursive:!0,force:!0}),ls(e,{recursive:!0}),as(BAe(e,n),t,`dir`)}function k9(e,t){try{let n=nu(e);return z(Ll(n)?n:z(I(e),n))===z(t)}catch{return!1}}function HAe(e,t){try{let n=nu(e),r=Ll(n)?z(n):z(I(e),n);if(!B(r))return!1;let i=R(z(t),r);return i!==``&&(i.startsWith(`..`)||Ll(i))}catch(t){return C9.warn({linkPath:e,err:t},`isForeignSymlink: could not resolve symlink; treating as reconcile-managed`),!1}}const UAe=[...Pa,`agents`];function WAe(e){for(let t of UAe){let n=`-${t}`;if(e.length>n.length&&e.endsWith(n))return e.slice(0,-n.length)}return null}function GAe(e){let{projectDir:t,skillsRoot:n}=e;if(!B(n))return;let r;try{r=tu(n)}catch{return}let i=w9();for(let e of r){let r=WAe(e);if(r===null)continue;let a=z(n,e),o=z(n,r);if(B(o))try{let n=Yl(a);if(n.isSymbolicLink()||!n.isDirectory()||!B(L(a,`SKILL.md`))||!B(L(o,`SKILL.md`))||!E9(o,a))continue;for(let{rel:n}of i){let r=z(t,n);if(GI(t,r))continue;let i=L(r,e);k9(i,a)&&O9(r,i,o)}ps(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 KAe(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=z(t,e);if(!B(o)||GI(t,o))continue;let s;try{s=tu(o)}catch(e){C9.warn({hostRoot:o,err:e},`reconcile: skipped unreadable host skills root`);continue}for(let e of s){if(zAe.has(e))continue;let t=L(o,e),s=z(n,e),c=B(s);try{let l=Yl(t);if(l.isSymbolicLink()){if(k9(t,s)&&c)continue;if(HAe(t,n)){r.skipped.push({name:e,editor:i});continue}c?(O9(o,t,s),r.healed.push({name:e,editor:i})):(ps(t,{recursive:!0,force:!0}),r.orphansRemoved.push({name:e,editor:i}));continue}if(!l.isDirectory())continue;if(!Wa.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=RN(t);for(let[r,a]of i){let i=z(n,r);if(!B(i))continue;let o=e.skills[r],s=Array.from(new Set([...o?.hosts??[],...a]));try{await BN(t,r,{hosts:s,scope:o?.scope??`project`,scripts:o?.scripts??BI(i,r).hasScripts,installedAt:o?.installedAt??new Date().toISOString()})}catch(e){C9.warn({err:e,skill:r},`reconcile marker update failed (non-fatal)`)}}}try{GAe({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=dO(e);A9=new As({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ao(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,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function P9(){ao(null),await A9?.drain(),A9=null,j9=!1}zo();const qAe=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],JAe=[`cache`,`tmp`];function YAe(e){let t=z(e,ge);if(!(()=>{if(!B(t))return!0;try{return tu(t).length===0}catch{return!0}})())return[];let n=[];for(let t of qAe)B(z(e,t))&&n.push(t);for(let t of JAe){let r=z(e,t);try{B(r)&&ou(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function XAe(e){let t=Gu(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 ZAe(e){IL();let t=e.projectDir??e.contentDir,n=Rge({projectDir:t});if(n){let e=n.telemetry.attributeDenylist,t=[];for(let n of e){t.push(n);for(let e=1;e<=5;e++)t.push(`${`*.`.repeat(e)}${n}`)}Es.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}bs({localSink:n?.telemetry}),N9(t),NAe(),PAe();let{kind:r,gitdir:i}=XAe(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=ds(i));let o=Ige(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Zo(`ok.boot`,{attributes:a},async()=>QAe(e)),l=()=>{if(s)try{let e=Lo.extract(Bo.active(),{traceparent:s});return Bo.with(e,c)}catch(e){F(`boot`).warn({err:e},`ok.boot trace-join failed — starting unparented boot`)}return c()},u;try{u=await l()}catch(e){throw o.uninstall(),e}let d=u.destroy;return u.destroy=async()=>{try{await d()}finally{o.uninstall()}},u}async function QAe(e){let t=e.skipAutoInit??!1,n=e.log??F(`boot`),r=e.serverRuntime??{...Sr(e.config),allowExternal:!1},i=e.bind!==void 0&&e.bind.length>0?e.bind:[e.host??`127.0.0.1`];if((fr(r)||!Gt(i))&&!r.allowExternal)throw new UB(`refusing to start: the server would bind a non-loopback address (${(Gt(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=KB({serverRuntime:r});r.allowExternal&&!r.loopbackOnly&&r.externalUrlSource!==`server`&&(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-BgDwOXHz.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){n.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new J8(B(m)?`config`:`okdir`,p);let h=z(m,`.gitignore`);B(h)||F(`boot`).warn({path:h},"Note: .ok/.gitignore is missing — per-machine state files in .ok/ may show up as untracked changes. Run `ok init` to add the recommended ignore entries.");let g=e.gitPreflight??yK;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof gK||e instanceof _K){let t=e instanceof _K?e.detected:``,r=e instanceof _K?`too_old`:`not_available`;RK(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 _=YAe(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${ge}/.`);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,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:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te}=v,D=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),O=e.port??0,k=()=>r.externalUrlSource===`server`&&r.externalUrl!==void 0?r.externalUrl.replace(/\/+$/,``):`http://${D}:${O}`,A=e.ephemeral?void 0:V8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>k(),localApi:v.localApi,log:n}),ne=c();ne.headersTimeout=3e4,ne.requestTimeout=6e4;let re=e.serveContentAssets===!1?void 0:_Q({contentFilter:v.contentFilter,contentSirv:ic(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_e,assetExtensions:w,blocklistExtensions:ke,ingressPolicy:a}),ie=!1;if(e.reactShellDistDir)try{xZ(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ie=!0}catch(e){if(e instanceof bZ)n.info({event:`ui-lock-yielded-to-live-holder`,pid:process.pid,existingPid:e.existing.pid,existingPort:e.existing.port,lockDir:C},`ui.lock already held by a live process — yielding (advertisement is fulfilled)`);else throw await b().catch(()=>{}),u(C),e}let ae=e.reactShellDistDir?ic(e.reactShellDistDir,{single:!0,gzip:!0,etag:!0,dev:!0}):void 0,oe=e.ephemeral?null:new fE({contentDir:e.contentDir,localDir:C,globalDir:z(uu(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:T,agentPresenceBroadcaster:ee,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:()=>k(),getMcpStdioCommand:()=>dE(e.localOpCliArgs,O),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:n});oe!==null&&await oe.init();let se=`pending`;x.then(()=>{se=`ready`},()=>{se=`failed`});let j=K8({httpServer:ne,hocuspocus:y,nativeApi:v.nativeApi,mcpHttpHandler:A,ingressPolicy:a,health:{readiness:()=>se,degraded:()=>S},log:n,sessionManager:T,agentFocusBroadcaster:E,agentPresenceBroadcaster:ee,maintenanceCoordinator:te,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:re,reactShellMiddleware:ae,ephemeral:e.ephemeral,acpThreadManager:oe}),ce=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},le=null;e.idleShutdownMs!==null&&(le=jQ({httpServer:ne,thresholdMs:e.idleShutdownMs??18e5,log:n,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await ce()})})),await I9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:n});let ue=[...new Set(i)],de=ue[0],fe=async()=>{if(ie)try{wZ(C)}catch(e){n.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}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(ne,e.port??0,de??`127.0.0.1`)}catch(e){throw await fe(),e}let me=ne.address(),he=typeof me==`object`&&me?me.port:e.port??0,M=[];for(let e of ue.slice(1)){let t=c();t.headersTimeout=ne.headersTimeout,t.requestTimeout=ne.requestTimeout;for(let e of ne.listeners(`request`))t.on(`request`,e);for(let e of ne.listeners(`upgrade`))t.on(`upgrade`,e);try{await pe(t,he,e)}catch(t){n.error({err:t,failedAddress:e,port:he,alreadyBound:M.length+1},`[boot] secondary address bind failed — unwinding all listeners`);for(let e of[...M,ne])e.closeAllConnections?.(),await new Promise(t=>{e.close(e=>{e&&n.warn({err:e},`[boot] listener close failed during unwind`),t()})});throw await fe(),t}M.push(t)}let N=LL();N!==void 0&&RL(`httpListenMs`,N);let ve=ne.address(),ye=typeof ve==`object`&&ve?ve.port:e.port??0;O=ye;let be=`http://${D}:${ye}`;d(C,ye,be),ie&&SZ(C,ye,be);let xe=!1,Se=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)}};ce=async()=>{if(xe)return;xe=!0,se=`draining`;let e=[],t=async(t,r)=>{try{await Se(t,r)}catch(r){e.push(r),n.warn({err:r,step:t},`bootServer destroy step failed`)}};try{l(C),ie&&sge(C)}catch(e){n.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{le?.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 M)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`,()=>j.shutdown()),A!==void 0&&await t(`mcpHttpHandler.close`,()=>A.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{j.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{ne.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{ne.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ie&&await t(`releaseUiLock`,async()=>wZ(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>ys()),await t(`teardownToleranceTelemetry`,()=>P9()),await t(`flushLogFileSinks`,()=>Es.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await S9({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`),inPlaceNames:x9(e.contentDir,yL(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=uu(),t=await S9({projectDir:e,skillsRoot:z(e,`.ok`,`skills`),hostRoots:IAe,inPlaceNames:x9(e,bL(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 KAe({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),r=t.healed.length+t.replaced.length+t.orphansRemoved.length;r>0&&n.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,replaced:t.replaced.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${r} editor skill entr${r===1?`y`:`ies`} to the symlink model.`)}catch(e){n.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:ne,destroy:ce,lockDir:C,contentDir:e.contentDir,port:ye,ready:x,degraded:S,didAutoInit:f,serverInstance:v,runtime:KDe(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 OQ(n),a=i.list()}catch(e){r.warn({err:e,projectDir:n},`[boot] lifecycle restore: failed to read conflicts.json — skipping`);return}if(a.length===0)return;let o=e=>e.variant===`working-tree`,s=null;try{let e=Ku(n),t=e?L(e,`MERGE_HEAD`):null;if(!t||!B(t)){let e=a.filter(e=>!o(e));for(let t of e)i.removeConflict(t.file);if(a=a.filter(o),e.length>0&&console.warn(JSON.stringify({event:`lifecycle-restore-cleared-stale-conflicts`,reason:`no-merge-head`,count:e.length})),a.length===0)return}else{let e=Fs({baseDir:n,timeout:{block:5e3}});s=new Set(await Wb(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=Vx(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 $Ae=Me;function eje(e={}){let t=e.home??uu(),n=e.platformName??process.platform,r=e.env??process.env;return n===`darwin`?B(L(t,`Library`,`Application Support`,`Claude`)):n===`win32`?B(L(r.APPDATA??L(t,`AppData`,`Roaming`),`Claude`)):!1}var L9=t(ks(),1);const R9=L(uu(),`.ok`,`logs`),tje=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function nje(){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 rje(e){Xl(e,{recursive:!0})}function z9(){return new Date().toISOString().slice(0,10)}function ije(e){try{if(ou(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{ru(n,r)}catch{}}try{su(`${e}.3`)}catch{}}function aje(e){try{let t=Date.now(),n=10080*60*1e3,r=tu(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=ou(L(e,t));return{name:t,mtime:n.mtimeMs,size:n.size}}catch{return null}}).filter(Boolean);for(let i of r)if(t-i.mtime>n)try{su(L(e,i.name))}catch{}let i=r.filter(e=>t-e.mtime<=n).sort((e,t)=>e.mtime-t.mtime),a=i.reduce((e,t)=>e+t.size,0);for(let t of i){if(a<=47185920)break;try{su(L(e,t.name)),a-=t.size}catch{}}}catch{}}function oje(e){rje(R9);let t=z9(),n=e.filePath??L(R9,`${e.name}.${t}.log`);ije(n),(e._setTimeout??setTimeout)(()=>aje(R9),5e3).unref();let r=L9.default.destination({dest:n,append:!0,sync:!0});return(0,L9.default)({level:nje(),name:e.name,redact:{paths:tje,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 sje(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 cje(e){return L(R9,`${e}.${z9()}.log`)}function lje(){return R9}function uje(e){let t=z(e),n=0;for(;n<30;){let e=!1;try{e=B(z(t,`.git`))}catch{e=!1}if(e)return{gitRoot:t,distance:n};let r=I(t);if(r===t)return null;t=r,n+=1}return null}const B9=Au(Al),V9=F(`project-git`);var H9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function dje(e,t){try{return await B9(e,[`var`,`GIT_COMMITTER_IDENT`],fN({cwd:t,encoding:`utf-8`})),!0}catch{return!1}}async function fje(e,t){try{let{stdout:n}=await B9(e,[`for-each-ref`,`--count=1`,`refs/`],fN({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 pje(e){let t=z(e,`packed-refs`);if(B(t))try{if(V(t,`utf-8`).split(`
2038
2038
  `).some(e=>e.trim()!==``&&!e.startsWith(`#`)))return!0}catch{return!0}try{return tu(z(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 fje(e,t))return;let n=[`commit`,`--allow-empty`,`--no-verify`,`--no-gpg-sign`,`-m`,`Initial commit`],r=await dje(e,t),i=r?n:[`-c`,`user.name=Open Knowledge`,`-c`,`user.email=noreply@openknowledge.local`,...n];try{await B9(e,i,fN({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 mje(e,t){try{let{stdout:n}=await B9(e,[`rev-parse`,`--is-inside-work-tree`],fN({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function hje(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1,a=!1;if(B(n)){if(!ou(n).isDirectory())return{didInit:!1};if(B(r)){if(pje(n))return{didInit:!1};a=!0}else V9.info({},`detected partial .git/ — running git init to repair`),i=!0}let o;try{o=yK()}catch(e){throw e instanceof gK||e instanceof _K?(RK(e),V9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof _K?`too_old`:`not_available`,detectedVersion:e instanceof _K?e.detected:``},e instanceof _K?`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 mje(s,t))return{didInit:!1};let c=``;try{c=(await B9(s,[`init`,`--initial-branch=main`,t],fN({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(!B(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=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,gje=Sa.map(e=>e.replace(/\/$/,``));async function _je(e){let t=Ku(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(xje(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=Is(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await Ps(async()=>{let t=await vje(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await yje(n);if(r===null)return{kind:`skipped`,reason:`unborn-head`};let i=await q9(n);if(i.length===0)return{kind:`nothing-tracked`};let a=Is(e,{gitIndexFile:L(pu(),`ok-untrack-idx-${process.pid}-${Date.now()}.idx`)});await a.git.raw([`read-tree`,r]),await a.git.raw([`rm`,`--cached`,`-r`,`--ignore-unmatch`,`--`,...i]);let o=(await a.git.raw([`write-tree`])).trim(),s=await bje(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await NB(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;Rs(a,{GIT_AUTHOR_NAME:l,GIT_AUTHOR_EMAIL:u,GIT_COMMITTER_NAME:l,GIT_COMMITTER_EMAIL:u});let d=`Stop tracking the OpenKnowledge project skill\n\nThe \`${Yi}\` 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 gje){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function vje(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 yje(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function bje(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function xje(e){return B(L(e,`MERGE_HEAD`))||B(L(e,`rebase-merge`))||B(L(e,`rebase-apply`))||B(L(e,`CHERRY_PICK_HEAD`))||B(L(e,`REVERT_HEAD`))}function J9(e){return e instanceof Error?e.message:String(e)}async function Sje(e,t){let n;try{n=kl(t).resolve(e)}catch(e){if(e?.code===`MODULE_NOT_FOUND`)return;throw e}for(let t=I(n),r=0;r<32;r+=1){let n=L(t,`package.json`);if(B(n))try{let t=JSON.parse(await _u(n,`utf-8`));if(t.name===e&&typeof t.version==`string`)return t.version}catch{}let r=I(t);if(r===t)return;t=r}}const Cje=[{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 Cje)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 wje(e){if(!zx(e))throw new $9(e);let t;try{t=H(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!ou(t).isFile())throw new Q9(e);let n=I(t),r=_B(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:Vx(R(Tje(e),t).split(Vl).join(`/`)),canonicalFilePath:t}}let i=Pl(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:Vx(i)}}function Tje(e){return z(e,Ko({absPath:cs(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Eje(e){let t=Zl(z(pu(),`ok-ephemeral-`)),n=z(t,`.ok`);return Xl(n,{recursive:!0}),cu(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),cu(z(n,`.gitignore`),`local/
2039
2039
  `,`utf-8`),t}export{J2 as $,kx as $i,uz as $n,JM as $r,GJ as $t,J7 as A,hw as Ai,LB as An,qP as Ar,mQ as At,u7 as B,K as Bi,Zz as Bn,Qde as Br,JJ as Bt,d9 as C,Yu as Ca,EE as Ci,UB as Cn,rI as Cr,yQ as Ct,Y7 as D,dE as Di,YB as Dn,aF as Dr,_ge as Dt,K7 as E,Fu as Ea,iE as Ei,VB as En,GF as Er,LZ as Et,Cke as F,xw as Fi,Oz as Fn,zP as Fr,wZ as Ft,G8 as G,$x as Gi,Qz as Gn,wN as Gr,$J as Gt,q8 as H,aS as Hi,Nz as Hn,Lde as Hr,oY as Ht,y7 as I,WC as Ii,eB as In,LP as Ir,SZ as It,R8 as J,Px as Ji,bz as Jn,vN as Jr,nY as Jt,U8 as K,nS as Ki,jz as Kn,SN as Kr,sY as Kt,v7 as L,GC as Li,Fz as Ln,$de as Lr,xY as Lt,I7 as M,jw as Mi,FB as Mn,ife as Mr,bZ as Mt,N7 as N,Tce as Ni,_B as Nn,RP as Nr,xZ as Nt,W7 as O,Mw as Oi,XB as On,GP as Or,vge as Ot,_7 as P,Ece as Pi,gB as Pn,BP as Pr,CZ as Pt,U2 as Q,Sx as Qi,mz as Qn,cN as Qr,WJ as Qt,dke as R,pw as Ri,Pz as Rn,IP as Rr,vY as Rt,P9 as S,Xu as Sa,DE as Si,qW as Sn,sI as Sr,TQ as St,U7 as T,qu as Ta,fE as Ti,eV as Tn,Cpe as Tr,RZ as Tt,J8 as U,Qx as Ui,$z as Un,xN as Ur,lY as Ut,s7 as V,fS as Vi,Kz as Vn,lP as Vr,cY as Vt,K8 as W,rS as Wi,mB as Wn,bN as Wr,QJ as Wt,V2 as X,Ex as Xi,pz as Xn,gN as Xr,iY as Xt,O8 as Y,Tx as Yi,fz as Yn,pN as Yr,tY as Yt,H2 as Z,Dx as Zi,hz as Zn,fN as Zr,eY as Zt,$Ae as _,rh as _a,nj as _i,GW as _n,gI as _r,wQ as _t,wje as a,jx as aa,iM as ai,_K as an,Vpe as ar,ube as at,N9 as b,Ed as ba,fO as bi,KW as bn,pI as br,SQ as bt,_je as c,gx as ca,Nj as ci,IK as cn,DI as cr,G0 as ct,uje as d,ax as da,sj as di,xK as dn,TI as dr,O_e as dt,bx as ea,qM as ei,HK as en,tz as er,Sbe as et,oje as f,Qb as fa,cj as fi,dK as fn,wI as fr,m1 as ft,eje as g,ih as ga,rj as gi,WW as gn,hI as gr,xQ as gt,lje as h,nh as ha,ej as hi,IW as hn,_I as hr,EQ as ht,Eje as i,Nx as ia,sM as ii,gK as in,FI as ir,lbe as it,H7 as j,kw as ji,IB as jn,WP as jr,VZ as jt,q7 as k,Pw as ki,qB as kn,KP as kr,gQ as kt,H9 as l,lx as la,Pj as li,vK as ln,OI as lr,x1 as lt,cje as m,Tie as ma,ij as mi,sK as mn,EI as mr,jQ as mt,Z9 as n,Fx as na,rM as ni,LK as nn,MR as nr,P2 as nt,X9 as o,Mx as oa,oM as oi,mK as on,MI as or,dbe as ot,sje as p,hse as pa,aj as pi,uK as pn,kpe as pr,_1 as pt,V8 as q,Zx as qi,yz as qn,CN as qr,uY as qt,$9 as r,vx as ra,$j as ri,RK as rn,II as rr,k2 as rt,Sje as s,Ix as sa,aM as si,yK as sn,AI as sr,C2 as st,Q9 as t,wx as ta,cM as ti,BK as tn,BR as tr,F2 as tt,hje as u,sx as ua,Kj as ui,TK as un,kI as ur,$$ as ut,ZAe as v,Td as va,dO as vi,BW as vn,mI as vr,bQ as vt,u9 as w,md as wa,TE as wi,KB as wn,cI as wr,_Q as wt,M9 as x,gd as xa,yD as xi,RW as xn,oI as xr,Mge as xt,I9 as y,_d as ya,uO as yi,YW as yn,dI as yr,CQ as yt,d7 as z,pS as zi,tB as zn,FP as zr,pY as zt};
2040
- //# sourceMappingURL=src--OhnhRml.mjs.map
2040
+ //# sourceMappingURL=src-CPA_Jv5y.mjs.map