@inkeep/open-knowledge 0.43.0-beta.6 → 0.43.0-beta.7

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 (114) hide show
  1. package/dist/{acp-harness-probe-lMMnSjqP.mjs → acp-harness-probe-DdhO9SQn.mjs} +2 -2
  2. package/dist/assets/skills/discovery/SKILL.md +1 -1
  3. package/dist/assets/skills/project/SKILL.md +1 -1
  4. package/dist/assets/skills/write-skill/SKILL.md +1 -1
  5. package/dist/cli.mjs +7 -7
  6. package/dist/constants-R-RUm7LH.mjs +2 -0
  7. package/dist/{git-handle-B0U6AD0P.mjs → git-handle-BV2RttjK.mjs} +2 -2
  8. package/dist/git-handle-BeQ4qN_k.mjs +1 -0
  9. package/dist/index.mjs +1 -1
  10. package/dist/{init-CirugI37.mjs → init-CSRKqDJN.mjs} +3 -3
  11. package/dist/init-SNyPXFWd.mjs +1 -0
  12. package/dist/{launch-json-removal-BZnOXYQ-.mjs → launch-json-removal-CfcsWacd.mjs} +2 -2
  13. package/dist/{loader-C3d0s2-M.mjs → loader-C7FbZaEP.mjs} +2 -2
  14. package/dist/loader-DaB_SHaP.mjs +1 -0
  15. package/dist/md-manager-msnOgYR9.mjs +2 -0
  16. package/dist/{open-browser-BrU96UMi.mjs → open-browser-DDNybrns.mjs} +2 -2
  17. package/dist/parse-worker.mjs +1 -1
  18. package/dist/{preview-BL2u7TEI.mjs → preview-1A9kSGGE.mjs} +2 -2
  19. package/dist/preview-CuzKQov6.mjs +1 -0
  20. package/dist/public/assets/{ActivityModeContent-CZvf7vaT.js → ActivityModeContent-D3C8O_w3.js} +1 -1
  21. package/dist/public/assets/{AgentDiffPane-srNk6utW.js → AgentDiffPane-BvGju1xE.js} +1 -1
  22. package/dist/public/assets/{AgentThreadClientBinder-B_xu_F7T.js → AgentThreadClientBinder-D4H_PDYc.js} +1 -1
  23. package/dist/public/assets/{CodeMirrorPropInput-BkZa8s6u.js → CodeMirrorPropInput-Bl20D0Uk.js} +1 -1
  24. package/dist/public/assets/{DocumentContext-_HmmdzDY.js → DocumentContext-Cdr74ISn.js} +1 -1
  25. package/dist/public/assets/{EditorModeToggle-CYYxR5D6.js → EditorModeToggle-BY6AO_qz.js} +1 -1
  26. package/dist/public/assets/{EnableSyncConfirmDialog-70LUF0BM.js → EnableSyncConfirmDialog-DJMo-qwB.js} +1 -1
  27. package/dist/public/assets/FeedbackForm-Crm9lLX8.js +1 -0
  28. package/dist/public/assets/{GraphPanel-Cpyav3kr.js → GraphPanel-DIO6yakG.js} +1 -1
  29. package/dist/public/assets/{LintConfigEditor-C235lTrG.js → LintConfigEditor-OxVpPRfH.js} +1 -1
  30. package/dist/public/assets/{ManagedArtifactProperties-xdcG7g6i.js → ManagedArtifactProperties-CLs0zXAe.js} +1 -1
  31. package/dist/public/assets/{McpConsentDialogBody-CBP-q0Ps.js → McpConsentDialogBody-CxXXnPDt.js} +1 -1
  32. package/dist/public/assets/{MermaidDocEditor-CBlxkKRh.js → MermaidDocEditor-DmtJmVIV.js} +1 -1
  33. package/dist/public/assets/{PropertyPanel-CyKA9aT3.js → PropertyPanel-DTkAfxY9.js} +1 -1
  34. package/dist/public/assets/{ReportBugDialogBody-BNPoUjQC.js → ReportBugDialogBody-CJmBcRe1.js} +1 -1
  35. package/dist/public/assets/{SchemaConfigEditor-SNtb0-ip.js → SchemaConfigEditor-DTWsipcT.js} +1 -1
  36. package/dist/public/assets/{SettingsDialogBody-BUm5bI4O.js → SettingsDialogBody--7DDTRea.js} +1 -1
  37. package/dist/public/assets/{ShareBranchSwitchDialog-DAdfkMmL.js → ShareBranchSwitchDialog-CHf9euSj.js} +1 -1
  38. package/dist/public/assets/{ShareReceiveDialog-D6W2uERu.js → ShareReceiveDialog-Bhm4sgyN.js} +1 -1
  39. package/dist/public/assets/{ShareReceiveMissDialog-y0j89UFf.js → ShareReceiveMissDialog-C5vtlW7T.js} +1 -1
  40. package/dist/public/assets/{SkillEditorActions-CEwn16Tc.js → SkillEditorActions-WbSFB2E8.js} +1 -1
  41. package/dist/public/assets/{SourceEditor-gJWLMSB0.js → SourceEditor-Bd7F9NS2.js} +1 -1
  42. package/dist/public/assets/{TerminalPanel-B1gBGZxV.js → TerminalPanel-DP8U0P5Y.js} +1 -1
  43. package/dist/public/assets/{TerminalSessionsHost-DzxIw4MP.js → TerminalSessionsHost-CiWsf0Az.js} +2 -2
  44. package/dist/public/assets/{TerminalWindowApp-BHIljFR0.js → TerminalWindowApp-CV4iSFXK.js} +1 -1
  45. package/dist/public/assets/{ThreadView-B-R_hzDk.js → ThreadView-NVvE5q8i.js} +1 -1
  46. package/dist/public/assets/{TimelineDiffPane-Be0SpZDg.js → TimelineDiffPane-CaXJq5G3.js} +1 -1
  47. package/dist/public/assets/{agent-diff-store-L0QRqFhx.js → agent-diff-store-5rFvn02h.js} +1 -1
  48. package/dist/public/assets/{agent-visibility-CL_tNGWg.js → agent-visibility-Dnk83DYS.js} +1 -1
  49. package/dist/public/assets/{auth-state-cache-l1Vfn_MK.js → auth-state-cache-D7ajc9Qr.js} +1 -1
  50. package/dist/public/assets/client-version-DxYAebBl.js +1 -0
  51. package/dist/public/assets/{config-provider-CwPQy5rX.js → config-provider-CPaxPgT-.js} +1 -1
  52. package/dist/public/assets/{dist-CuWeCBEf.js → dist-Buo04VFd.js} +1 -1
  53. package/dist/public/assets/{doc-hash-BVKebTVG.js → doc-hash-SvezN6Rq.js} +1 -1
  54. package/dist/public/assets/{documents-events-B5wmrm16.js → documents-events-dEUha72t.js} +1 -1
  55. package/dist/public/assets/{file-tree-adapter-yYBioQs5.js → file-tree-adapter-iop4fdHa.js} +1 -1
  56. package/dist/public/assets/{file-tree-utils-DfqWA_5n.js → file-tree-utils-CFhkdQEq.js} +1 -1
  57. package/dist/public/assets/{globals-DwTVKVQU.css → globals-B1VH9dVh.css} +1 -1
  58. package/dist/public/assets/{index-hiHNx_VS.js → index-fFZmLpuY.js} +7 -7
  59. package/dist/public/assets/{lint-config-client-5R8jfpMC.js → lint-config-client-CxiCF4DX.js} +1 -1
  60. package/dist/public/assets/{markdownlint-rule-browser-B10BhLO-.js → markdownlint-rule-browser-C38r_8F1.js} +1 -1
  61. package/dist/public/assets/{navigation-targets-CHJwvlLn.js → navigation-targets-BRUFNxdH.js} +1 -1
  62. package/dist/public/assets/{open-managed-artifact-tab-DU2wriss.js → open-managed-artifact-tab--dyTqqlT.js} +1 -1
  63. package/dist/public/assets/{pending-receive-nav-store-vEz7n7hI.js → pending-receive-nav-store-BglLdOwd.js} +1 -1
  64. package/dist/public/assets/{prop-types-BKQrBeTE.js → prop-types-DOS9ukZA.js} +1 -1
  65. package/dist/public/assets/{receive-store-Cai4Ylv2.js → receive-store-C9LkmGjP.js} +1 -1
  66. package/dist/public/assets/{selection-context-BfNuCyz7.js → selection-context-BlON5dXS.js} +1 -1
  67. package/dist/public/assets/{skill-actions-CqHp5fhi.js → skill-actions-DVtgKFDb.js} +1 -1
  68. package/dist/public/assets/{skills-api-CakWD1yl.js → skills-api-OnwTD-gx.js} +1 -1
  69. package/dist/public/assets/{src-CzOcS7Os.js → src-Bla2VWV9.js} +1 -1
  70. package/dist/public/assets/{tag-pill-input-DrBsmU2V.js → tag-pill-input-C71zF3_V.js} +1 -1
  71. package/dist/public/assets/{target-navigation-intent-BvA7kyRG.js → target-navigation-intent-Ckw_zIOm.js} +1 -1
  72. package/dist/public/assets/{telemetry-impl-Bl_U4MrE.js → telemetry-impl-llHFvtad.js} +1 -1
  73. package/dist/public/assets/{telemetry-startup-DXlGUC0d.js → telemetry-startup-Ce8-_9qU.js} +1 -1
  74. package/dist/public/assets/{terminal-launch-events-C02gKY4p.js → terminal-launch-events-BCvN0vmT.js} +1 -1
  75. package/dist/public/assets/{terminal-telemetry-WPPXmVH6.js → terminal-telemetry-aybtUvXL.js} +1 -1
  76. package/dist/public/assets/{typing-burst-detector-BGhFSaCK.js → typing-burst-detector-B0tlkeuP.js} +1 -1
  77. package/dist/public/assets/{uninstall-CjMD-IxK.js → uninstall-ClvMa9lt.js} +1 -1
  78. package/dist/public/assets/{use-activity-panel-DoDwyzOZ.js → use-activity-panel-BCV49rp2.js} +1 -1
  79. package/dist/public/assets/{use-apply-config-color-theme-0KmFjCFT.js → use-apply-config-color-theme-2eJGLg4E.js} +1 -1
  80. package/dist/public/assets/{use-collab-url-DQjlkOUP.js → use-collab-url-CMrtW1hJ.js} +1 -1
  81. package/dist/public/assets/{use-live-xterm-theme-CM3UGTWm.js → use-live-xterm-theme-XwgkaK_f.js} +1 -1
  82. package/dist/public/assets/{use-settings-route-0Taj5Wwx.js → use-settings-route-7y0-KX-u.js} +1 -1
  83. package/dist/public/assets/{use-terminal-enabled-BTOXFzup.js → use-terminal-enabled-DEK3ggum.js} +1 -1
  84. package/dist/public/assets/{use-timeline-entry-diff-DFXSuMB3.js → use-timeline-entry-diff-DyYICR11.js} +1 -1
  85. package/dist/public/assets/{use-workspace-D2do84a0.js → use-workspace-DzRZ3d5B.js} +1 -1
  86. package/dist/public/assets/{workspace-paths-hoX5L8bW.js → workspace-paths-DgaXFkO5.js} +1 -1
  87. package/dist/public/index.html +37 -37
  88. package/dist/public/uninstall.html +4 -4
  89. package/dist/{repair-launch-json-DR9LNeHq.mjs → repair-launch-json-CoyH_Fg4.mjs} +2 -2
  90. package/dist/{repair-mcp-configs-D-W0Trir.mjs → repair-mcp-configs-C3AcKIaG.mjs} +2 -2
  91. package/dist/repair-skills-BbxNdXSs.mjs +1 -0
  92. package/dist/{repair-skills-D8zfBuEH.mjs → repair-skills-DoTJZ9g0.mjs} +2 -2
  93. package/dist/{server-lock-Dvu9Crm-.mjs → server-lock-C4qH3g-P.mjs} +2 -2
  94. package/dist/server-lock-CACUewto.mjs +1 -0
  95. package/dist/{src-DTzbBBWG.mjs → src-7dzK48Dw.mjs} +2 -2
  96. package/dist/{src-B-HV6HNi.mjs → src-Bl6FSa1U.mjs} +1 -1
  97. package/dist/{src-CMWx7wd8.mjs → src-CepmZgB5.mjs} +4 -4
  98. package/dist/{src-DRjy7jah.mjs → src-D5f9ThMD.mjs} +2 -2
  99. package/dist/start-DnI6DsO5.mjs +1 -0
  100. package/dist/{start-BmMsXVx3.mjs → start-m_7Q1P4t.mjs} +3 -3
  101. package/dist/{write-project-skill--6mgOtCu.mjs → write-project-skill-C7z5m6Zc.mjs} +2 -2
  102. package/package.json +4 -4
  103. package/dist/constants-DI_gr5ih.mjs +0 -2
  104. package/dist/git-handle-CAmPAeqb.mjs +0 -1
  105. package/dist/init-CxiSUQf2.mjs +0 -1
  106. package/dist/loader-BbtvxjVj.mjs +0 -1
  107. package/dist/md-manager-CSd1MWq_.mjs +0 -2
  108. package/dist/preview-CPdu4CHM.mjs +0 -1
  109. package/dist/public/assets/FeedbackForm-Dpnyx8Bz.js +0 -1
  110. package/dist/public/assets/client-version-D6r-zu-F.js +0 -1
  111. package/dist/repair-skills-Z6x_KZdO.mjs +0 -1
  112. package/dist/server-lock-PrjHr5-L.mjs +0 -1
  113. package/dist/start-Ca3be5dp.mjs +0 -1
  114. /package/dist/public/assets/{globals-BrJQliEr.js → globals-CdwCpkXl.js} +0 -0
@@ -1,4 +1,4 @@
1
- import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$a as i,$i as a,$n as o,$r as s,$t as c,A as l,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Co as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Do as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Eo as ue,Er as de,Et as fe,F as pe,Fa as me,Fi as he,Fn as ge,Fr as _e,Ft as ve,G as ye,Ga as be,Gi as xe,Gn as Se,Gr as Ce,Gt as we,H as Te,Hi as Ee,Hn as De,Hr as Oe,Ht as ke,Ia as Ae,Ii as je,In as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ka as He,Ki as Ue,Kn as We,Kr as Ge,Kt as Ke,Li as qe,Ln as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mr as tt,Mt as nt,N as rt,Na as it,Ni as at,Nn as ot,Nr as st,Nt as ct,O as T,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,Pa as ht,Pi as gt,Pn as _t,Pr as vt,Pt as yt,Q as bt,Qi as xt,Qn as St,Qr as eee,Qt as tee,R as Ct,Ra as wt,Ri as Tt,Rn as Et,Rr as Dt,Rt as Ot,S as kt,Sa as At,Si as jt,Sn as nee,Sr as Mt,St as Nt,T as Pt,Ta as Ft,Ti as It,Tn as Lt,To as Rt,Tr as zt,Tt as Bt,U as Vt,Ua as Ht,Ui as Ut,Un as Wt,Ur as Gt,Ut as Kt,V as qt,Vi as Jt,Vn as Yt,Vr as Xt,Vt as Zt,W as Qt,Wa as $t,Wi as en,Wn as tn,Wr as nn,Wt as rn,X as an,Xa as on,Xi as sn,Xn as ree,Xr as cn,Xt as ln,Y as un,Ya as dn,Yi as fn,Yn as pn,Yr as mn,Yt as hn,Z as gn,Za as _n,Zi as vn,Zn as yn,Zr as bn,Zt as xn,_ as Sn,_a as Cn,_i as wn,_n as Tn,_o as En,_r as Dn,_t as On,a as kn,aa as An,ai as jn,an as Mn,ao as Nn,ar as Pn,at as Fn,b as In,bi as Ln,bn as Rn,bo as zn,br as Bn,bt as Vn,c as Hn,ca as Un,ci as Wn,cn as Gn,co as Kn,cr as iee,ct as qn,d as Jn,da as aee,di as Yn,dn as Xn,do as Zn,dr as oee,dt as Qn,ea as $n,ei as er,en as tr,eo as nr,er as rr,et as ir,f as ar,fa as or,fi as sr,fn as cr,fo as lr,fr as ur,g as dr,ga as fr,gi as pr,gn as mr,go as hr,gr,gt as _r,h as vr,ha as yr,hi as br,hn as xr,ho as Sr,hr as Cr,ht as wr,i as Tr,ia as Er,ii as Dr,in as Or,io as kr,ir as Ar,it as jr,j as Mr,ja as Nr,ji as Pr,jn as Fr,jr as Ir,jt as Lr,k as Rr,ki as zr,kn as Br,ko as Vr,kr as Hr,kt as Ur,l as Wr,la as Gr,li as Kr,ln as qr,lo as Jr,lr as Yr,lt as Xr,m as Zr,mi as Qr,mn as $r,mo as ei,mr as ti,mt as ni,n as ri,na as ii,ni as ai,nn as oi,no as si,nr as ci,nt as li,o as ui,oa as di,oi as fi,on as pi,oo as mi,or as hi,ot as gi,pa as _i,pi as vi,pn as yi,po as bi,pr as xi,q as Si,qa as Ci,qi as see,qn as cee,qr as lee,qt as uee,r as wi,ra as dee,ri as Ti,rn as fee,ro as Ei,rr as Di,rt as Oi,s as ki,sa as Ai,si as ji,sn as Mi,so as Ni,sr as Pi,st as Fi,t as Ii,ta as Li,ti as Ri,tn as zi,to as Bi,tr as Vi,tt as Hi,u as Ui,ua as Wi,ui as Gi,un as Ki,uo as qi,ur as Ji,ut as Yi,v as Xi,vi as Zi,vn as Qi,vr as pee,vt as $i,w as mee,wa as ea,wi as hee,wn as gee,wo as ta,wr as na,wt as ra,x as ia,xi as _ee,xn as aa,xr as oa,xt as sa,y as ca,ya as la,yi as ua,yn as da,yr as fa,yt as pa,z as ma,zi as ha,zn as ga,zr as _a,zt as va}from"./src-DRjy7jah.mjs";import{$ as ya,At as ba,B as xa,C as Sa,Ct as Ca,Dt as wa,E as Ta,Et as Ea,G as Da,H as Oa,I as ka,J as Aa,K as ja,Mt as Ma,N as Na,Nt as Pa,Ot as Fa,Pt as Ia,Q as La,S as Ra,T as za,Tt as Ba,V as Va,W as Ha,Y as Ua,Z as Wa,_ as Ga,_t as E,at as Ka,bt as qa,ct as D,dt as O,ft as Ja,g as Ya,gt as k,h as Xa,ht as A,i as Za,it as Qa,jt as $a,kt as eo,l as to,lt as no,m as ro,mt as j,n as io,nt as M,ot as ao,pt as oo,r as so,rt as co,t as lo,tt as N,u as uo,ut as P,v as fo,vt as po,w as mo,wt as ho,yt as go,z as _o}from"./sleep-DDnWCWup.mjs";import{c as vo,i as yo,l as bo,n as xo,s as So}from"./esm-CItKw7Y6.mjs";import{n as Co,t as wo}from"./md-manager-CSd1MWq_.mjs";import{A as To,C as Eo,D as Do,E as Oo,N as ko,O as Ao,S as jo,T as Mo,_ as No,a as Po,b as Fo,c as Io,d as Lo,f as Ro,g as zo,h as Bo,i as Vo,j as Ho,k as Uo,l as Wo,m as Go,n as Ko,o as qo,p as Jo,r as Yo,s as Xo,t as Zo,u as Qo,v as $o,w as es,x as ts,y as ns}from"./fs-traced-DDm-belY.mjs";import{D as vee,E as yee,S as rs,T as bee,a as is,b as as,l as os,p as ss,r as F,s as cs,x as ls,y as us}from"./logger-B7Z8XO-z.mjs";import{a as ds,i as fs,o as ps,r as ms,s as hs,t as gs}from"./git-handle-B0U6AD0P.mjs";import{S as _s,a as vs,b as xee,c as ys,d as bs,f as xs,g as Ss,h as Cs,i as ws,l as Ts,m as Es,n as Ds,r as Os,x as ks,y as As}from"./server-lock-Dvu9Crm-.mjs";import{t as js}from"./libesm-DzwC_yFw.mjs";import{n as Ms,t as Ns}from"./build-DYQrG4v7.mjs";import{t as Ps}from"./yazl-BafwB467.mjs";import{t as Fs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Is,c as Ls,d as Rs,f as zs,h as Bs,i as Vs,l as Hs,m as Us,n as Ws,o as Gs,p as Ks,r as qs,s as Js,t as Ys,u as Xs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Zs,B as Qs,C as $s,D as ec,E as tc,F as nc,H as rc,I as ic,L as ac,M as oc,N as sc,O as cc,P as lc,S as uc,T as dc,V as fc,_ as pc,a as mc,b as hc,c as gc,d as _c,f as vc,g as yc,h as bc,i as xc,j as Sc,k as Cc,l as wc,m as Tc,n as Ec,o as Dc,p as Oc,r as kc,s as Ac,t as jc,u as Mc,v as Nc,w as Pc,x as Fc,y as Ic,z as Lc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Rc,c as zc,d as Bc,i as Vc,l as Hc,n as Uc,o as Wc,r as Gc,s as Kc,t as qc,u as Jc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Yc,r as Xc,t as Zc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as Qc}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as $c}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as el,t as tl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as nl,t as rl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as il,r as al,t as ol}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as sl,t as cl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as ll}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as ul}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as dl}from"./wrapper-BcpqREsI.mjs";import{createRequire as fl}from"node:module";import{execFile as pl,spawn as ml,spawnSync as hl}from"node:child_process";import*as gl from"node:path";import{basename as _l,delimiter as vl,dirname as I,extname as yl,isAbsolute as bl,join as L,normalize as xl,posix as Sl,relative as R,resolve as z,sep as Cl,win32 as wl}from"node:path";import*as Tl from"node:fs";import{appendFileSync as El,chmodSync as Dl,closeSync as Ol,constants as kl,createReadStream as Al,createWriteStream as jl,existsSync as B,lstatSync as Ml,mkdirSync as Nl,mkdtempSync as Pl,openSync as Fl,readFile as Il,readFileSync as V,readSync as Ll,readdirSync as Rl,readlinkSync as zl,realpathSync as Bl,renameSync as Vl,rmSync as Hl,rmdirSync as Ul,statSync as Wl,unlinkSync as Gl,writeFileSync as Kl,writeSync as ql}from"node:fs";import{arch as Jl,availableParallelism as Yl,homedir as Xl,hostname as Zl,platform as Ql,tmpdir as $l}from"node:os";import{access as eu,chmod as tu,constants as nu,lstat as ru,readFile as iu,readdir as au,realpath as ou,stat as su,writeFile as See}from"node:fs/promises";import{Readable as cu,Transform as Cee,Writable as wee}from"node:stream";import{URLSearchParams as Tee,fileURLToPath as lu,pathToFileURL as Eee}from"node:url";import uu,{createHash as du,randomUUID as fu,webcrypto as pu}from"node:crypto";import Dee from"crypto";import{Readable as mu}from"stream";import{Worker as Oee}from"node:worker_threads";import{monitorEventLoopDelay as kee,performance as hu}from"node:perf_hooks";import{createInterface as Aee}from"node:readline";import{pipeline as gu}from"node:stream/promises";import{setTimeout as _u}from"node:timers/promises";import{promisify as vu}from"node:util";import{lookup as jee}from"node:dns/promises";import{request as Mee}from"node:http";import{request as Nee}from"node:https";import{createBrotliDecompress as Pee,createGunzip as Fee,createInflate as Iee}from"node:zlib";import{Http2ServerRequest as yu,constants as Lee}from"http2";import{AsyncLocalStorage as Ree}from"node:async_hooks";import{lookup as zee}from"node:dns";import Bee from"node:tls";var bu=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=bl(t)?t:z(this.gitDir,t))}catch(e){if(!wu(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 wu(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]}:Eu(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 wu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Vee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Tu(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(`..`)||bl(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Wee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!wu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return wu(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 Eu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function xu(e){return Cu(z(e),``)}function Su(e){let t=z(e),n=z(Xl());if(t===n)return{kind:`absent`};let r=Cu(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=Cu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Cu(e,t){let n=L(e,`.git`),r;try{r=Wl(n)}catch(e){return wu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new bu(`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=bl(o)?o:z(e,o);try{if(!Wl(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 bu(`linked`,e,t,n,s)}}function Vee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Hee(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=Uee(i[1]);if(a.length>0)return a}return null}function Hee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Uee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function wu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Tu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Wee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Tu(t[1])?{kind:`symbolic`,target:t[1]}:null:Eu(e)?{kind:`oid`,oid:e}:null}function Eu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Gee(e){return`git-author-${Vr(e.trim().toLowerCase())}`}const Kee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Du(e){let t=Su(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 Ou(e){let t=Du(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ku(e){let t=Du(e);switch(t.kind){case`directory`:return z(t.path,Au(t.projectSubPath));case`linked`:if(!B(t.path))throw new ju(t.gitPath,t.path);return z(t.path,Au(t.projectSubPath));case`malformed-pointer`:throw new ju(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Mu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Au(e){return e===``?`ok`:`ok-${qee(e)}`}function qee(e){let t=e.split(Cl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Jee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Jee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var ju=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}},Mu=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 Yee(e){let t;try{t=ku(e)}catch(e){if(e instanceof ju||e instanceof Mu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Nu(e){return`refs/wip/${e}/`}function Xee(e){if(!e)return[];let t=[];for(let n of e.split(`
1
+ import{i as e,o as t,t as n}from"./chunk-DTipWd-i.mjs";import{$ as r,$a as i,$i as a,$n as o,$r as s,$t as c,A as l,Ai as u,An as d,Ar as f,At as p,B as m,Ba as h,Bn as g,Br as _,Bt as v,Ca as y,Ci as b,Cn as x,Co as S,Cr as C,Ct as w,D as ee,Da as te,Di as ne,Dn as re,Do as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Eo as ue,Er as de,Et as fe,F as pe,Fa as me,Fi as he,Fn as ge,Fr as _e,Ft as ve,G as ye,Ga as be,Gi as xe,Gn as Se,Gr as Ce,Gt as we,H as Te,Hi as Ee,Hn as De,Hr as Oe,Ht as ke,Ia as Ae,Ii as je,In as Me,Ir as Ne,It as Pe,J as Fe,Ja as Ie,Ji as Le,Jn as Re,Jr as ze,Jt as Be,K as Ve,Ka as He,Ki as Ue,Kn as We,Kr as Ge,Kt as Ke,Li as qe,Ln as Je,Lr as Ye,Lt as Xe,M as Ze,Ma as Qe,Mi as $e,Mn as et,Mr as tt,Mt as nt,N as rt,Na as it,Ni as at,Nn as ot,Nr as st,Nt as ct,O as T,Oa as lt,Oi as ut,On as dt,Oo as ft,Or as pt,Ot as mt,Pa as ht,Pi as gt,Pn as _t,Pr as vt,Pt as yt,Q as bt,Qi as xt,Qn as St,Qr as eee,Qt as tee,R as Ct,Ra as wt,Ri as Tt,Rn as Et,Rr as Dt,Rt as Ot,S as kt,Sa as At,Si as jt,Sn as nee,Sr as Mt,St as Nt,T as Pt,Ta as Ft,Ti as It,Tn as Lt,To as Rt,Tr as zt,Tt as Bt,U as Vt,Ua as Ht,Ui as Ut,Un as Wt,Ur as Gt,Ut as Kt,V as qt,Vi as Jt,Vn as Yt,Vr as Xt,Vt as Zt,W as Qt,Wa as $t,Wi as en,Wn as tn,Wr as nn,Wt as rn,X as an,Xa as on,Xi as sn,Xn as ree,Xr as cn,Xt as ln,Y as un,Ya as dn,Yi as fn,Yn as pn,Yr as mn,Yt as hn,Z as gn,Za as _n,Zi as vn,Zn as yn,Zr as bn,Zt as xn,_ as Sn,_a as Cn,_i as wn,_n as Tn,_o as En,_r as Dn,_t as On,a as kn,aa as An,ai as jn,an as Mn,ao as Nn,ar as Pn,at as Fn,b as In,bi as Ln,bn as Rn,bo as zn,br as Bn,bt as Vn,c as Hn,ca as Un,ci as Wn,cn as Gn,co as Kn,cr as iee,ct as qn,d as Jn,da as aee,di as Yn,dn as Xn,do as Zn,dr as oee,dt as Qn,ea as $n,ei as er,en as tr,eo as nr,er as rr,et as ir,f as ar,fa as or,fi as sr,fn as cr,fo as lr,fr as ur,g as dr,ga as fr,gi as pr,gn as mr,go as hr,gr,gt as _r,h as vr,ha as yr,hi as br,hn as xr,ho as Sr,hr as Cr,ht as wr,i as Tr,ia as Er,ii as Dr,in as Or,io as kr,ir as Ar,it as jr,j as Mr,ja as Nr,ji as Pr,jn as Fr,jr as Ir,jt as Lr,k as Rr,ki as zr,kn as Br,ko as Vr,kr as Hr,kt as Ur,l as Wr,la as Gr,li as Kr,ln as qr,lo as Jr,lr as Yr,lt as Xr,m as Zr,mi as Qr,mn as $r,mo as ei,mr as ti,mt as ni,n as ri,na as ii,ni as ai,nn as oi,no as si,nr as ci,nt as li,o as ui,oa as di,oi as fi,on as pi,oo as mi,or as hi,ot as gi,pa as _i,pi as vi,pn as yi,po as bi,pr as xi,q as Si,qa as Ci,qi as see,qn as cee,qr as lee,qt as uee,r as wi,ra as dee,ri as Ti,rn as fee,ro as Ei,rr as Di,rt as Oi,s as ki,sa as Ai,si as ji,sn as Mi,so as Ni,sr as Pi,st as Fi,t as Ii,ta as Li,ti as Ri,tn as zi,to as Bi,tr as Vi,tt as Hi,u as Ui,ua as Wi,ui as Gi,un as Ki,uo as qi,ur as Ji,ut as Yi,v as Xi,vi as Zi,vn as Qi,vr as pee,vt as $i,w as mee,wa as ea,wi as hee,wn as gee,wo as ta,wr as na,wt as ra,x as ia,xi as _ee,xn as aa,xr as oa,xt as sa,y as ca,ya as la,yi as ua,yn as da,yr as fa,yt as pa,z as ma,zi as ha,zn as ga,zr as _a,zt as va}from"./src-D5f9ThMD.mjs";import{$ as ya,At as ba,B as xa,C as Sa,Ct as Ca,Dt as wa,E as Ta,Et as Ea,G as Da,H as Oa,I as ka,J as Aa,K as ja,Mt as Ma,N as Na,Nt as Pa,Ot as Fa,Pt as Ia,Q as La,S as Ra,T as za,Tt as Ba,V as Va,W as Ha,Y as Ua,Z as Wa,_ as Ga,_t as E,at as Ka,bt as qa,ct as D,dt as O,ft as Ja,g as Ya,gt as k,h as Xa,ht as A,i as Za,it as Qa,jt as $a,kt as eo,l as to,lt as no,m as ro,mt as j,n as io,nt as M,ot as ao,pt as oo,r as so,rt as co,t as lo,tt as N,u as uo,ut as P,v as fo,vt as po,w as mo,wt as ho,yt as go,z as _o}from"./sleep-DDnWCWup.mjs";import{c as vo,i as yo,l as bo,n as xo,s as So}from"./esm-CItKw7Y6.mjs";import{n as Co,t as wo}from"./md-manager-msnOgYR9.mjs";import{A as To,C as Eo,D as Do,E as Oo,N as ko,O as Ao,S as jo,T as Mo,_ as No,a as Po,b as Fo,c as Io,d as Lo,f as Ro,g as zo,h as Bo,i as Vo,j as Ho,k as Uo,l as Wo,m as Go,n as Ko,o as qo,p as Jo,r as Yo,s as Xo,t as Zo,u as Qo,v as $o,w as es,x as ts,y as ns}from"./fs-traced-DDm-belY.mjs";import{D as vee,E as yee,S as rs,T as bee,a as is,b as as,l as os,p as ss,r as F,s as cs,x as ls,y as us}from"./logger-B7Z8XO-z.mjs";import{a as ds,i as fs,o as ps,r as ms,s as hs,t as gs}from"./git-handle-BV2RttjK.mjs";import{S as _s,a as vs,b as xee,c as ys,d as bs,f as xs,g as Ss,h as Cs,i as ws,l as Ts,m as Es,n as Ds,r as Os,x as ks,y as As}from"./server-lock-C4qH3g-P.mjs";import{t as js}from"./libesm-DzwC_yFw.mjs";import{n as Ms,t as Ns}from"./build-DYQrG4v7.mjs";import{t as Ps}from"./yazl-BafwB467.mjs";import{t as Fs}from"./chunk-B74TABJS-BSazPoW8.mjs";import{a as Is,c as Ls,d as Rs,f as zs,h as Bs,i as Vs,l as Hs,m as Us,n as Ws,o as Gs,p as Ks,r as qs,s as Js,t as Ys,u as Xs}from"./chunk-GFQRA5P5-JJS41DJS.mjs";import{A as Zs,B as Qs,C as $s,D as ec,E as tc,F as nc,H as rc,I as ic,L as ac,M as oc,N as sc,O as cc,P as lc,S as uc,T as dc,V as fc,_ as pc,a as mc,b as hc,c as gc,d as _c,f as vc,g as yc,h as bc,i as xc,j as Sc,k as Cc,l as wc,m as Tc,n as Ec,o as Dc,p as Oc,r as kc,s as Ac,t as jc,u as Mc,v as Nc,w as Pc,x as Fc,y as Ic,z as Lc}from"./chunk-BGSUD5R5-BIZeqUja.mjs";import{a as Rc,c as zc,d as Bc,i as Vc,l as Hc,n as Uc,o as Wc,r as Gc,s as Kc,t as qc,u as Jc}from"./chunk-KX3P26DQ-Di79jFtW.mjs";import{n as Yc,r as Xc,t as Zc}from"./chunk-R6VWJ2ZL-CQWpbRHp.mjs";import{r as Qc}from"./chunk-CWQS3NFK-HnFncXpd.mjs";import{t as $c}from"./chunk-DXB73IDG-q-dGnwlc.mjs";import{n as el,t as tl}from"./chunk-5QMZ5MUS-D8tv8KWc.mjs";import{n as nl,t as rl}from"./chunk-A5O5YHGN-C27iG4wY.mjs";import{n as il,r as al,t as ol}from"./chunk-OJDRYQWQ-CmHyfN6x.mjs";import{r as sl,t as cl}from"./chunk-24IMIIXA-BQtWA2ag.mjs";import{n as ll}from"./chunk-3THT3N7L-DcPtGCSm.mjs";import{t as ul}from"./chunk-44UOCSGV-Dadyg26w.mjs";import{t as dl}from"./wrapper-BcpqREsI.mjs";import{createRequire as fl}from"node:module";import{execFile as pl,spawn as ml,spawnSync as hl}from"node:child_process";import*as gl from"node:path";import{basename as _l,delimiter as vl,dirname as I,extname as yl,isAbsolute as bl,join as L,normalize as xl,posix as Sl,relative as R,resolve as z,sep as Cl,win32 as wl}from"node:path";import*as Tl from"node:fs";import{appendFileSync as El,chmodSync as Dl,closeSync as Ol,constants as kl,createReadStream as Al,createWriteStream as jl,existsSync as B,lstatSync as Ml,mkdirSync as Nl,mkdtempSync as Pl,openSync as Fl,readFile as Il,readFileSync as V,readSync as Ll,readdirSync as Rl,readlinkSync as zl,realpathSync as Bl,renameSync as Vl,rmSync as Hl,rmdirSync as Ul,statSync as Wl,unlinkSync as Gl,writeFileSync as Kl,writeSync as ql}from"node:fs";import{arch as Jl,availableParallelism as Yl,homedir as Xl,hostname as Zl,platform as Ql,tmpdir as $l}from"node:os";import{access as eu,chmod as tu,constants as nu,lstat as ru,readFile as iu,readdir as au,realpath as ou,stat as su,writeFile as See}from"node:fs/promises";import{Readable as cu,Transform as Cee,Writable as wee}from"node:stream";import{URLSearchParams as Tee,fileURLToPath as lu,pathToFileURL as Eee}from"node:url";import uu,{createHash as du,randomUUID as fu,webcrypto as pu}from"node:crypto";import Dee from"crypto";import{Readable as mu}from"stream";import{Worker as Oee}from"node:worker_threads";import{monitorEventLoopDelay as kee,performance as hu}from"node:perf_hooks";import{createInterface as Aee}from"node:readline";import{pipeline as gu}from"node:stream/promises";import{setTimeout as _u}from"node:timers/promises";import{promisify as vu}from"node:util";import{lookup as jee}from"node:dns/promises";import{request as Mee}from"node:http";import{request as Nee}from"node:https";import{createBrotliDecompress as Pee,createGunzip as Fee,createInflate as Iee}from"node:zlib";import{Http2ServerRequest as yu,constants as Lee}from"http2";import{AsyncLocalStorage as Ree}from"node:async_hooks";import{lookup as zee}from"node:dns";import Bee from"node:tls";var bu=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=bl(t)?t:z(this.gitDir,t))}catch(e){if(!wu(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 wu(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]}:Eu(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 wu(e)?{kind:`absent`,reason:`config-missing`}:{kind:`unreadable`,cause:e}}let r=Vee(n,e);return r===null?{kind:`absent`,reason:`remote-missing`}:{kind:`configured`,url:r}}readRef(e){if(!Tu(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(`..`)||bl(r))return{kind:`invalid`};try{let e=V(n,`utf-8`).trim(),t=Wee(e);return t===null?{kind:`malformed`,raw:e}:{kind:`present`,storage:`loose`,value:t}}catch(e){if(!wu(e))return{kind:`unreadable`,cause:e}}let i;try{i=V(L(t.path,`packed-refs`),`utf-8`)}catch(e){return wu(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 Eu(r[0])?{kind:`present`,storage:`packed`,value:{kind:`oid`,oid:r[0]}}:{kind:`malformed`,raw:n}}return{kind:`absent`}}};function xu(e){return Cu(z(e),``)}function Su(e){let t=z(e),n=z(Xl());if(t===n)return{kind:`absent`};let r=Cu(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=Cu(e,R(e,t));if(r.kind!==`absent`)return r;i=e}return{kind:`absent`}}function Cu(e,t){let n=L(e,`.git`),r;try{r=Wl(n)}catch(e){return wu(e)?{kind:`absent`}:{kind:`inaccessible`,gitPath:n,cause:e}}if(r.isDirectory())return{kind:`repository`,repository:new bu(`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=bl(o)?o:z(e,o);try{if(!Wl(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 bu(`linked`,e,t,n,s)}}function Vee(e,t){let n=!1;for(let r of e.split(/\r?\n/)){let e=Hee(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=Uee(i[1]);if(a.length>0)return a}return null}function Hee(e){let t=e.search(/[;#]/);return(t===-1?e:e.slice(0,t)).trim()}function Uee(e){let t=e.trim();return t.startsWith(`"`)&&t.endsWith(`"`)||t.startsWith(`'`)&&t.endsWith(`'`)?t.slice(1,-1):t}function wu(e){let t=e?.code;return t===`ENOENT`||t===`ENOTDIR`}function Tu(e){return e.startsWith(`refs/`)&&!e.includes(`\0`)&&!e.includes(`\\`)&&!e.includes(`..`)&&!e.includes(`//`)&&!e.endsWith(`/`)}function Wee(e){if(e.length===0)return null;let t=/^ref:[ \t]*(refs\/.+)$/.exec(e);return t?Tu(t[1])?{kind:`symbolic`,target:t[1]}:null:Eu(e)?{kind:`oid`,oid:e}:null}function Eu(e){return/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(e)}function Gee(e){return`git-author-${Vr(e.trim().toLowerCase())}`}const Kee=/^(agent-[^/]+|principal-[^/]+|git-author-[^/]+|file-system|git-upstream|openknowledge-service)$/;function Du(e){let t=Su(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 Ou(e){let t=Du(e);return t.kind===`directory`||t.kind===`linked`?t.path:null}function ku(e){let t=Du(e);switch(t.kind){case`directory`:return z(t.path,Au(t.projectSubPath));case`linked`:if(!B(t.path))throw new ju(t.gitPath,t.path);return z(t.path,Au(t.projectSubPath));case`malformed-pointer`:throw new ju(t.gitPath,t.target,{cause:t.cause});case`inaccessible`:throw new Mu(t.gitPath,{cause:t.cause});case`absent`:return z(e,`.git/ok`)}}function Au(e){return e===``?`ok`:`ok-${qee(e)}`}function qee(e){let t=e.split(Cl).join(`-`).replace(/\/+/g,`-`).replace(/[^A-Za-z0-9._-]/g,`_`).replace(/^\.+/,`_`);if(t.length<=64)return t||`sub`;let n=Jee(e).toString(16).padStart(8,`0`);return`${t.slice(0,55)}-${n}`}function Jee(e){let t=5381;for(let n=0;n<e.length;n++)t=t*33+e.charCodeAt(n)>>>0;return t}var ju=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}},Mu=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 Yee(e){let t;try{t=ku(e)}catch(e){if(e instanceof ju||e instanceof Mu)return null;throw e}return B(z(t,`HEAD`))?t:null}function Nu(e){return`refs/wip/${e}/`}function Xee(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 Pu=`ok-actor: `;function Fu(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),`${Pu}${JSON.stringify(i)}`}function Iu(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=Zee(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 Zee(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 Lu(e){if(!e)return null;for(let t of e.split(`
3
3
  `)){let e=t.trim();if(!e.startsWith(Pu))continue;let n;try{n=JSON.parse(e.slice(10))}catch{return null}return typeof n!=`object`||!n?null:Iu(n)}return null}function Ru(e){if(!e)return[];let t=[];for(let n of e.split(`
4
4
  `)){let e=n.trim();if(!e.startsWith(Pu))continue;let r;try{r=JSON.parse(e.slice(10))}catch{continue}if(typeof r!=`object`||!r)continue;let i=Iu(r);i&&t.push(i)}return t}function zu(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 Bu(e){let t=Ru(e);return t.length>0?t.map(zu):Xee(e)}function Vu(e){return e.length===0?`wip: auto-save`:e.length===1?`wip: ${e[0]}`:`wip: ${e.length} docs`}function Hu(e){return`reconcile: ${e}`}function Uu(e,t){return`rollback: ${e} to ${t.slice(0,7)}`}function Wu(e,t){return`park: ${e} -> ${t}`}function Gu(e,t){return`rename: ${e} -> ${t}`}function Ku(e){return`checkpoint: ${e}`}function qu(e,t){return e?`import: from ${e.slice(0,8)}..${t.slice(0,8)}`:`import: initial at ${t.slice(0,8)}`}const Ju=RegExp(`[\\r\\n\\v\\f\\u0085\\u2028\\u2029]`,`g`);function Yu(e){return e.replace(Ju,` `)}function Qee(e,t){let n=Yu(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=Yu(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 Xu(e){return Kee.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 Zu(e){return e.kind??`other`}function Qu(e,t){for(let n of t){let t=e.find(e=>e.kind===n);if(t!==void 0)return t}}var $u=class{filePath;log;grants=null;constructor(e,t){this.filePath=L(e,`acp-permissions.json`),this.log=t}decide(e,t,n){let r=Zu(t),i=Qu(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=Zu(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-CeWo_16n.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 ed=[`claude-acp`,`codex-acp`,`gemini`,`cursor`,`github-copilot-cli`,`opencode`],td={"claude-acp":`claude`,"codex-acp":`codex`,cursor:`cursor`,opencode:`opencode`},nd=`acp-agents.json`,rd=`acp-registry-cache.json`;function id(){let e=Ql(),t=Jl(),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}`}function ad(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 od(e){let t;try{t=JSON.parse(e)}catch{return null}let n=t?.agents;return Array.isArray(n)?n.filter(ad):null}var sd=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=od(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-CeWo_16n.mjs`);await e(this.localDir,{recursive:!0}),await n(L(this.localDir,rd),t)}catch(e){this.log.warn({err:e},`[acp-registry] disk cache write failed`)}return this.memory}catch(e){let t=await this.readDiskCache();if(t!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving disk cache`),this.memory=t,t;if(this.memory!==null)return this.log.warn({err:e},`[acp-registry] CDN unreachable — serving stale memory copy`),this.memory={...this.memory,stale:!0},this.memory;throw e instanceof Error?e:Error(String(e))}}async readDiskCache(){try{let e=od(await iu(L(this.localDir,rd),`utf8`));return e===null?null:{agents:e,fetchedAt:0,stale:!0}}catch{return null}}};async function cd(e,t){let n;try{n=await iu(L(e,nd),`utf8`)}catch{return[]}let r;try{r=JSON.parse(n)}catch(e){return t.warn({err:e},`[acp-registry] ${nd} 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 ${nd} entry`)}return i}const H={initialize:`initialize`,authenticate:`authenticate`,providers_list:`providers/list`,providers_set:`providers/set`,providers_disable:`providers/disable`,session_new:`session/new`,session_load:`session/load`,session_set_mode:`session/set_mode`,session_set_config_option:`session/set_config_option`,session_prompt:`session/prompt`,session_cancel:`session/cancel`,mcp_message:`mcp/message`,session_list:`session/list`,session_delete:`session/delete`,session_fork:`session/fork`,session_resume:`session/resume`,session_close:`session/close`,logout:`logout`,nes_start:`nes/start`,nes_suggest:`nes/suggest`,nes_accept:`nes/accept`,nes_reject:`nes/reject`,nes_close:`nes/close`,document_did_open:`document/didOpen`,document_did_change:`document/didChange`,document_did_close:`document/didClose`,document_did_save:`document/didSave`,document_did_focus:`document/didFocus`},ld={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`},ud={cancel_request:`$/cancel_request`},dd=Symbol(`skippedItem`);function U(e,t){return e.catch(t)}function fd(e,t){let n=e.catch(t);return E().transform((e,t)=>e===void 0?(t.addIssue({code:`custom`,message:`Required value is missing`}),Ia):n.parse(e))}function pd(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=pd(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 hd(e,t,n){return E().transform((r,i)=>{let a=e.safeParse(r);if(!a.success){for(let e of a.error.issues)i.addIssue({...e,input:r});return Ia}let o=a.data,s=pd(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 gd(e){return N(e.catch(dd)).transform(e=>e.filter(e=>e!==dd))}const _d=k([P(),A()]).nullable(),vd=A(),yd=O({sessionId:vd,path:A(),content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),bd=O({sessionId:vd,path:A(),line:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),limit:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xd=A(),Sd=k([D(`read`),D(`edit`),D(`delete`),D(`move`),D(`search`),D(`execute`),D(`think`),D(`fetch`),D(`switch_mode`),D(`other`)]),Cd=k([D(`pending`),D(`in_progress`),D(`completed`),D(`failed`)]),wd=O({audience:U(gd(k([D(`assistant`),D(`user`)])).nullish(),()=>void 0),lastModified:U(A().nullish(),()=>void 0),priority:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Td=O({annotations:U(wd.nullish(),()=>void 0),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ed=O({annotations:U(wd.nullish(),()=>void 0),data:A(),mimeType:A(),uri:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Dd=O({annotations:U(wd.nullish(),()=>void 0),data:A(),mimeType:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Od=O({annotations:U(wd.nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),mimeType:U(A().nullish(),()=>void 0),name:A(),size:U(P().nullish(),()=>void 0),title:U(A().nullish(),()=>void 0),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),kd=k([O({mimeType:U(A().nullish(),()=>void 0),text:A(),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),O({blob:A(),mimeType:U(A().nullish(),()=>void 0),uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)})]),Ad=O({annotations:U(wd.nullish(),()=>void 0),resource:kd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),jd=k([Td.and(O({type:D(`text`)})),Ed.and(O({type:D(`image`)})),Dd.and(O({type:D(`audio`)})),Od.and(O({type:D(`resource_link`)})),Ad.and(O({type:D(`resource`)}))]),Md=O({content:jd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Nd=O({path:A(),oldText:U(A().nullish(),()=>void 0),newText:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pd=A(),$ee=O({terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Fd=k([Md.and(O({type:D(`content`)})),Nd.and(O({type:D(`diff`)})),$ee.and(O({type:D(`terminal`)}))]),Id=O({path:A(),line:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ld=O({toolCallId:xd,kind:U(Sd.nullish(),()=>void 0),status:U(Cd.nullish(),()=>void 0),title:U(A().nullish(),()=>void 0),content:U(gd(Fd).nullish(),()=>void 0),locations:U(gd(Id).nullish(),()=>void 0),rawInput:U(E().optional(),()=>void 0),rawOutput:U(E().optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rd=A(),ete=k([D(`allow_once`),D(`allow_always`),D(`reject_once`),D(`reject_always`)]),zd=O({sessionId:vd,toolCall:Ld,options:N(O({optionId:Rd,name:A(),kind:ete,_meta:U(j(A(),E()).nullish(),()=>void 0)})),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bd=O({name:A(),value:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vd=O({sessionId:vd,command:A(),args:U(gd(A()).optional(),()=>[]),env:U(gd(Bd).optional(),()=>[]),cwd:U(A().nullish(),()=>void 0),outputByteLimit:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hd=O({sessionId:vd,terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ud=O({sessionId:vd,terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wd=O({sessionId:vd,terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gd=O({sessionId:vd,terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kd=O({sessionId:vd,toolCallId:U(xd.nullish(),()=>void 0)}),qd=O({requestId:_d}),Jd=D(`object`),Yd=k([D(`email`),D(`uri`),D(`date`),D(`date-time`)]),Xd=O({const:A(),title:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Zd=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minLength:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),maxLength:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),pattern:A().nullish(),format:Yd.nullish(),default:U(A().nullish(),()=>void 0),enum:N(A()).nullish(),oneOf:N(Xd).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qd=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),$d=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minimum:P().nullish(),maximum:P().nullish(),default:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ef=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),default:U(M().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),tf=O({enum:N(A()),_meta:U(j(A(),E()).nullish(),()=>void 0)}),nf=O({anyOf:N(Xd),_meta:U(j(A(),E()).nullish(),()=>void 0)}),rf=hd(k([tf.and(O({type:D(`string`)})),md(O({type:A()}),`type`,[`string`]),nf]),`type`,[`string`]),af=O({title:U(A().nullish(),()=>void 0),description:U(A().nullish(),()=>void 0),minItems:P().nullish(),maxItems:P().nullish(),items:rf,default:U(gd(A()).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),of=hd(k([Zd.and(O({type:D(`string`)})),Qd.and(O({type:D(`number`)})),$d.and(O({type:D(`integer`)})),ef.and(O({type:D(`boolean`)})),af.and(O({type:D(`array`)})),md(O({type:A()}),`type`,[`array`,`boolean`,`integer`,`number`,`string`])]),`type`,[`array`,`boolean`,`integer`,`number`,`string`]),sf=O({type:U(Jd.optional().default(`object`),()=>`object`),title:U(A().nullish(),()=>void 0),properties:j(A(),of).optional().default({}),required:N(A()).nullish(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),cf=ao(k([Kd,qd]),O({requestedSchema:sf})),lf=A(),uf=ao(k([Kd,qd]),O({elicitationId:lf,url:po()})),df=hd(ao(k([cf.and(O({mode:D(`form`)})),uf.and(O({mode:D(`url`)})),md(ao(k([Kd,qd]),O({mode:A()})),`mode`,[`form`,`url`])]),O({message:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)})),`mode`,[`form`,`url`]),ff=A(),pf=O({serverId:ff,_meta:U(j(A(),E()).nullish(),()=>void 0)}),mf=A(),hf=O({connectionId:mf,method:A(),params:j(A(),E()).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),gf=O({connectionId:mf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),_f=E();O({id:_d,method:A(),params:k([yd,bd,zd,Vd,Hd,Ud,Wd,Gd,df,pf,hf,gf,_f]).nullish()});const vf=Ka().gte(0).lte(65535),yf=O({image:U(M().optional().default(!1),()=>!1),audio:U(M().optional().default(!1),()=>!1),embeddedContext:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),bf=O({http:U(M().optional().default(!1),()=>!1),sse:U(M().optional().default(!1),()=>!1),acp:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),wf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Tf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),tte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),nte=O({list:U(xf.nullish(),()=>void 0),delete:U(Sf.nullish(),()=>void 0),additionalDirectories:U(Cf.nullish(),()=>void 0),fork:U(wf.nullish(),()=>void 0),resume:U(Tf.nullish(),()=>void 0),close:U(tte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),rte=O({logout:U(O({_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ite=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),ate=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),ote=O({syncKind:k([D(`full`),D(`incremental`)]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ste=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),cte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),lte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),ute=O({document:U(O({didOpen:U(ate.nullish(),()=>void 0),didChange:U(ote.nullish(),()=>void 0),didClose:U(ste.nullish(),()=>void 0),didSave:U(cte.nullish(),()=>void 0),didFocus:U(lte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),dte=O({maxCount:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),fte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),pte=O({maxCount:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),mte=O({maxCount:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),hte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),gte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ef=O({recentFiles:U(dte.nullish(),()=>void 0),relatedSnippets:U(fte.nullish(),()=>void 0),editHistory:U(pte.nullish(),()=>void 0),userActions:U(mte.nullish(),()=>void 0),openFiles:U(hte.nullish(),()=>void 0),diagnostics:U(gte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Df=O({events:U(ute.nullish(),()=>void 0),context:U(Ef.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Of=k([D(`utf-16`),D(`utf-32`),D(`utf-8`)]),kf=O({loadSession:U(M().optional().default(!1),()=>!1),promptCapabilities:U(yf.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:U(bf.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:U(nte.optional().default({}),()=>({})),auth:U(rte.optional().default({}),()=>({})),providers:U(ite.nullish(),()=>void 0),nes:U(Df.nullish(),()=>void 0),positionEncoding:U(Of.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Af=A(),jf=O({name:A(),label:U(A().nullish(),()=>void 0),secret:U(M().optional().default(!0),()=>!0),optional:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mf=O({id:Af,name:A(),description:U(A().nullish(),()=>void 0),vars:fd(gd(jf),()=>[]),link:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Nf=O({id:Af,name:A(),description:U(A().nullish(),()=>void 0),args:U(gd(A()).optional(),()=>[]),env:U(j(A(),A()).optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pf=O({id:Af,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ff=k([Mf.and(O({type:D(`env_var`)})),Nf.and(O({type:D(`terminal`)})),Pf]),If=O({name:A(),title:U(A().nullish(),()=>void 0),version:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Lf=O({protocolVersion:vf,agentCapabilities:U(kf.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:U(gd(Ff).optional().default([]),()=>[]),agentInfo:U(If.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),zf=A(),Bf=k([D(`anthropic`),D(`openai`),D(`azure`),D(`vertex`),D(`bedrock`),A()]),Vf=O({apiType:Bf,baseUrl:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hf=O({providers:N(O({providerId:zf,supported:fd(gd(Bf),()=>[]),required:M(),current:Vf.nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)})),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Uf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gf=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kf=A(),qf=O({currentModeId:Kf,availableModes:fd(gd(O({id:Kf,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Jf=A(),Yf=k([D(`mode`),D(`model`),D(`model_config`),D(`thought_level`),A()]),Xf=A(),Zf=O({value:Xf,name:A(),description:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qf=O({group:A(),name:A(),options:fd(gd(Zf),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),$f=O({currentValue:Xf,options:k([N(Zf),N(Qf)])}),ep=O({currentValue:M()}),tp=ao(k([$f.and(O({type:D(`select`)})),ep.and(O({type:D(`boolean`)}))]),O({id:Jf,name:A(),description:U(A().nullish(),()=>void 0),category:U(Yf.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),np=O({sessionId:vd,modes:U(qf.nullish(),()=>void 0),configOptions:U(gd(tp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),rp=O({modes:U(qf.nullish(),()=>void 0),configOptions:U(gd(tp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ip=O({sessions:fd(gd(O({sessionId:vd,cwd:A(),additionalDirectories:U(gd(A()).optional(),()=>[]),title:U(A().nullish(),()=>void 0),updatedAt:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),nextCursor:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ap=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),op=O({sessionId:vd,modes:U(qf.nullish(),()=>void 0),configOptions:U(gd(tp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),sp=O({modes:U(qf.nullish(),()=>void 0),configOptions:U(gd(tp).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),cp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),lp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),up=O({configOptions:fd(gd(tp),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),dp=O({stopReason:k([D(`end_turn`),D(`max_tokens`),D(`max_turn_requests`),D(`refusal`),D(`cancelled`)]),usage:U(O({totalTokens:P(),inputTokens:P(),outputTokens:P(),thoughtTokens:U(P().nullish(),()=>void 0),cachedReadTokens:U(P().nullish(),()=>void 0),cachedWriteTokens:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),fp=O({sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),pp=A(),mp=O({line:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),character:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),_meta:U(j(A(),E()).nullish(),()=>void 0)}),hp=O({start:mp,end:mp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),gp=O({range:hp,newText:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_p=O({id:pp,uri:A(),edits:N(gp),cursorPosition:U(mp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),vp=O({id:pp,uri:A(),position:mp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),yp=O({id:pp,uri:A(),position:mp,newName:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),bp=O({id:pp,uri:A(),search:A(),replace:A(),isRegex:M().nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xp=O({suggestions:N(k([_p.and(O({kind:D(`edit`)})),vp.and(O({kind:D(`jump`)})),yp.and(O({kind:D(`rename`)})),bp.and(O({kind:D(`searchAndReplace`)}))])),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cp=E(),wp=E(),Tp=O({code:k([D(-32700),D(-32600),D(-32601),D(-32602),D(-32603),D(-32800),D(-32e3),D(-32002),Ka().min(-2147483648,{error:`Invalid value: Expected int32 to be >= -2147483648`}).max(2147483647,{error:`Invalid value: Expected int32 to be <= 2147483647`})]),message:A(),data:U(E().optional(),()=>void 0)});k([O({id:_d,result:k([Lf,Rf,Hf,Uf,Wf,Gf,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,xp,Sp,Cp,wp])}),O({id:_d,error:Tp})]);const Ep=O({content:jd,messageId:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Dp=O({toolCallId:xd,title:A(),kind:U(Sd.optional(),()=>void 0),status:U(Cd.optional(),()=>void 0),content:U(gd(Fd).optional(),()=>[]),locations:U(gd(Id).optional(),()=>[]),rawInput:U(E().optional(),()=>void 0),rawOutput:U(E().optional(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Op=k([D(`high`),D(`medium`),D(`low`)]),kp=k([D(`pending`),D(`in_progress`),D(`completed`)]),Ap=O({content:A(),priority:Op,status:kp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),jp=O({entries:fd(gd(Ap),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mp=A(),Np=O({planId:Mp,entries:fd(gd(Ap),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pp=O({planId:Mp,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Fp=O({planId:Mp,content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ip=O({plan:k([Np.and(O({type:D(`items`)})),Pp.and(O({type:D(`file`)})),Fp.and(O({type:D(`markdown`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Lp=O({planId:Mp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rp=O({hint:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),zp=O({availableCommands:fd(gd(O({name:A(),description:A(),input:U(Rp.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)})),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bp=O({currentModeId:Kf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Vp=O({configOptions:fd(gd(tp),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Hp=O({title:U(A().nullish(),()=>void 0),updatedAt:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Up=O({amount:P(),currency:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Wp=O({used:P(),size:P(),cost:U(Up.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Gp=O({sessionId:vd,update:k([Ep.and(O({sessionUpdate:D(`user_message_chunk`)})),Ep.and(O({sessionUpdate:D(`agent_message_chunk`)})),Ep.and(O({sessionUpdate:D(`agent_thought_chunk`)})),Dp.and(O({sessionUpdate:D(`tool_call`)})),Ld.and(O({sessionUpdate:D(`tool_call_update`)})),jp.and(O({sessionUpdate:D(`plan`)})),Ip.and(O({sessionUpdate:D(`plan_update`)})),Lp.and(O({sessionUpdate:D(`plan_removed`)})),zp.and(O({sessionUpdate:D(`available_commands_update`)})),Bp.and(O({sessionUpdate:D(`current_mode_update`)})),Vp.and(O({sessionUpdate:D(`config_option_update`)})),Hp.and(O({sessionUpdate:D(`session_info_update`)})),Wp.and(O({sessionUpdate:D(`usage_update`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Kp=O({elicitationId:lf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),qp=O({connectionId:mf,method:A(),params:U(j(A(),E()).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Jp=E();O({method:A(),params:k([Gp,Kp,qp,Jp]).nullish()});const Yp=O({readTextFile:U(M().optional().default(!1),()=>!1),writeTextFile:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Xp=O({configOptions:U(O({boolean:U(O({_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Zp=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Qp=O({terminal:U(M().optional().default(!1),()=>!1),_meta:U(j(A(),E()).nullish(),()=>void 0)}),$p=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),em=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),tm=O({form:U($p.nullish(),()=>void 0),url:U(em.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),nm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),rm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),im=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),am=O({jump:U(nm.nullish(),()=>void 0),rename:U(rm.nullish(),()=>void 0),searchAndReplace:U(im.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),om=O({protocolVersion:vf,clientCapabilities:U(O({fs:U(Yp.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:U(M().optional().default(!1),()=>!1),session:U(Xp.nullish(),()=>void 0),plan:U(Zp.nullish(),()=>void 0),auth:U(Qp.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:U(tm.nullish(),()=>void 0),nes:U(am.nullish(),()=>void 0),positionEncodings:U(gd(Of).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}).optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:U(If.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),sm=O({methodId:Af,_meta:U(j(A(),E()).nullish(),()=>void 0)}),cm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),lm=O({providerId:zf,apiType:Bf,baseUrl:A(),headers:j(A(),A()).optional(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),um=O({providerId:zf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),dm=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),fm=O({name:A(),value:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),pm=O({name:A(),url:A(),headers:N(fm),_meta:U(j(A(),E()).nullish(),()=>void 0)}),mm=O({name:A(),url:A(),headers:N(fm),_meta:U(j(A(),E()).nullish(),()=>void 0)}),hm=O({name:A(),serverId:ff,_meta:U(j(A(),E()).nullish(),()=>void 0)}),gm=O({name:A(),command:A(),args:N(A()),env:N(Bd),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_m=k([pm.and(O({type:D(`http`)})),mm.and(O({type:D(`sse`)})),hm.and(O({type:D(`acp`)})),gm]),vm=O({cwd:A(),additionalDirectories:U(gd(A()).optional(),()=>[]),mcpServers:fd(gd(_m),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),ym=O({mcpServers:fd(gd(_m),()=>[]),cwd:A(),additionalDirectories:U(gd(A()).optional(),()=>[]),sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),bm=O({cwd:A().nullish(),cursor:A().nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xm=O({sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Sm=O({sessionId:vd,cwd:A(),additionalDirectories:U(gd(A()).optional(),()=>[]),mcpServers:U(gd(_m).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cm=O({sessionId:vd,cwd:A(),additionalDirectories:U(gd(A()).optional(),()=>[]),mcpServers:U(gd(_m).optional(),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),wm=O({sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Tm=O({sessionId:vd,modeId:Kf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Em=ao(k([O({value:M(),type:D(`boolean`)}),O({value:Xf})]),O({sessionId:vd,configId:Jf,_meta:U(j(A(),E()).nullish(),()=>void 0)})),Dm=O({sessionId:vd,prompt:N(jd),_meta:U(j(A(),E()).nullish(),()=>void 0)}),_te=O({uri:A(),name:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),vte=O({name:A(),owner:A(),remoteUrl:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Om=O({workspaceUri:U(A().nullish(),()=>void 0),workspaceFolders:N(_te).nullish(),repository:U(vte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),yte=k([D(`automatic`),D(`diagnostic`),D(`manual`)]),bte=O({uri:A(),languageId:A(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),xte=O({startLine:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),endLine:Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ste=O({uri:A(),excerpts:N(xte),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Cte=O({uri:A(),diff:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),wte=O({action:A(),uri:A(),position:mp,timestampMs:P(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Tte=O({uri:A(),languageId:A(),visibleRange:U(hp.nullish(),()=>void 0),lastFocusedMs:U(P().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ete=k([D(`error`),D(`warning`),D(`information`),D(`hint`)]),Dte=O({uri:A(),range:hp,severity:Ete,message:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ote=O({recentFiles:N(bte).nullish(),relatedSnippets:N(Ste).nullish(),editHistory:N(Cte).nullish(),userActions:N(wte).nullish(),openFiles:N(Tte).nullish(),diagnostics:N(Dte).nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),km=O({sessionId:vd,uri:A(),version:P(),position:mp,selection:hp.nullish(),triggerKind:yte,context:Ote.nullish(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Am=O({sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)});O({id:_d,method:A(),params:k([om,sm,cm,lm,um,dm,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,hf,_f]).nullish()});const kte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ate=O({content:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),jte=O({optionId:Rd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Mte=O({outcome:k([O({outcome:D(`cancelled`)}),jte.and(O({outcome:D(`selected`)}))]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Nte=O({terminalId:Pd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pte=O({exitCode:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Fte=O({output:A(),truncated:M(),exitStatus:U(Pte.nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Ite=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),Lte=O({exitCode:U(Ka().gte(0).max(4294967295,{error:`Invalid value: Expected uint32 to be <= 4294967295`}).nullish(),()=>void 0),signal:U(A().nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rte=O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),zte=k([A(),P(),P(),M(),N(A())]),jm=O({content:j(A(),zte).nullish()});k([O({id:_d,result:k([kte,Ate,Mte,Nte,Fte,Ite,Lte,Rte,hd(ao(k([jm.and(O({action:D(`accept`)})),O({action:D(`decline`)}),O({action:D(`cancel`)}),md(O({action:A()}),`action`,[`accept`,`cancel`,`decline`])]),O({_meta:U(j(A(),E()).nullish(),()=>void 0)})),`action`,[`accept`,`cancel`,`decline`]),O({connectionId:mf,_meta:U(j(A(),E()).nullish(),()=>void 0)}),O({_meta:U(j(A(),E()).nullish(),()=>void 0)}),wp,Cp])}),O({id:_d,error:Tp})]);const Mm=O({sessionId:vd,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Nm=O({sessionId:vd,uri:A(),languageId:A(),version:P(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Bte=O({range:hp.nullish(),text:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Pm=O({sessionId:vd,uri:A(),version:P(),contentChanges:fd(gd(Bte),()=>[]),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Fm=O({sessionId:vd,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Im=O({sessionId:vd,uri:A(),_meta:U(j(A(),E()).nullish(),()=>void 0)}),Lm=O({sessionId:vd,uri:A(),version:P(),position:mp,visibleRange:hp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),Rm=O({sessionId:vd,id:pp,_meta:U(j(A(),E()).nullish(),()=>void 0)}),zm=O({sessionId:vd,id:pp,reason:U(k([D(`rejected`),D(`ignored`),D(`replaced`),D(`cancelled`)]).nullish(),()=>void 0),_meta:U(j(A(),E()).nullish(),()=>void 0)});O({method:A(),params:k([Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,qp,Jp]).nullish()}),O({requestId:_d,_meta:U(j(A(),E()).nullish(),()=>void 0)}),cf.and(O({mode:D(`form`)})).and(O({message:A()})),uf.and(O({mode:D(`url`)})).and(O({message:A()})),k([Kd,qd]).and(O({message:A()})),Zd.and(O({type:D(`string`)})),Qd.and(O({type:D(`number`)})),$d.and(O({type:D(`integer`)})),ef.and(O({type:D(`boolean`)})),af.and(O({type:D(`array`)})),tf.and(O({type:D(`string`)})),jm.and(O({action:D(`accept`)})),O({action:D(`decline`)}),O({action:D(`cancel`)});const Bm=`$/cancel_request`;function Vm(e){return typeof e==`object`&&!!e}function Vte(e){return e===null||typeof e==`string`||typeof e==`number`&&Number.isFinite(e)}function Hte(e){if(!(!Vm(e)||!Vte(e.requestId)))return e.requestId}const Hm={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};function Um(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Ute(e){if(e instanceof Error||typeof e==`object`&&e&&`message`in e&&typeof e.message==`string`)return e.message}function Wte(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 Wm(e){if(e instanceof qm)return e.toResult();if(Wte(e))return qm.invalidParams(e.format()).toResult();let t=Ute(e);try{return qm.internalError(t?JSON.parse(t):{}).toResult()}catch{return qm.internalError({details:t}).toResult()}}function Gte(e){return e instanceof qm&&e.code===-32800?e:qm.requestCancelled(e)}function Kte(e,t){let n=qte(e,t);return n?n.toResult():Wm(e)}function qte(e,t){if(!(!t.aborted||!Jte(e)))return Gte(t.reason)}function Jte(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.name===`AbortError`||t.code===`ABORT_ERR`}var Yte=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 qm?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?Um(Error(`JSON-RPC request already responded`)):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},Gm=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Xte=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}},Km=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Xte(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 Zte}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 Gm(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return Um(this.closedReason());let i=this.nextRequestId++,a=()=>{},o=new Promise((e,t)=>{let o={resolve:r=>{try{e(n?n(r):r)}catch(e){t(e)}},reject:t};a=()=>{o.cancellationSent||(o.cancellationSent=!0,o.cleanup?.(),this.sendCancelRequest(i).catch(()=>{}))},r.cancellationSignal?.addEventListener(`abort`,a,{once:!0}),o.cleanup=()=>{r.cancellationSignal?.removeEventListener(`abort`,a)},this.pendingResponses.set(i,o)});return o.catch(()=>{}),this.sendMessage({jsonrpc:`2.0`,id:i,method:e,params:t}).catch(()=>{}),r.cancellationSignal?.aborted&&a(),o}sendCancelRequest(e){return this.sendNotification(Bm,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?Um(this.closedReason()):this.sendMessage({jsonrpc:`2.0`,method:e,params:t})}close(e){if(this.abortController.signal.aborted)return;let t=e??Error(`ACP connection closed`);this.abortController.abort(t);for(let e of this.pendingResponses.values())e.cleanup?.(),e.reject(t);this.pendingResponses.clear();for(let e of this.incomingRequests.values())e.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t){this.stream=e,this.staticHandlers=t,this.closedPromise=new Promise(e=>{this.abortController.signal.addEventListener(`abort`,()=>e())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind===`request`){let t=await e(n.method,n.params,r);await n.responder.respond(t)}else await t(n.method,n.params,r);return Hm.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(!Vm(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(qm.methodNotFound(t.method))}catch(n){if(this.abortController.signal.aborted)return;if(t.kind===`request`&&!t.responder.responded)await t.responder.respondWithResult(Kte(n,t.responder.signal));else{let t=Wm(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 Yte(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&&Vm(e.error)){let{code:n,message:r,data:i}=e.error;t.reject(new qm(n,r,i))}else t.reject(qm.invalidRequest(e));else console.error(`Got response to unknown request`,e.id)}handleProtocolNotification(e){if(e.method!==Bm)return;let t=Hte(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);!n||n.signal.aborted||n.abort(qm.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error(`ACP connection closed`)}async sendMessage(e){return this.abortController.signal.aborted?Um(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(e=>{throw this.close(e),e}),this.writeQueue)}},Zte=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)??Hm.no(t),describe:()=>this.connectionName??`onReceiveMessage`})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`request`||r.method!==e?Hm.no(r):await n(t(r.params),r.responder,i)??Hm.yes(),describe:()=>`${this.connectionName??`request`}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,i)=>r.kind!==`notification`||r.method!==e?Hm.no(r):await n(t(r.params),i)??Hm.yes(),describe:()=>`${this.connectionName??`notification`}:${e}`})}connect(e,t){return new Km(e,this.handlers,t)}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}},qm=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}}},Qte=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 $te(e,t){let n=new TextEncoder,r=new TextDecoder,i=!1,a;return{readable:new ReadableStream({async start(e){let n=new Qte,o=t=>{let n=r.decode(t).trim();if(n)try{let t=JSON.parse(n);Vm(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)+`
@@ -1225,7 +1225,7 @@ tags: [lore, history]
1225
1225
  `),i=n.nextFenced+(r?`
1226
1226
  `:``)+t;nS(b.dc.document,i,`agent`,void 0,S),$C(`mcp-write`),te=!0}ee=!0},b.origin)})}finally{Ze?.touchMode(c,`idle`)}if(w){let e;switch(w.kind){case`invalid_value`:e={[w.key]:w.reason};break;case`reserved_key`:e={[w.key]:`'${w.key}' is reserved`};break;case`unknown_key`:e={[w.key]:`'${w.key}' is not a recognized key`};break;case`duplicate_target`:e={[w.key]:`'${w.key}' appears more than once`};break;case`reorder_mismatch`:e={__region__:`frontmatter reorder mismatch (expected: ${w.expected.join(`, `)}; got: ${w.got.join(`, `)})`};break;case`region_too_large`:e={__region__:`frontmatter region too large (${w.bytes} > ${w.limit} bytes)`};break;case`parse_failed`:e={__region__:`frontmatter region unparseable: ${w.reason}`};break;case`invalid_path`:e={[w.path.map(String).join(`.`)||`__path__`]:w.reason};break;default:e={__region__:`unhandled frontmatter edit error (${String(w)})`}}G(r,400,`urn:ok:error:invalid-frontmatter-patch`,`Frontmatter patch rejected: schema validation failed.`,{handler:`frontmatter-patch`,extensions:{fieldErrors:e}});return}if(ee&&ne.length>0){if(cN(o,c,u,d,void 0,Si({clientName:f,clientVersion:p,label:m}),y),xS(),Ti(_),te){let e=await mr(o);if(e?.kind===`failure`){_r(r,e.failure,`frontmatter-patch`);return}if(e?.kind===`divergence`){vr(r,`frontmatter-patch`);return}}lr(o,`frontmatter-patch`)}qe?.setFocus(c,{agentName:u,currentDoc:o,writeKind:`write`,ts:Date.now()}),Qe?.();let re=ar(o),ie=or();ie===0&&kq().add(1,{"shadow.writer":`agent`,"agent.type":Ah(f)});let ae=br(x);Tr(o,b.dc.document.getText(`source`).toString());let oe=Sr();oe.add(o);let se=WB(b.dc.document.getText(`source`).toString(),o,oe,wr);q(r,200,Ri,{timestamp:C,subscriberCount:re,systemSubscriberCount:ie,appliedKeys:ne,...v?{summary:v}:{},...ae?{warning:ae,warnings:[ae]}:{},brokenLinks:se},{handler:`frontmatter-patch`})}catch(e){if(e instanceof hE){G(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`frontmatter-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e,requestId:jC(n)},`[frontmatter-patch] handler failed`),G(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`frontmatter-patch`,cause:e})}},{handler:`frontmatter-patch`,method:`POST`});function Bi(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 Hi=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)||`test-doc`;if(!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`document-read`});return}let r=ir(n);if(oC(r)||cC(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`document-read`});return}let i=a.documents.get(r);if(i){q(t,200,Ye,{docName:r,content:i.getText(`source`).toString(),lifecycle:Bi(i)},{handler:`document-read`});return}if(!B(DJ(l,`file`,r))){G(t,404,`urn:ok:error:doc-not-found`,`Document not found: ${r}.`,{handler:`document-read`});return}let o=await a.openDirectConnection(r);try{let e=o.document;if(!e){G(t,500,`urn:ok:error:doc-not-available`,`Document is not available.`,{handler:`document-read`});return}q(t,200,Ye,{docName:r,content:e.getText(`source`).toString(),lifecycle:Bi(e)},{handler:`document-read`})}finally{await o.disconnect()}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read document.`,{handler:`document-read`,cause:e})}},{handler:`document-read`,method:`GET`,skipBodyParse:!0}),Ui=J(g,async(e,t)=>{try{kt&&await kt.catch(e=>{Y.warn({err:e,handler:`document-list`},`[api] ready gate rejected — responding with partial index`)});let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=n.searchParams.get(`dir`),i=n.searchParams.get(`showAll`)===`true`,a=n.searchParams.get(`showOk`)===`true`,o=n.searchParams.get(`depth`)===`1`?1:1/0;if(r)try{sJ(l,r)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid directory parameter.`,{handler:`document-list`});return}if(i&&Ct&&_J(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 n=IC(t,`document-list`),i=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=uJ(),n=vJ({contentDir:l,contentFilter:Ct,dirFilter:r,maxEntries:t,maxDepth:o,showOk:a,signal:e.signal}),s=0,c=await n.next();for(;!c.done;)await i(`${JSON.stringify(c.value)}\n`),s+=1,c=await n.next();let{truncated:u}=c.value;u&&Y.info({handler:`document-list`,maxEntries:t,count:s},`[document-list][showAll] stream truncated at entry cap`),await i(`${JSON.stringify({type:`complete`,truncated:u,count:s})}\n`)}catch(e){!t.writableEnded&&!t.destroyed?n(500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll stream).`,{cause:e}):Y.error({err:e,handler:`document-list`},`[document-list][showAll] stream failed after response ended`)}finally{t.writableEnded||t.end()}return}if(i&&Ct){let e=`showAll:${o===1?`d1:`:``}${a?`ok:`:``}${r??``}`,n=dn.get(e);if(!n){let t=new AbortController,i=(async()=>{let e=[],n=uJ(),{truncated:i}=await yJ({contentDir:l,contentFilter:Ct,dirFilter:r,documents:e,maxEntries:n,maxDepth:o,showOk:a,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)}),i&&Y.info({handler:`document-list`,maxEntries:n,count:e.length},`[document-list][showAll] walk truncated at entry cap`),{documents:e,truncated:i}})();n={promise:i,controller:t,waiters:0};let s=n;dn.set(e,s),i.finally(()=>{dn.get(e)===s&&dn.delete(e)})}let i=n;i.waiters+=1;let s=!1,c=()=>{t.writableEnded||s||(s=!0,--i.waiters,i.waiters<=0&&(i.controller.abort(),dn.get(e)===i&&dn.delete(e)))};t.on(`close`,c);try{let{documents:e,truncated:n}=await i.promise;if(s)return;q(t,200,Ne,n?{documents:e,truncated:n}:{documents:e},{handler:`document-list`})}catch(e){if(s)return;G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents (showAll mode).`,{handler:`document-list`,cause:e})}finally{t.removeListener(`close`,c)}return}let s=m(),c=S(),u=ie?.()??new Map,d=[];for(let[e,t]of u)r&&!e.startsWith(`${r}/`)&&e!==r||d.push({kind:`folder`,path:e,size:0,modified:t.modified,docExt:`.md`,isSymlink:!1,canonicalDocName:null,targetPath:null});let f=[];try{let e=An(s);yn?.signature!==e&&(yn={signature:e,assets:PA({contentDir:l,fileIndex:s,readMarkdown:e=>{try{return V(e,`utf-8`)}catch{return null}},isExcluded:Ct?e=>Ct.isPathIgnored(e):void 0})}),f=yn?.assets??[]}catch(e){yn=null,Y.warn({err:e},`[document-list] asset collection failed; returning documents only`)}let p=new Set;for(let e of f)r&&!e.path.startsWith(`${r}/`)&&e.path!==r||(p.add(e.path),d.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 c){if(t.kind===`markdown`){if(r&&!e.startsWith(`${r}/`)&&e!==r)continue;let n=SC(e);d.push({kind:`document`,docName:e,docExt:n,size:t.size,modified:t.modified,isSymlink:!1,canonicalDocName:null,targetPath:null});for(let i of t.aliases){if(r&&!i.startsWith(`${r}/`)&&i!==r)continue;let a=Zk(R(l,t.canonicalPath));d.push({kind:`document`,docName:i,docExt:n,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:a})}continue}if((!r||e===r||e.startsWith(`${r}/`))&&!p.has(e)){let n=cJ(e);d.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 n of t.aliases){if(!(!r||n===r||n.startsWith(`${r}/`))||p.has(n))continue;let i=Zk(R(l,t.canonicalPath)),a=cJ(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${a}`,assetExt:a,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:i})}}let h=me?.()??new Map;if(h.size>0){let e=e=>!r||e===r||e.startsWith(`${r}/`),t=new Map;for(let[e,n]of h){let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let[n,r]of t){let t=u.get(n),i=t?Zk(R(l,t.canonicalPath)):n;for(let a of r)e(a)&&d.push({kind:`folder`,path:a,size:0,modified:t?.modified??`1970-01-01T00:00:00.000Z`,docExt:`.md`,isSymlink:!0,canonicalDocName:n,targetPath:i})}let n=(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 u)n(e,n=>{d.push({kind:`folder`,path:n,size:0,modified:t.modified,docExt:`.md`,isSymlink:!0,canonicalDocName:e,targetPath:Zk(R(l,t.canonicalPath))})});for(let[e,t]of c)n(e,n=>{let r=Zk(R(l,t.canonicalPath));if(t.kind===`markdown`)d.push({kind:`document`,docName:n,docExt:SC(e),size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r});else{let i=cJ(n);d.push({kind:`file`,docName:n,path:n,docExt:`.${i}`,assetExt:i,size:t.size,modified:t.modified,isSymlink:!0,canonicalDocName:e,targetPath:r})}})}d.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)}),q(t,200,Ne,{documents:d},{handler:`document-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list documents.`,{handler:`document-list`,cause:e})}},{handler:`document-list`,method:`GET`,skipBodyParse:!0}),qi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlinks`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`backlinks`});return}if(!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`backlinks`});return}q(t,200,_e,{docName:n,backlinks:Ie.getBacklinks(n).map(e=>({source:e.source,anchor:e.anchor,title:Wn(e.source),snippet:e.snippet}))},{handler:`backlinks`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlinks.`,{handler:`backlinks`,cause:e})}},{handler:`backlinks`,method:`GET`,skipBodyParse:!0}),Yi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`backlink-counts`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docNames`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docNames parameter.`,{handler:`backlink-counts`});return}let r={};for(let e of n.split(`,`)){let t=e.trim();!t||!eY(t)||(r[t]=Ie.getBacklinkCount(t))}q(t,200,vt,{counts:r},{handler:`backlink-counts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read backlink counts.`,{handler:`backlink-counts`,cause:e})}},{handler:`backlink-counts`,method:`GET`,skipBodyParse:!0}),Xi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`forward-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`forward-links`});return}if(!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`forward-links`});return}let r=Sr();q(t,200,Dt,{docName:n,forwardLinks:Ie.getForwardLinkEntries(n).map(e=>e.kind===`doc`?{kind:`doc`,docName:e.target,anchor:e.anchor,title:Kn(e.target,r),snippet:e.snippet}:{kind:`external`,url:e.url,title:e.label??e.url,snippet:e.snippet})},{handler:`forward-links`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read forward links.`,{handler:`forward-links`,cause:e})}},{handler:`forward-links`,method:`GET`,skipBodyParse:!0}),Zi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`link-graph`});return}try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`docName`);if(r&&!eY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`link-graph`});return}let i=n.searchParams.get(`degrees`);if(i&&!r){G(t,400,`urn:ok:error:invalid-request`,`docName is required when degrees is provided.`,{handler:`link-graph`});return}let a,o;if(i&&r){let e=Number.parseInt(i,10);if(!Number.isFinite(e)||e<0){G(t,400,`urn:ok:error:invalid-request`,`degrees must be a non-negative integer.`,{handler:`link-graph`});return}({nodes:a,links:o}=Ie.getLinkGraphNeighborhood(r,e))}else ({nodes:a,links:o}=Ie.getLinkGraph());let s=Sr();q(t,200,_a,{nodes:a.map(e=>{if(e.kind===`doc`){let t=Zn(e.docName,s);return{id:e.id,kind:`doc`,docName:e.docName,anchor:e.anchor??null,label:Kn(e.docName,s),cluster:t.cluster??null,category:t.category??null,tags:t.tags??null}}return{id:e.id,kind:`external`,url:e.url,label:e.label??e.url}}),links:o},{handler:`link-graph`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read link graph.`,{handler:`link-graph`,cause:e})}},{handler:`link-graph`,method:`GET`,skipBodyParse:!0}),Qi=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`orphans`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`mode`)??`both`;if(!Ae(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid orphan mode. Allowed values: incoming, outgoing, both.`,{handler:`orphans`});return}q(t,200,Mt,{orphans:Ie.getOrphans([...m().keys()],n).map(e=>({docName:e,title:Wn(e)}))},{handler:`orphans`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read orphan pages.`,{handler:`orphans`,cause:e})}},{handler:`orphans`,method:`GET`,skipBodyParse:!0}),$i=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`hubs`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`limit`),r=n?Number.parseInt(n,10):20,i=Number.isFinite(r)&&r>0?r:20,a=Sr();q(t,200,oa,{hubs:Ie.getHubs(i).map(e=>({docName:e.docName,title:Kn(e.docName,a),count:e.count}))},{handler:`hubs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read hub pages.`,{handler:`hubs`,cause:e})}},{handler:`hubs`,method:`GET`,skipBodyParse:!0}),ta=J(g,async(e,t)=>{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`dead-links`});return}try{let n=new URL(e.url??``,`http://localhost`).searchParams.getAll(`sourceDocName`);if(n.some(e=>e.length===0||!eY(e))){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourceDocName.`,{handler:`dead-links`});return}let r=n.length?[...new Set(n.map(e=>ir(e)))]:void 0;q(t,200,Bn,{deadLinks:Ie.getDeadLinks(Sr(),r).map(e=>({target:e.target,sources:e.sources.map(e=>({source:e.source,title:Wn(e.source),snippet:e.snippet}))}))},{handler:`dead-links`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read dead links.`,{handler:`dead-links`,cause:e})}},{handler:`dead-links`,method:`GET`,skipBodyParse:!0}),na=J(Gt,async(n,r,i)=>{try{let{find:n,replace:o,offset:c}=i,u=TJ(i.docName,r,`agent-patch`);if(u===null)return;let d=ir(u),{agentId:f,agentName:p,colorSeed:m,clientName:h,clientVersion:g,label:_}=bi(i);if(Mq(n)){jq().add(1,{result:`rejected`}),G(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}if(oC(d)||cC(d)){G(r,400,`urn:ok:error:reserved-doc-name`,`'${d}' is a reserved document name.`,{handler:`agent-patch`});return}let v=Rk(i.summary),b=await s.getSession(d,f,{displayName:p,colorSeed:m,clientName:h}),x=gV(t,a,d,l,e.resolveEmbed,lt?.()),S=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:d}:void 0,C;{let{frontmatter:e,body:t}=ea(b.dc.document.getText(`source`).toString()),r=y(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i!==-1&&i>=e.length){let e=r.slice(0,i)+o+r.slice(i+n.length);C=await tE(b.dc.document,ea(e).body,`patch`,S)}}let w=new Date().toISOString(),ee=!1,te=!1,ne=!1,re,ie;try{let e=Jn(h),t=Hn[e]??Wr(m??f);if(Ze?.setPresence(f,{displayName:p,icon:e,color:t,currentDoc:d,mode:`writing`,ts:Date.now()}),ie=Ik(b.dc.document.getText(`source`),f,b.origin,m,h),b.dc.document.transact(()=>{let{frontmatter:e,body:t}=ea(b.dc.document.getText(`source`).toString()),r=y(e,t),i=c==null?r.indexOf(n):r.slice(c,c+n.length)===n?c:-1;if(i===-1){c==null?ee=!0:te=!0,console.warn(JSON.stringify({event:`agent-patch-find-mismatch`,"doc.name":d,findLength:n.length,replaceLength:o.length,hadOffset:c!=null})),gre();return}if(i<e.length){ne=!0;return}let{body:a}=ea(r.slice(0,i)+o+r.slice(i+n.length)),s=oE(b.dc.document);re=aE(b.dc.document,a,`patch`,S,C,rE(b));let l=En(s,oE(b.dc.document))??void 0;b.dc.document.getMap(`agent-flash`).set(f,{agentId:f,timestamp:Date.now(),type:`insert`,description:`Patched (${p}): ${n.slice(0,50)}`,...l===void 0?{}:{changedBlocks:l}})},b.origin),re!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":d,position:`patch`,intendedBytes:re.intendedBytes,actualBytes:re.actualBytes,byteDelta:re.byteDelta,"agent.id":f,"agent.client_name":h})),!ee&&!te&&!ne){let{stored:e}=Ci(v);cN(d,f,p,m,void 0,Si({clientName:h,clientVersion:g,label:_}),e),xS(),Ti(v),Uq(`agent-patch`,re)}}finally{ie?.(),Ze?.touchMode(f,`idle`)}if(te){G(r,409,`urn:ok:error:stale-target`,`Target text no longer matches at the requested offset.`,{handler:`agent-patch`});return}if(ee){G(r,404,`urn:ok:error:target-not-found`,`Text not found in document.`,{handler:`agent-patch`});return}if(ne){jq().add(1,{result:`rejected`}),G(r,400,`urn:ok:error:frontmatter-edit-not-supported`,`Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.`,{handler:`agent-patch`});return}let ae=await mr(d);if(ae?.kind===`failure`){_r(r,ae.failure,`agent-patch`);return}if(ae?.kind===`divergence`){vr(r,`agent-patch`);return}lr(d,`agent-patch`),qe?.setFocus(f,{agentName:p,currentDoc:d,writeKind:`edit`,ts:Date.now()}),Qe?.();let oe=ar(d),se=or();se===0&&kq().add(1,{"shadow.writer":`agent`,"agent.type":Ah(h)});let{response:ce}=Ci(v),le=b.dc.document.getText(`source`).toString();Tr(d,le);let ue=await nL(le,d),de=Sr();de.add(d);let fe=WB(le,d,de,wr),pe=br(x),me=re===void 0?void 0:qC(re),he=[...me?[me]:[],...pe?[pe]:[],...ue??[],...await ol(b.dc.document.getText(`source`).toString(),d)];q(r,200,nn,{timestamp:w,subscriberCount:oe,systemSubscriberCount:se,...ce?{summary:ce}:{},...me?{warning:me}:pe?{warning:pe}:{},...he.length>0?{warnings:he}:{},brokenLinks:fe},{handler:`agent-patch`})}catch(e){if(e instanceof HC){UC(r,e,`agent-patch`);return}if(e instanceof JC){XC(r,e,`agent-patch`);return}if(e instanceof hE){G(r,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`agent-patch`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e,requestId:jC(n)},`[agent-patch] handler failed`),G(r,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-patch`,cause:e})}},{handler:`agent-patch`,method:`POST`}),ra=J(Ce,async(t,n,r)=>{try{let t=TJ(r.docName,n,`agent-undo`);if(t===null)return;let i=ir(t),{agentId:a,agentName:o,colorSeed:c,clientName:l,clientVersion:u,label:d}=bi(r);if(oC(i)||cC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`agent-undo`});return}let{connectionId:f}=r,p,m;if(r.scope===`count`?(p=`count`,m=r.count):p=r.scope===`session`||r.scope===`file`?`session`:`last`,!s.hasSession(i,f)){G(n,404,`urn:ok:error:no-active-session`,`No active session for this connectionId and docName.`,{handler:`agent-undo`});return}let h=await s.getSession(i,f),g=!1;try{let t=Jn(l),n=Hn[t]??Wr(c??a);Ze?.setPresence(a,{displayName:o,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),g=lE(h,p,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,m),g&&cN(i,f,o,c,void 0,Si({clientName:l,clientVersion:u,label:d}))}finally{Ze?.touchMode(a,`idle`)}if(g){let e=await mr(i);if(e?.kind===`failure`){_r(n,e.failure,`agent-undo`);return}if(e?.kind===`divergence`){vr(n,`agent-undo`);return}sr(i,`agent-undo`)}qe?.setFocus(f,{agentName:f,currentDoc:i,writeKind:`undo`,ts:Date.now()}),q(n,200,Ge,{docName:i,scope:p,undone:g},{handler:`agent-undo`})}catch(e){if(e instanceof HC){UC(n,e,`agent-undo`);return}Y.error({err:e,requestId:jC(t)},`[agent-undo] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-undo`,cause:e})}},{handler:`agent-undo`,method:`POST`}),ia=J(g,async(e,t)=>{try{let n=Dh(new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`agentId`));if(n===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-activity`});return}q(t,200,pn,jie(s,n),{handler:`agent-activity`})}catch(n){Y.error({err:n,requestId:jC(e)},`[agent-activity] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-activity`,cause:n})}},{handler:`agent-activity`,method:`GET`,skipBodyParse:!0}),sa=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=Dh(n.searchParams.get(`agentId`)),i=n.searchParams.get(`docName`),a=n.searchParams.get(`keptCount`);if(r===null){G(t,400,`urn:ok:error:invalid-request`,`agentId required (alphanumeric/_/- only).`,{handler:`agent-burst-diff`});return}if(!i||i.trim()===``){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`agent-burst-diff`});return}if(!eY(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`agent-burst-diff`});return}let o=ir(i);if(oC(o)||cC(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`agent-burst-diff`});return}if(!a||Number.isNaN(Number(a))){G(t,400,`urn:ok:error:invalid-request`,`keptCount must be a number.`,{handler:`agent-burst-diff`});return}let c=Number(a);if(!Number.isInteger(c)||c<0){G(t,400,`urn:ok:error:invalid-request`,`keptCount must be a non-negative integer.`,{handler:`agent-burst-diff`});return}let l=s.getLiveSession(o,r);if(!l){G(t,404,`urn:ok:error:no-active-session`,`No active session for this agentId and docName.`,{handler:`agent-burst-diff`});return}let u=l.um;if(c>u.undoStack.length){G(t,404,`urn:ok:error:not-found`,`keptCount ${c} out of range (stack has ${u.undoStack.length} items).`,{handler:`agent-burst-diff`});return}let d=l.dc.document.getText(`source`),{diff:f,before:p,after:m}=Oie(u.undoStack,c,d,o);q(t,200,ree,{diff:f,before:p,after:m,generatedAt:Date.now()},{handler:`agent-burst-diff`})}catch(n){Y.error({err:n,requestId:jC(e)},`[agent-burst-diff] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`agent-burst-diff`,cause:n})}},{handler:`agent-burst-diff`,method:`GET`,skipBodyParse:!0}),ca=J(g,async(e,t)=>{try{await Te?.(),q(t,200,Ar,{},{handler:`test-flush-git`})}catch(n){Y.error({err:n,requestId:jC(e)},`[test-flush-git] flush failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-flush-git`,cause:n})}},{handler:`test-flush-git`,method:`POST`,skipBodyParse:!0}),la=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),r=ir(n.searchParams.get(`docName`)??`test-doc`),i;try{i=$k(r,l)}catch(e){Y.error({err:e,docName:r},`[test-reset] safeContentPath rejected docName`),G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`test-reset`,cause:e});return}await s.closeAll(r),a.closeConnections(r);let o=`onStoreDocument-${r}`;a.debouncer.isDebounced(o)&&await a.debouncer.executeNow(o);let c=a.documents.get(r);if(c&&await(Tt??a.unloadDocument.bind(a))(c),Kl(i,``,`utf-8`),Ie&&(Ie.deleteDocument(r),Ie.saveToDisk().catch(e=>{Y.warn({docName:r,err:e},`[backlinks] Failed to persist cache after test-reset for ${r}`)}),Ve?.(`backlinks`),Ve?.(`graph`)),n.searchParams.get(`reset-okignore`)!==`false`)try{let e=z(l,`.okignore`),t=a.documents.get(nr);if(t){let e=t.getText(`source`);e.length>0&&t.transact(()=>{e.delete(0,e.length)},VA)}B(e)&&Kl(e,``,`utf-8`),Ct&&await Ct.rebuildIgnorePatterns()}catch(e){Y.warn({err:e},`[test-reset] okignore reset partial failure`)}Ve?.(`files`),q(t,200,Pi,{},{handler:`test-reset`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-reset`,cause:e})}},{handler:`test-reset`,method:`POST`,skipBodyParse:!0}),pa=J(g,async(e,t)=>{try{if(!Ie){G(t,503,`urn:ok:error:backlink-index-not-configured`,`Backlink index is not configured.`,{handler:`test-rescan-backlinks`});return}await Ie.rebuildFromDisk(),await Ie.ingestGlobalSkillBundles([z(Rs,`.ok`,`skills`)]),Ie.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist cache after test-rescan-backlinks`)}),Ve?.(`backlinks`),Ve?.(`graph`),q(t,200,Pn,{},{handler:`test-rescan-backlinks`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-backlinks`,cause:e})}},{handler:`test-rescan-backlinks`,method:`POST`,skipBodyParse:!0}),ma=J(g,async(e,t)=>{try{if(!he){G(t,503,`urn:ok:error:file-rescan-not-configured`,`Watcher rescan capability is not configured.`,{handler:`test-rescan-files`});return}await he(),Ve?.(`files`),q(t,200,hi,{},{handler:`test-rescan-files`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`test-rescan-files`,cause:e})}},{handler:`test-rescan-files`,method:`POST`,skipBodyParse:!0}),ha=J(f,async(e,t,n)=>{try{let{rawAgentId:e,agentId:r,agentName:i,clientName:a}=bi(n),o=be?.current;if(!o){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`save-version`});return}let s=/^[a-zA-Z0-9_-]+$/,c=[],l=!1;if(Array.isArray(n.writers))try{c=n.writers.map(e=>{let t=e.id??`unknown`;if(!s.test(t))throw Error(`Invalid writer id: ${t}`);return{id:t,name:(e.name??`unknown`).replace(/[\r\n]/g,``),email:(e.email??`noreply@openknowledge.local`).replace(/[\r\n]/g,``)}})}catch(e){G(t,400,`urn:ok:error:invalid-request`,e instanceof Error?e.message:`Invalid writer id.`,{handler:`save-version`,cause:e});return}let u=Oe?.()??`main`;if(c.length===0)if(e!==void 0)c=[{id:r,name:a?`${i} (${a})`:i,email:`${r}@openknowledge.local`}];else{let e=(await RS(o,u)).filter(e=>!e.isPark);c=e.length>0?e.map(e=>({id:e.writerId,name:e.writerId,email:`${e.writerId}@openknowledge.local`})):[qS],l=!0}let d=Fe??`.`,f=Rk(typeof n.summary==`string`?n.summary:void 0),p=await nC(o,d,c,u,f.kind===`value`?f.value:void 0,l?{includeUpstream:!1}:void 0);F(`history`).info({checkpointRef:p.checkpointRef},`checkpoint`);try{await LG(o,yG(o.gitDir))}catch(e){Y.warn({err:e},`[rename-log] post-saveVersion GC failed`)}q(t,200,Ir,{checkpointRef:p.checkpointRef},{handler:`save-version`})}catch(n){Y.error({err:n,requestId:jC(e)},`[save-version] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`save-version`,cause:n})}},{handler:`save-version`,method:`POST`}),ya=J(g,async(e,t)=>{let n=be?.current;if(!n){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history`});return}try{let e=performance.now();await Te?.();let t=performance.now()-e;t>1e3&&Y.warn({durationMs:Math.round(t)},`[history] pre-read commit flush slow`)}catch(e){Y.warn({err:e},`[history] pre-read commit flush failed`)}let r=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=r.searchParams.get(`docName`)??``,a=r.searchParams.get(`folder`),o=r.searchParams.get(`branch`)??Oe?.()??`main`;if(!i&&a===null){G(t,400,`urn:ok:error:invalid-request`,`A docName or folder query parameter is required.`,{handler:`history`});return}if(o.includes(`..`)||!/^[a-zA-Z0-9][a-zA-Z0-9._/-]*$/.test(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid branch name.`,{handler:`history`});return}if(a!==null&&!i){let e=ys(a,t,`folder`,`history`);if(!e)return;let i=Number(r.searchParams.get(`limit`)??`50`),s=Math.min(200,Number.isFinite(i)?i:50),c=Number(r.searchParams.get(`offset`)??`0`),l=Math.max(0,Number.isFinite(c)?c:0),u=`folder\0${o}\0${e.folderRel}\0${s}\0${l}`,{promise:d,coalesced:f}=gn.run(u,()=>Tq(n,e.folderRel,Fe??`.`,{branch:o,limit:s,offset:l}));f&&oq(`folder`),q(t,200,ae,{...await d},{handler:`history`});return}let s=Fe??`.`,c=Yq(i,s);if(`error`in c){G(t,400,`urn:ok:error:invalid-request`,c.error,{handler:`history`});return}let l=Number(r.searchParams.get(`limit`)??`50`),u=Number(r.searchParams.get(`offset`)??`0`),d=Math.min(200,Number.isFinite(l)?l:50),f=Number.isFinite(u)?u:0,p=r.searchParams.get(`type`)??void 0,m=r.searchParams.get(`author`)??void 0,h=r.searchParams.get(`excludeAuthor`)??void 0,g=r.searchParams.get(`includeAutoCheckpoints`)===`true`,_=`doc\0${o}\0${i}\0${d}\0${f}\0${p??``}\0${m??``}\0${h??``}\0${g?`1`:`0`}`,v=Date.now();try{let{promise:e,coalesced:r}=gn.run(_,()=>wq(n,{docName:i,branch:o,limit:d,offset:f,type:p,author:m,excludeAuthor:h,includeAutoCheckpoints:g},s));r&&oq(`doc`);let a=await e,c=Date.now()-v;F(`timeline`).info({docName:i,entries:a.entries.length,durationMs:c},`query`),q(t,200,ae,{...a},{handler:`history`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read history.`,{handler:`history`,cause:e})}},{handler:`history`,method:`GET`,skipBodyParse:!0});async function ba(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`history-version`,extraHeaders:{Allow:`GET`}});return}let r=be?.current;if(!r){G(t,503,`urn:ok:error:shadow-not-configured`,`Shadow repo not configured.`,{handler:`history-version`});return}let i=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`docName`)??``,a=Fe??`.`,o=Yq(i,a);if(`error`in o){G(t,400,`urn:ok:error:invalid-request`,o.error,{handler:`history-version`});return}let s=LS(r),c=Oe?.()??`main`;if(!/^[0-9a-f]{40}$/i.test(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid commit SHA.`,{handler:`history-version`});return}try{let e=await HG(r,i,n,c,yG(r.gitDir),e=>Xq(e,a),CG());if(e===null){G(t,404,`urn:ok:error:doc-not-found`,`Document did not exist at this version.`,{handler:`history-version`});return}let o=await s.raw(`show`,`${n}:${e}`),[l=``,u=``]=(await s.raw(`log`,`-1`,`--format=%aI%x00%an`,n)).trim().split(`\0`);q(t,200,pt,{sha:n,content:o,timestamp:l,author:u},{handler:`history-version`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`history-version`,cause:e})}}let Sa=J(Se,async(t,n,r)=>{let i=_V(r,ut);if(i.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rollback`});return}let o=a.documents.get(r.docName);if(o&&RC(o)){UC(n,new HC({file:CC(r.docName)}),`rollback`);return}let s=be?.current;if(!s){G(n,503,`urn:ok:error:rollback-not-configured`,`Shadow repo not configured.`,{handler:`rollback`});return}let{docName:c,commitSha:l}=r,u=Fe??`.`,d=Yq(c,u);if(`error`in d){G(n,400,`urn:ok:error:invalid-request`,d.error,{handler:`rollback`});return}let f=LS(s),p=Date.now();try{let t=yG(s.gitDir),r=CG(),o=await HG(s,c,l,Oe?.()??`main`,t,e=>Xq(e,u),r);if(o===null){G(n,404,`urn:ok:error:doc-not-found`,`Commit ${l.slice(0,7)} does not contain document ${c} at any known historical path.`,{handler:`rollback`});return}let d=await f.raw(`show`,`${l}:${o}`),m=new Date().toISOString();await ZS(s,u,{action:`rollback`,context:{docName:c,targetSha:l}});let h=a.documents.get(c);if(!h){G(n,409,`urn:ok:error:doc-not-open`,`Document is not currently open — open it in the editor first.`,{handler:`rollback`});return}let g=e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:c}:void 0,_=await Cw(d,g),v;h.transact(()=>{rS(h,d,g,_),v=KC(h.getText(`source`).toString(),d,`rollback`)},Kq),v!==void 0&&console.warn(JSON.stringify({event:`agent-write-content-divergence`,"doc.name":c,position:`rollback`,intendedBytes:v.intendedBytes,actualBytes:v.actualBytes,byteDelta:v.byteDelta,"actor.kind":i.kind,...i.kind===`agent`||i.kind===`principal`?{"actor.writer_id":i.writerId}:{}})),Uq(`rollback`,v);let y;switch(i.kind){case`agent`:{let e=l.slice(0,8),t=i.summary.kind===`value`,n=t?i.summary:Rk(`Restored to ${e}`),r=Ci(n);y=t||!r.response?r.response:wi(r.response),cN(c,i.writerId,i.displayName,i.colorSeed,Uu(c,l),i.actor,r.stored),xS(),Ti(n,!t);break}case`principal`:{let e=Ci(i.summary);y=e.response,cN(c,i.writerId,i.displayName,i.colorSeed,Uu(c,l),i.actor,e.stored),Ti(i.summary,!1);break}case`anonymous`:Y.debug({docName:c,commitSha:l.slice(0,8)},`[rollback] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`);break;default:throw Error(`Unhandled actor kind in handleRollback: ${String(i.kind)}`)}Pq().add(1,{kind:`rollback`,attribution_kind:i.kind});let b=await mr(c);if(b?.kind===`failure`){_r(n,b.failure,`rollback`);return}if(b?.kind===`divergence`){vr(n,`rollback`);return}sr(c,`rollback`);let x=Date.now()-p;F(`rollback`).info({docName:c,from:l.slice(0,8),durationMs:x},`rollback`),i.kind===`agent`&&qe?.setFocus(i.writerId,{agentName:i.displayName,currentDoc:c,writeKind:`rollback-apply`,ts:Date.now()});let S=v===void 0?void 0:qC(v);q(n,200,We,{restoredFrom:l,timestamp:m,...y?{summary:y}:{},...S?{warning:S,warnings:[S]}:{}},{handler:`rollback`})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Failed to roll back.`,{handler:`rollback`,cause:e})}},{handler:`rollback`,method:`POST`}),Ca=J(g,async(e,t)=>{try{q(t,200,Vi,AS(),{handler:`metrics-reconciliation`})}catch(n){Y.error({err:n,requestId:jC(e)},`[metrics-reconciliation] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-reconciliation`,cause:n})}},{handler:`metrics-reconciliation`,method:`GET`,skipBodyParse:!0}),wa=J(g,async(e,t)=>{try{q(t,200,rr,Ut(),{handler:`metrics-parse-health`})}catch(n){Y.error({err:n,requestId:jC(e)},`[metrics-parse-health] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-parse-health`,cause:n})}},{handler:`metrics-parse-health`,method:`GET`,skipBodyParse:!0}),Ea=J(g,async(e,n)=>{try{kt&&await kt.catch(e=>{Y.warn({err:e,handler:`server-info`},`[api] ready gate rejected — responding with current state`)});let e=t.getActiveBranch(),r=je?.(),i=nV();q(n,200,fn,{serverInstanceId:u,currentBranch:e,...r===void 0?{}:{currentDiskAckSVs:r},...i===void 0?{}:{boot:i}},{handler:`server-info`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(n,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`server-info`,cause:e})}},{handler:`server-info`,method:`GET`,skipBodyParse:!0}),Da=O({agents:N(O({id:A(),name:A(),version:A(),description:A().optional(),license:A().optional(),iconUrl:A().optional(),website:A().optional(),source:La([`registry`,`custom`]),supported:M(),featured:M(),harness:O({cli:La([`claude`,`codex`,`cursor`,`opencode`,`pi`]),availability:La([`present`,`not-found`,`unknown`])}).optional()})),stale:M(),maxThreads:P()}),ka=J(g,async(e,t)=>{if(ht===void 0){G(t,404,`urn:ok:error:not-found`,`ACP catalog unavailable.`,{handler:`acp-catalog`});return}try{let e=id(),{agents:n,stale:r}=await ht.getCatalog(),i=await gt?.()??[],a=await bt();q(t,200,Da,{agents:[...n.map(t=>{let n=Ak[t.id];return{id:t.id,name:t.name,version:t.version,...t.description===void 0?{}:{description:t.description},...t.license===void 0?{}:{license:t.license},...t.icon===void 0?{}:{iconUrl:t.icon},...t.website===void 0?{}:{website:t.website},source:`registry`,supported:t.distribution.npx!==void 0||t.distribution.uvx!==void 0||e!==null&&t.distribution.binary?.[e]!==void 0,featured:ed.includes(t.id),...n===void 0?{}:{harness:{cli:n,availability:a[n]??`unknown`}}}}),...i.map(e=>({id:e.id,name:e.name,version:`custom`,source:`custom`,supported:!0,featured:!1}))],stale:r,maxThreads:8},{handler:`acp-catalog`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,502,`urn:ok:error:registry-unreachable`,`Agent registry unreachable.`,{handler:`acp-catalog`,cause:e})}},{handler:`acp-catalog`,method:`GET`,skipBodyParse:!0});async function Aa(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`principal`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`principal`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`principal`,extraHeaders:{Allow:`GET`}});return}let n=ut?.()??null;if(!n){G(t,404,`urn:ok:error:principal-not-available`,`Principal not available.`,{handler:`principal`});return}q(t,200,see,n,{handler:`principal`})}async function ja(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-presence`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-presence`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-presence`,extraHeaders:{Allow:`GET`}});return}try{let e=Ze?.getPresenceMap()??{},n=Date.now(),r={};for(let[t,i]of Object.entries(e))n-i.ts<2e4&&(r[t]=i);q(t,200,o,{presence:r},{handler:`metrics-agent-presence`})}catch(n){Y.error({err:n,requestId:jC(e)},`[metrics-agent-presence] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-presence`,cause:n})}}async function Ma(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-agent-effects`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-agent-effects`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-agent-effects`,extraHeaders:{Allow:`GET`}});return}let n;try{let e=[];for(let[t,r]of a.documents){if(oC(t)||cC(t)||!r.share.has(`agent-effects`))continue;n=t;let i=r.getMap(`agent-effects`);if(i.size===0)continue;let a=[...i.values()].map(e=>{let t=0,n=0;for(let r of e.delta)typeof r.insert==`string`?t+=r.insert.length:r.insert!==void 0&&(t+=1),typeof r.delete==`number`&&(n+=r.delete);return{sessionId:e.sessionId,agentType:e.agent_type,ts:e.timestamp,insertedChars:t,deletedChars:n}}).sort((e,t)=>e.ts-t.ts);e.push({"doc.name":t,entries:a})}e.sort((e,t)=>e[`doc.name`].localeCompare(t[`doc.name`])),q(t,200,St,{effects:e},{handler:`metrics-agent-effects`})}catch(e){Y.error({err:e,"doc.name":n},`[metrics-agent-effects] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-agent-effects`,cause:e})}}async function Pa(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`metrics-watcher-recent`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`metrics-watcher-recent`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`metrics-watcher-recent`,extraHeaders:{Allow:`GET`}});return}try{q(t,200,ci,{decisions:NV().map(e=>({ts:e.ts,decision:e.decision,kind:e.kind,"doc.name":e.path,pathRole:e.pathRole}))},{handler:`metrics-watcher-recent`})}catch(n){Y.error({err:n,requestId:jC(e)},`[metrics-watcher-recent] handler failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`metrics-watcher-recent`,cause:n})}}async function Fa(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`embed-detect`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`embed-detect`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`embed-detect`,extraHeaders:{Allow:`GET`}});return}let n=vN.read();q(t,200,st,{entries:n,count:n.length,detection:wN(n[0])},{handler:`embed-detect`})}async function Ia(e,t){if(!zk(e.socket.remoteAddress)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`workspace`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`workspace`});return}if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`workspace`,extraHeaders:{Allow:`GET`}});return}let n=z(l),r=n,a=!0;try{r=Bl(n)}catch(e){let r=As(e);if(r===`ENOENT`)Y.warn({path:n},`[workspace] contentDir does not exist; returning unresolved path`),a=!1;else{Y.warn({path:n,err:e},`[workspace] realpath failed for contentDir`),G(t,500,`urn:ok:error:internal-server-error`,`Workspace realpath failed.`,{handler:`workspace`,detail:r??void 0,cause:e});return}}q(t,200,tt,{contentDir:r,pathSeparator:Cl,symlinkResolved:a},{handler:`workspace`})}let Ra=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset`});return}let r=FA(n),i=yl(n).slice(1).toLowerCase();if(!r||!Na.has(i)){G(t,415,`urn:ok:error:unsupported-asset-type`,`Unsupported asset type.`,{handler:`asset`});return}let a=Bl(l),o=z(a,n),s;try{s=Bl(o)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!eA(s,a)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}let c;try{c=Wl(s)}catch{G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}if(!c.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let u=NA(a,s);if(u!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset`});return}if(Ct?.isPathIgnored(u)){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset`});return}let d=Oa.has(i),f={"Content-Type":r,"Content-Length":String(c.size),"X-Content-Type-Options":`nosniff`,"Content-Disposition":_o.has(i)||d?`inline`:`attachment`,"Cache-Control":`no-store`};i===`svg`?f[`Content-Security-Policy`]=`sandbox; default-src 'none'; style-src 'unsafe-inline'`:d&&(f[`Content-Security-Policy`]=Va),t.writeHead(200,f);try{await gu(Al(s),t)}catch(e){Y.error({event:`api.asset.pipeline-failed`,handler:`asset`,assetPath:n,err:e},`[asset] pipeline failed mid-stream`),t.destroyed||t.destroy(e instanceof Error?e:void 0)}}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset`,cause:e})}},{handler:`asset`,method:`GET`,skipBodyParse:!0}),Ba=1048576,Ha=J(g,async(e,t)=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`).searchParams.get(`path`);if(!n||n.includes(`\0`)){G(t,400,`urn:ok:error:invalid-request`,`Missing asset path.`,{handler:`asset-text`});return}let r=Bl(l),i=z(r,n),a;try{a=Bl(i)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!eA(a,r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}let o;try{o=Wl(a)}catch(e){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`,cause:e});return}if(!o.isFile()){G(t,404,`urn:ok:error:asset-not-found`,`Asset not found.`,{handler:`asset-text`});return}if(NA(r,a)!==n.split(`\\`).join(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid asset path.`,{handler:`asset-text`});return}if(o.size>Ba){G(t,413,`urn:ok:error:payload-too-large`,`File exceeds the ${Ba}-byte text-viewer cap.`,{handler:`asset-text`});return}let s=(await iu(a)).toString(`utf-8`);t.writeHead(200,{"Content-Type":`text/plain; charset=utf-8`,"X-Content-Type-Options":`nosniff`,"Content-Disposition":`inline`,"Cache-Control":`no-store`}),t.end(s)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`asset-text`,cause:e})}},{handler:`asset-text`,method:`GET`,skipBodyParse:!0}),Ua=J(g,async(e,t)=>{try{if(!be?.current){q(t,200,Hr,[],{handler:`rescue-list`});return}let e=Date.now(),n=[],r=z(be.current.gitDir,`rescue`);if(B(r))try{let t=Rl(r).filter(e=>hC(e));for(let i of t){let t=z(r,i),a=Wl(t);if(e-a.mtimeMs>864e5){try{Gl(t)}catch(e){Y.debug({err:e},`[rescue] cleanup failed (non-critical)`)}continue}n.push({docName:_C(i),timestamp:a.mtime.toISOString(),size:a.size,source:`flat`})}}catch(e){Y.error({err:e},`[rescue] Failed to list flat-file rescue buffers`)}try{let e=Oe?.()??`main`,t=await $S(be.current,e);for(let e of t)n.push({...e,source:`timeline`})}catch(e){Y.error({err:e},`[rescue] Failed to list timeline-ref rescue checkpoints`)}q(t,200,Hr,n,{handler:`rescue-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`rescue-list`,cause:e})}},{handler:`rescue-list`,method:`GET`,skipBodyParse:!0}),Wa=J(_t,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-page`});return}let r=n.path;if(!hC(r)){G(t,400,`urn:ok:error:invalid-request`,`path must end with .md or .mdx.`,{handler:`create-page`});return}if(r.includes(`..`)||r.startsWith(`/`)||r.includes(`\0`)||r.includes(`\\`)){G(t,400,`urn:ok:error:path-escape`,`Invalid path.`,{handler:`create-page`,detail:`path must not contain .. or start with /`});return}let i=z(l),a=z(i,r);if(!Qk(a,i)){G(t,400,`urn:ok:error:path-escape`,`path must not escape content directory.`,{handler:`create-page`});return}let o=_C(r);if(oC(o)||cC(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`});return}if(xJ(r)||Jr(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${o}' is a reserved document name.`,{handler:`create-page`,detail:`Cannot create a page inside .ok or .git — skills and templates are authored through their own validating flows.`});return}let s=typeof n.template==`string`?n.template.trim():``,c=``,u;if(s.length>0){if(!/^[A-Za-z0-9_-]+$/.test(s)){G(t,400,`urn:ok:error:invalid-request`,`Template name must match [A-Za-z0-9_-]+.`,{handler:`create-page`});return}let n=r.includes(`/`)?r.slice(0,r.lastIndexOf(`/`)):``,a=Gj(i,n),o=a.find(e=>e.name===s);if(!o){let e=a.length===0?`(none)`:a.map(e=>`"${e.name}" (${e.scope})`).join(`, `);G(t,400,`urn:ok:error:invalid-request`,`Template "${s}" does not resolve for folder "${n||`(root)`}". Available: ${e}`,{handler:`create-page`});return}let l=z(i,o.path),d;try{d=V(l,`utf-8`)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template at ${o.path}.`,{handler:`create-page`,cause:e});return}let f=dr(d),p=e.kind===`agent`||e.kind===`principal`?e.displayName??``:``;c=GM(f,{date:qM(),user:p}),u=o.scope}Nl(I(a),{recursive:!0});try{Kl(a,c,{encoding:`utf-8`,flag:`wx`})}catch(e){if(MJ(e)){G(t,409,`urn:ok:error:doc-already-exists`,`File already exists.`,{handler:`create-page`,cause:e});return}throw e}let d=_C(r);switch(At?.delete(d),Ct&&Ct.incrementMdDir(I(d)),wV(a,EV(c)),e.kind){case`agent`:case`principal`:cN(d,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleCreatePage: ${String(e.kind)}`)}w?.({kind:`create`,path:a,docName:d,content:c}),Ie&&(Ie.updateDocumentFromMarkdown(d,c),Ie.saveToDisk().catch(e=>{Y.warn({docName:d,err:e},`[backlinks] Failed to persist create-page cache for ${d}`)}),Ve?.(`backlinks`),Ve?.(`graph`)),Ve?.(`files`),u!==void 0&&console.warn(JSON.stringify({event:`template-instantiate`,templateName:s,templateScope:u,docName:d})),q(t,200,ge,{docName:d},{handler:`create-page`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create page.`,{handler:`create-page`,cause:e})}},{handler:`create-page`,method:`POST`}),Ga=J(et,async(e,t,n)=>{try{if(_V(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`create-folder`});return}let e=n.path;if(!bJ(e)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`create-folder`});return}if(xJ(e)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`create-folder`});return}if(Ct?.isDirExcluded(e)){G(t,400,`urn:ok:error:invalid-request`,`Destination folder is excluded by the workspace content config.`,{handler:`create-folder`});return}let r=DJ(l,`folder`,e);if(B(r)){G(t,409,`urn:ok:error:doc-already-exists`,`Folder already exists.`,{handler:`create-folder`});return}Wo(r,{recursive:!0}),Tn(e),Ve?.(`files`),q(t,200,ot,{path:e},{handler:`create-folder`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to create folder.`,{handler:`create-folder`,cause:e})}},{handler:`create-folder`,method:`POST`}),E=J(Et,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`duplicate-path`});return}let{kind:r}=n,i=n.path,o=r===`file`?_C(i):i;if(!bJ(i)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`duplicate-path`});return}if(xJ(i)||r===`file`&&(oC(o)||cC(o))||r===`folder`&&SJ(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved paths cannot be duplicated.`,{handler:`duplicate-path`});return}r===`file`&&UJ(l,i);let s=DJ(l,r,i);if(!B(s)){if(r===`file`){let e=DJ(l,`folder`,i);if(B(e)&&Wl(e).isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}}G(t,404,`urn:ok:error:doc-not-found`,`${r} does not exist.`,{handler:`duplicate-path`});return}let c=Wl(s);if(r===`file`&&!c.isFile()||r===`folder`&&!c.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${r}.`,{handler:`duplicate-path`});return}let u=r===`file`?[LJ(l,i)]:ui(DJ(l,`folder`,i)),d=$e?.(),f=new Set(d?d.getConflicts().map(e=>e.file):[]);for(let e of u){let n=e,r=a.documents.get(n),i=CC(n),o=r!==void 0&&RC(r),s=f.has(i);if(o||s){UC(t,new HC({file:i}),`duplicate-path`);return}}let p,m=[];if(r===`file`){let e=yl(s);if(p=zJ(l,o).docName,oC(p)||cC(p)||Ct?.isExcluded(`${p}${e}`)){G(t,400,`urn:ok:error:invalid-request`,`Duplicated document destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let n=RJ(l,p,e),r=V(s,`utf-8`),i=I(n),a=B(i);try{Wo(i,{recursive:!0}),$o(n,r,{encoding:`utf-8`,flag:`wx`})}catch(e){if(MJ(e)){G(t,409,`urn:ok:error:doc-already-exists`,`A file at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}if(!a)try{Go(i)}catch(e){let t=As(e);t!==`ENOENT`&&t!==`ENOTEMPTY`&&Y.warn({destinationDir:i,err:e},`[duplicate-path] failed to clean duplicate parent directory`)}throw e}let c=!1;try{xC(p,e),At?.delete(p),Ct&&(Ct.incrementMdDir(I(p)),c=!0),wV(n,EV(r)),w?.({kind:`create`,path:n,docName:p,content:r}),Ie?.updateDocumentFromMarkdown(p,r),m=[p]}catch(e){try{Jo(n,{force:!0})}catch(e){Y.warn({destinationPath:n,err:e},`[duplicate-path] failed to clean partial file duplicate`)}throw TC(p),Ct&&c&&Ct.decrementMdDir(I(p)),w?.({kind:`delete`,path:n,docName:p}),e}}else{if(p=BJ(l,i).folderPath,Ct?.isDirExcluded(p)){G(t,400,`urn:ok:error:invalid-request`,`Duplicated folder destination is excluded by the project content config.`,{handler:`duplicate-path`});return}let e=DJ(l,`folder`,p);try{qo(s,e,{recursive:!0,errorOnExist:!0,force:!1})}catch(e){if(MJ(e)){G(t,409,`urn:ok:error:doc-already-exists`,`A folder at the duplicate destination already exists.`,{handler:`duplicate-path`,cause:e});return}throw e}try{for(let e of HJ(l,p))Tn(e);let e=VJ(l,p);m=e.map(e=>e.docName);for(let t of e){let e=yl(t.fullPath);xC(_C(t.docName),e),At?.delete(t.docName),Ct&&Ct.incrementMdDir(I(t.docName)),wV(t.fullPath,EV(t.content)),w?.({kind:`create`,path:t.fullPath,docName:t.docName,content:t.content}),Ie?.updateDocumentFromMarkdown(t.docName,t.content)}}catch(t){try{Jo(e,{recursive:!0,force:!0})}catch(t){Y.warn({destinationPath:e,err:t},`[duplicate-path] failed to clean partial folder duplicate`)}throw t}}switch(e.kind){case`agent`:case`principal`:for(let t of m)cN(t,e.writerId,e.displayName,e.colorSeed,void 0,e.actor);break;case`anonymous`:break;default:throw Error(`Unhandled actor kind in handleDuplicatePath: ${String(e.kind)}`)}Ie&&m.length>0&&(Ie.saveToDisk().catch(e=>{Y.warn({err:e},`[backlinks] Failed to persist duplicate-path cache`)}),Ve?.(`backlinks`),Ve?.(`graph`)),Ve?.(`files`),q(t,200,ga,{kind:r,path:p,duplicatedDocNames:m},{handler:`duplicate-path`})}catch(e){if(e instanceof jJ){G(t,409,`urn:ok:error:doc-already-exists`,`All available duplicate name slots are occupied for this path.`,{handler:`duplicate-path`,cause:e});return}let n=NJ(e);if(n){G(t,n.status,n.type,n.title,{handler:`duplicate-path`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to duplicate path.`,{handler:`duplicate-path`,cause:e})}},{handler:`duplicate-path`,method:`POST`}),Ka=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n||n.length===0){G(t,400,`urn:ok:error:invalid-request`,`Missing docName query parameter.`,{handler:`page-headings`});return}if(!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}let r=Vn(n);if(!r){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`page-headings`});return}if(!B(r)){G(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`page-headings`});return}q(t,200,Yt,{docName:n,headings:$J(V(r,`utf-8`))},{handler:`page-headings`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read headings.`,{handler:`page-headings`,cause:e})}},{handler:`page-headings`,method:`GET`,skipBodyParse:!0}),qa=J(Wt,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`rename-path`});return}let{kind:r,fromPath:i,toPath:o}=n;if(!bJ(i)||!bJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Paths must be relative content paths.`,{handler:`rename-path`});return}if(r===`file`&&(oC(i)||oC(o)||cC(i)||cC(o))){G(t,400,`urn:ok:error:reserved-doc-name`,`Reserved document names cannot be renamed.`,{handler:`rename-path`});return}if(xJ(i)||xJ(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`rename-path`});return}if(i===o){q(t,200,tn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}let s=r===`asset`&&hC(i)&&hC(o)?`file`:r;if(s===`asset`){let n;try{n=hC(i)&&!hC(o)?await _i(i,o):await mi(i,o)}catch(e){if(e instanceof HC){UC(t,e,`rename-path`);return}let{status:n,type:r,error:i}=Pr(e);G(t,n,r,i,{handler:`rename-path`,cause:e});return}n.renamedAssets.length>0&&jn();let r;if(n.renamedAssets.length>0&&n.rewrittenDocs.length>0){let t=`Renamed asset ${i} → ${o}`;r=Ei(e,t,n.rewrittenDocs.map(({docName:e})=>({docName:e,subject:t})),{context:`handleRenamePath asset branch`,onAnonymous:()=>{Y.debug({kind:`asset`,fromPath:i,toPath:o,affectedDocs:n.rewrittenDocs.length,affectedAssets:n.renamedAssets.length},`[rename-path] anonymous actor; no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})}if(Pq().add(1,{kind:`rename-asset`,attribution_kind:e.kind}),Ee)try{await Ee()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed after asset rename (commitSha backfill may be deferred)`)}q(t,200,tn,{renamed:[],renamedAssets:n.renamedAssets,rewrittenDocs:n.rewrittenDocs,...r?{summary:r}:{}},{handler:`rename-path`});return}s===`file`&&UJ(l,i);let c=s===`file`?[LJ(l,i)]:ui(DJ(l,`folder`,i)),u=$e?.(),d=new Set(u?u.getConflicts().map(e=>e.file):[]);for(let e of c){let n=e,r=a.documents.get(n),i=CC(n),o=r!==void 0&&RC(r),s=d.has(i);if(o||s){UC(t,new HC({file:i}),`rename-path`);return}}if(Ct){let e=hC(i)?yl(i):SC(i);if(s===`file`?Ct.isExcluded(hC(o)?o:`${o}${e}`):Ct.isDirExcluded(o)){G(t,400,`urn:ok:error:invalid-request`,`Destination ${s===`file`?`document`:`folder`} is excluded by the project content config.`,{handler:`rename-path`});return}}let f=e.kind===`agent`||e.kind===`principal`?{writerId:e.writerId,displayName:e.displayName,colorSeed:e.colorSeed,actorMetadata:e.actor}:void 0,p;try{p=await vi(i,o,s,f?{actor:f}:{})}catch(e){if(e instanceof jF){G(t,409,`urn:ok:error:doc-already-exists`,Nr(e.message),{handler:`rename-path`,extensions:{colliding:e.colliding},cause:e});return}throw e}if(p.renamed.length===0&&p.renamedAssets.length===0){q(t,200,tn,{renamed:[],renamedAssets:[],rewrittenDocs:[]},{handler:`rename-path`});return}p.renamedAssets.length>0&&jn();let m,h=p.renamed.filter(({fromDocName:e,toDocName:t})=>e!==t);if(h.length>0&&(m=Ei(e,`Renamed ${i} → ${o}`,h.map(({fromDocName:e,toDocName:t})=>({docName:t,subject:Gu(e,t)})),{context:`handleRenamePath`,onAnonymous:()=>{Y.debug({kind:r,fromPath:i,toPath:o,affectedDocs:p.renamed.length},`[rename-path] anonymous actor — no contributor recorded (no agentId in body and getPrincipal() returned null)`)}})),Pq().add(1,{kind:`rename-${s}`,attribution_kind:e.kind}),Ee)try{await Ee()}catch(e){Y.warn({err:e},`[rename-path] flushContributors failed (commitSha backfill may be deferred)`)}q(t,200,tn,{renamed:p.renamed,renamedAssets:p.renamedAssets,rewrittenDocs:p.rewrittenDocs,...m?{summary:m}:{}},{handler:`rename-path`})}catch(e){let{status:n,type:r,error:i}=Pr(e);G(t,n,r,i,{handler:`rename-path`,cause:e})}},{handler:`rename-path`,method:`POST`}),D=J(Me,async(e,t,n)=>{try{bi(n);let{kind:e,path:r}=n;if(!bJ(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`delete-path`});return}let i=e===`asset`?li(r):{path:r,ambiguous:!1};if(i.ambiguous){G(t,400,`urn:ok:error:invalid-request`,`Asset path without an extension matches multiple files.`,{handler:`delete-path`});return}let o=i.path,s=e===`asset`&&hC(o)?`file`:e;if(s===`file`&&UJ(l,o),xJ(o)){G(t,400,`urn:ok:error:reserved-doc-name`,`.ok and .git are reserved directories.`,{handler:`delete-path`});return}let c=s===`asset`?DJ(l,`folder`,o):DJ(l,s,o);if(!B(c)){G(t,404,`urn:ok:error:doc-not-found`,`${s} does not exist.`,{handler:`delete-path`});return}let u=Wl(c);if(s===`file`&&!u.isFile()||s===`asset`&&!u.isFile()||s===`folder`&&!u.isDirectory()){G(t,400,`urn:ok:error:invalid-request`,`Target path is not a ${s}.`,{handler:`delete-path`});return}let d=s===`asset`?[]:s===`file`?[LJ(l,o)]:ui(DJ(l,`folder`,o)),f=$e?.(),p=new Set(f?f.getConflicts().map(e=>e.file):[]);for(let e of d){let n=e,r=a.documents.get(n),i=CC(n),o=r!==void 0&&RC(r),s=p.has(i);if(o||s){UC(t,new HC({file:i}),`delete-path`);return}}if(await Rr(d,`deleted-upstream`),At)for(let e of d)oC(e)||cC(e)||(At.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleDeletePath`})));s===`file`||s===`asset`?zo(c):(Jo(c,{recursive:!0,force:!1}),On(o)),jn();for(let e of d)w?.({kind:`delete`,path:z(l,CC(e)),docName:e});Ve?.(`files`),q(t,200,Je,{deletedDocNames:d},{handler:`delete-path`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete path.`,{handler:`delete-path`,cause:e})}},{handler:`delete-path`,method:`POST`}),Ja=J(cee,async(e,t,n)=>Mo(`ok.fs.trash_cleanup`,{attributes:{"ok.cleanup.kind":n.kind,"ok.cleanup.path":Ko(n.path),"ok.cleanup.path.role":Zo(n.path)}},async()=>{try{if(_V(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`trash-cleanup`});return}let{kind:e,path:r}=n;if(!bJ(r)){G(t,400,`urn:ok:error:invalid-request`,`path must be a relative content path.`,{handler:`trash-cleanup`});return}let i=e===`asset`&&hC(r)?`file`:e,a=_C(r);i===`file`&&UJ(l,r);let o=i===`folder`&&SJ(r);if(i===`file`&&(oC(a)||cC(a))||o||xJ(r)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${r}' is a reserved document name.`,{handler:`trash-cleanup`});return}if(i===`asset`){jn(),Ve?.(`files`),q(t,200,Re,{deletedDocNames:[]},{handler:`trash-cleanup`});return}let s=m(),c=i===`file`?s.has(a)?[a]:[]:CJ(s,i,r);if(jn(),c.length===0){q(t,200,Re,{deletedDocNames:[]},{handler:`trash-cleanup`});return}if(await Rr(c,`deleted-upstream`),At)for(let e of c)oC(e)||cC(e)||(At.setDeleted(e),console.info(JSON.stringify({event:`recently-removed-docs-populate`,docName:e,kind:`deleted`,source:`handleTrashCleanup`})));for(let e of c)w?.({kind:`delete`,path:z(l,CC(e)),docName:e});i===`folder`&&On(r),Ve?.(`files`),q(t,200,Re,{deletedDocNames:c},{handler:`trash-cleanup`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clean up after trash.`,{handler:`trash-cleanup`,cause:e})}}),{handler:`trash-cleanup`,method:`POST`}),Ya=J(g,async(e,t)=>{try{let e=m(),n=[];for(let[t,r]of e){let e=SC(t),i,a;if(r.title!==void 0)i=r.title,a=r.icon;else{i=t;try{let n=V(z(l,`${t}${e}`),`utf-8`);i=cL(n,t),a=lL(n)}catch(e){Y.warn({docName:t,err:e},`[pages] Failed to read title for ${t}`)}}n.push({docName:t,title:i,docExt:e,size:r.size,modified:r.modified,icon:a})}n.sort((e,t)=>e.docName.localeCompare(t.docName)),q(t,200,De,{pages:n},{handler:`pages`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list pages.`,{handler:`pages`,cause:e})}},{handler:`pages`,method:`GET`,skipBodyParse:!0}),k=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`docName`);if(!n){G(t,400,`urn:ok:error:invalid-request`,`Missing docName parameter.`,{handler:`suggest-links`});return}if(!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Invalid docName.`,{handler:`suggest-links`});return}if(oC(n)||cC(n)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${n}' is a reserved document name.`,{handler:`suggest-links`});return}q(t,200,C,await QK({hocuspocus:a,fileIndex:m(),docName:n}),{handler:`suggest-links`})}catch(e){if(e instanceof jK){G(t,404,`urn:ok:error:doc-not-found`,`Page not found.`,{handler:`suggest-links`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to suggest links.`,{handler:`suggest-links`,cause:e})}},{handler:`suggest-links`,method:`GET`,skipBodyParse:!0});async function Xa(e,t){if(e.method!==`POST`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`upload-asset`,extraHeaders:{Allow:`POST`}});return}let n;try{n=await oJ(e,T??l)}catch(e){if(e instanceof aB){G(t,oB(e.reason),e.reason,cB(e.reason),{handler:`upload-asset`,cause:e});return}G(t,400,`urn:ok:error:malformed-upload`,`Failed to parse upload.`,{handler:`upload-asset`,cause:e});return}let{filename:r,tempPath:i,sha:a,byteLength:o,parentDocName:s,placement:c}=n,u=()=>{if(B(i))try{Gl(i)}catch{}},d=KP(xt,{parentDocName:s,placement:c||void 0},t,{handler:`upload-asset`});if(!d.ok){u();return}let{parentDocName:f,placement:p}=d.value,{agentId:m,agentName:g}=bi(Object.fromEntries(new URL(e.url??``,`http://localhost`).searchParams.entries()));if(o===0){u(),G(t,400,`urn:ok:error:no-file-received`,`No file received.`,{handler:`upload-asset`});return}if(f.includes(`\0`)||f.includes(`..`)||f.startsWith(`/`)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}let _=z(l),v;try{v=p===`parent-dir`?`./`:h?.()??`./`}catch(e){u(),Y.error({err:e},`[upload] project config has invalid content.attachmentFolderPath`),G(t,500,`urn:ok:error:internal-server-error`,`Server configuration error: invalid attachment folder path.`,{handler:`upload-asset`,cause:e});return}if(!za(v)){u(),G(t,400,`urn:ok:error:invalid-request`,`Invalid attachment folder path.`,{handler:`upload-asset`});return}let y=tJ(f,Ta(v),_);if(!eA(y,_)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}try{EJ(y,_)}catch(e){if(u(),(e instanceof Error?e.message:String(e)).startsWith(`symlink-escape:`)){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}Y.error({err:e,destDir:y},`[upload] failed to validate destination directory`),G(t,500,`urn:ok:error:storage-error`,`Storage error.`,{handler:`upload-asset`,cause:e});return}try{Nl(y,{recursive:!0})}catch(e){if(!MJ(e)){u();let n=sB(e);G(t,oB(n),n,cB(n),{handler:`upload-asset`,cause:e,detail:`failed to create attachment directory`});return}}try{let e=Bl(y),n;try{n=Bl(_)}catch{n=_}if(!eA(e,n)){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`});return}}catch(e){if(As(e)!==`ENOENT`){u(),G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`upload-asset`,cause:e});return}}let b=nJ(i,4100),x=await Dk(b),S=x?.mime,C=x?.ext;if(!S){let e=b.subarray(0,256).toString(`utf-8`).replace(/^/,``).trimStart();(e.startsWith(`<svg`)||e.startsWith(`<?xml`)&&e.includes(`<svg`))&&(S=`image/svg+xml`,C=`svg`)}{let n=await aJ(y,a,o);if(n){u();let r=Zk(R(l,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:g,dedup:!0,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] dedup hit`),q(t,200,vn,{src:n,path:r,deduped:!0},{handler:`upload-asset`});return}}let w;if(!r||r===`upload`||Zq.test(r)){let e=new Date().toISOString().replace(/[-:T]/g,``).slice(0,14).replace(/(\d{8})(\d{6})/,`$1-$2`),t=r?yl(r).slice(1):``,n=C??t??``;w=n===``?`pasted-${e}`:`pasted-${e}.${n}`}else w=eJ(r);try{let n=pB(i,y,w),r=Zk(R(l,z(y,n)));Y.info({event:`upload`,endpoint:e.url??`/api/upload`,agentId:m,agentName:g,dedup:!1,mime:S??null,size:o,destPath:r,httpStatus:200},`[upload] write ok`),q(t,200,vn,{src:n,path:r,deduped:!1},{handler:`upload-asset`})}catch(n){let r=n instanceof aB?n.reason:`urn:ok:error:storage-error`;Y.error({event:`upload`,endpoint:e.url??`/api/upload`,requestId:jC(e),agentId:m,agentName:g,filename:w,size:o,reason:r,httpStatus:oB(r),err:n},`[upload] write failed`),G(t,oB(r),r,cB(r),{handler:`upload-asset`,cause:n})}}let Za=`/api/local-op/clone`,Qa=`/api/local-op/ok-init`,$a=600*1e3,eo={stdio:[`ignore`,`ignore`,`pipe`]},to={stdio:[`ignore`,`pipe`,`pipe`]},no={stdio:`ignore`},ro=`local-op-clone`,j=J(Ue,io,{handler:ro,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:ro})});async function io(e,t,n){let{url:r,dir:i,branch:a}=n;if(!VU(r)){G(t,400,`urn:ok:error:url-not-allowed`,`URL protocol is not allowed for clone.`,{handler:ro,cause:Error(`url=${r}`)});return}if(!GU(i)){G(t,400,`urn:ok:error:dir-outside-home`,`Clone destination must be within the user home directory.`,{handler:ro,cause:Error(`dir=${i}`)});return}if(!un.tryAcquire(Za)){G(t,429,`urn:ok:error:concurrent-operation`,`A clone operation is already in progress.`,{handler:ro,extraHeaders:{"Retry-After":`30`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let o=IC(t,ro),s=null,c=uW({cliArgs:it,url:r,dir:i,branch:a,timeoutMs:$a,onEvent:e=>{if(e.type===`complete`){s=e.dir;return}if(e.type===`error`){e.message&&Y.warn({stderr:AL(e.message),url:r,dir:i},`[local-op/clone] clone failed`);let t=iW(e.message??``);o(500,`urn:ok:error:clone-failed`,t.title,{detail:t.detail||void 0,cause:e.message?Error(AL(e.message)):void 0});return}if(!t.writableEnded&&!t.destroyed)try{t.write(`${JSON.stringify(e)}\n`)}catch{}}});(async()=>{try{if(await c.done,s&&!t.writableEnded&&!t.destroyed){let e=await ao(s);!t.writableEnded&&!t.destroyed&&(`port`in e?t.write(`${JSON.stringify({type:`complete`,port:e.port,dir:s})}\n`):o(500,`urn:ok:error:server-start-failed`,`Cloned successfully but failed to start the project server.`,{cause:Error(e.error)}))}}catch(e){!t.writableEnded&&!t.destroyed?o(500,`urn:ok:error:internal-server-error`,`Unexpected error during clone post-processing.`,{cause:e}):Y.error({err:e,handler:ro},`clone IIFE rejected after stream ended`)}finally{t.writableEnded||t.end(),un.release(Za)}})(),t.on(`close`,()=>{c.cancel()})}async function ao(e,t){let n=z(HU(e)),r=zA(n),i=nB(r);if(i&&i.port>0)return{port:i.port};let[a,...o]=it,s=e=>{let n=t===void 0?[]:e===`ui`?[`--port`,String(t)]:[`--ui-port`,String(t)];return[...o,e,...n]},c=async e=>{let t=ml(a,s(e),OP({...eo,cwd:n,detached:!0,env:{...process.env,OK_LOCK_KIND:`interactive`}})),i=[];t.stderr?.on(`data`,t=>{i.push(t),Y.warn({cwd:n,cliCmd:e,msg:t.toString(`utf-8`).trim()},`[local-op/clone] child stderr`)});let o=null,c=null,l=null;t.on(`exit`,(e,t)=>{o=e??-1,c=t??null}),t.on(`error`,t=>{l=t.message,o=-1,Y.error({cwd:n,cliCmd:e,err:t},`[local-op/clone] failed to spawn child`)}),t.unref();let u=Date.now()+45e3;for(;Date.now()<u;){await _u(500);let t=nB(r);if(t&&t.port>0)return{port:t.port};if(o!==null){let t=Buffer.concat(i).toString(`utf-8`).trim();return{error:`\`ok ${e}\` exited (${l?`spawn failed: ${l}`:c?`killed by ${c}`:`code ${o}`})${t?` — ${t}`:``}`,exited:!0}}}let d=Buffer.concat(i).toString(`utf-8`).trim();return{error:`UI did not start within the expected time${d?` — ${d}`:``}`,exited:!1}},l=ws(r),u=l&&l.port>0?`ui`:`start`,d=await c(u);if(u===`start`&&`error`in d&&d.exited){let e=ws(r);if(e&&e.port>0){let e=await c(`ui`);return`port`in e?e:{error:`${d.error}; connect fallback failed: ${e.error}`}}}return`port`in d?d:{error:d.error}}let oo=`local-op-ok-init`,so=J(pee,async(e,t,n)=>{let{projectPath:r}=n;if(!bl(r)){G(t,400,`urn:ok:error:invalid-request`,`projectPath must be an absolute path.`,{handler:oo,cause:Error(`projectPath=${r}`)});return}let i;try{i=Bl(r)}catch(e){q(t,200,fa,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath does not exist or is not accessible: ${e.message}`},{handler:oo});return}if(!GU(i)){G(t,400,`urn:ok:error:dir-outside-home`,`projectPath must be within the user home directory.`,{handler:oo,cause:Error(`projectPath=${r}`)});return}let a=Du(i).kind;if(a!==`directory`&&a!==`linked`){Y.warn({project:_l(i),result:`not-a-git-worktree`,kind:a},`[ok-init] action=init project=${_l(i)} result=not-a-git-worktree kind=${a}`),q(t,200,fa,{ok:!1,reason:`not-a-git-worktree`,message:`projectPath is not a git working tree (.git is ${a}).`},{handler:oo});return}if(sH(i)){Y.warn({project:_l(i),result:`already-initialized`},`[ok-init] action=init project=${_l(i)} result=already-initialized`),q(t,200,fa,{ok:!0,projectPath:i},{handler:oo});return}if(!un.tryAcquire(Qa)){G(t,429,`urn:ok:error:concurrent-operation`,`An ok-init operation is already in progress.`,{handler:oo,extraHeaders:{"Retry-After":`2`}});return}try{await fs(async()=>{RH(i)}),Y.warn({project:_l(i),result:`success`},`[ok-init] action=init project=${_l(i)} result=success`),q(t,200,fa,{ok:!0,projectPath:i},{handler:oo})}catch(e){let n=e instanceof Error?e.message:String(e);Y.warn({project:_l(i),result:`failed`,reason:n},`[ok-init] action=init project=${_l(i)} result=failed reason=${n}`),q(t,200,fa,{ok:!1,reason:`init-failed`,message:n},{handler:oo})}finally{un.release(Qa)}},{handler:oo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:oo})}),co=`/api/local-op/auth/login`,lo=`/api/local-op/auth/status`,uo=`/api/local-op/auth/repos`,fo=`/api/local-op/auth/signout`,po=`/api/local-op/auth/pat`,mo=`/api/local-op/auth/gh-login`,ho=at??15e3,go=960*1e3,xo=()=>gL(T??l),Co={current:null},wo={current:null};function To(e){let{res:t,handler:n,guardKey:r,inFlight:i,concurrentMessage:a,streamErrorMessage:o,makeFlow:s}=e;if(!un.tryAcquire(r)){let e=i.current;if(!e){console.error(JSON.stringify({event:`ok-local-op:auth-flow-slot-no-controller`,channel:`auth`,transport:`http`,handler:n})),G(t,429,`urn:ok:error:concurrent-operation`,a,{handler:n,extraHeaders:{"Retry-After":`5`}});return}e.cancel(),i.current=null,console.warn(JSON.stringify({event:`ok-local-op:idempotent-start-replaced-stale-slot`,channel:`auth`,transport:`http`,handler:n}))}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let c=IC(t,n),l=e=>{if(!(t.writableEnded||t.destroyed))try{t.write(e)}catch{}},u=setInterval(()=>{l(`${JSON.stringify({type:`ping`})}\n`)},ho);u.unref();let d=()=>{u!==null&&(clearInterval(u),u=null)},f=s(e=>{if(e.type===`error`){c(500,`urn:ok:error:auth-failed`,o,{cause:e.message?Error(e.message):void 0});return}Gq(e,$e),l(`${JSON.stringify(e)}\n`)});i.current=f;let p=()=>{d(),i.current===f&&console.warn(JSON.stringify({event:`ok-local-op:auth-stream-detached`,channel:`auth`,transport:`http`,handler:n}))};t.on(`close`,p),f.done.finally(()=>{if(d(),t.off(`close`,p),!t.writableEnded&&!t.destroyed)try{t.end()}catch{}i.current===f&&(i.current=null,un.release(r))})}let Eo=`local-op-auth-login`,Do=J(Ji,ko,{handler:Eo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Eo})});async function ko(e,t,n){let r=n.host??xo();To({res:t,handler:Eo,guardKey:co,inFlight:Co,concurrentMessage:`An auth login operation is already in progress.`,streamErrorMessage:`Auth subprocess reported an error.`,makeFlow:e=>QU({cliArgs:it,host:r,timeoutMs:go,onEvent:e})})}let Ao=`local-op-auth-gh-login`,jo=J(Ji,async(e,t,n)=>{let r=n.host??xo(),i=await vW();if(i===null){G(t,400,`urn:ok:error:auth-failed`,`The GitHub CLI (gh) is not installed.`,{handler:Ao});return}To({res:t,handler:Ao,guardKey:mo,inFlight:wo,concurrentMessage:`A gh sign-in is already in progress.`,streamErrorMessage:`gh sign-in reported an error.`,makeFlow:e=>xW({host:r,ghPath:i,timeoutMs:go,onEvent:e})})},{handler:Ao,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ao})}),No=`local-op-auth-cancel`,Po=J(iee,EH(async(e,t,n)=>{let r=n.channel===`gh-login`?{inFlight:wo,guardKey:mo}:{inFlight:Co,guardKey:co},i=r.inFlight.current;i&&(i.cancel(),r.inFlight.current=null,un.release(r.guardKey)),q(t,200,Yr,{},{handler:No})},{handler:No,title:`Failed to cancel the sign-in.`}),{handler:No,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:No})}),Io=`local-op-auth-status`,Lo=J(Ji,async(e,t,n)=>{let r=n.host??xo();if(!un.tryAcquire(lo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth status operation is already in progress.`,{handler:Io,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`status`,`--json`,`--host`,r],a=(await new Promise((t,n)=>{let r=ml(e,i,OP({...to,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,r.kill(`SIGTERM`)},3e4),s=[];r.stdout.on(`data`,e=>s.push(e)),r.on(`close`,()=>{if(clearTimeout(o),a){n(Error(`auth status subprocess timed out after 30s`));return}t(Buffer.concat(s).toString(`utf-8`))}),r.on(`error`,e=>{clearTimeout(o),n(e)})})).split(`
1227
1227
  `).map(e=>e.trim()).filter(Boolean),o=null;for(let e=a.length-1;e>=0;e--)try{o=JSON.parse(a[e]);break}catch{}let s=await vW()!==null;o===null?q(t,200,ti,{authenticated:!1,ghAvailable:s},{handler:Io}):q(t,200,ti,{...o,ghAvailable:s},{handler:Io})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth status check failed.`,{handler:Io,cause:e})}finally{un.release(lo)}},{handler:Io,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Io})}),Ro=`local-op-auth-pat`,Bo=J(oee,async(e,t,n)=>{let r=n.host??xo();if(!un.tryAcquire(po)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth operation is already in progress.`,{handler:Ro,extraHeaders:{"Retry-After":`5`}});return}try{let e=await $U({cliArgs:it,host:r,token:n.token});e.ok?(Wq($e),q(t,200,ur,{host:e.host,login:e.login},{handler:Ro})):G(t,400,`urn:ok:error:auth-failed`,e.error,{handler:Ro})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Storing the token failed.`,{handler:Ro,cause:e})}finally{un.release(po)}},{handler:Ro,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Ro})}),Vo=`local-op-auth-repos`,Ho=J(Ji,Uo,{handler:Vo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Vo})});async function Uo(e,t,n){let r=n.host??xo();if(!un.tryAcquire(uo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth repos operation is already in progress.`,{handler:Vo,extraHeaders:{"Retry-After":`5`}});return}t.writeHead(200,{"Content-Type":`application/x-ndjson`,"Transfer-Encoding":`chunked`,"X-Content-Type-Options":`nosniff`,"Cache-Control":`no-cache`});let i=IC(t,Vo),[a,...o]=it,s=[...o,`auth`,`repos`,`--json`,`--host`,r],c=!1,l=``,u=ml(a,s,OP({...to,env:{...process.env}})),d=setTimeout(()=>{u.kill(`SIGTERM`)},$a);u.stdout.on(`data`,e=>{l+=e.toString(`utf-8`);let n=l.split(`
1228
- `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Y.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),un.release(uo))}),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()),un.release(uo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),un.release(uo))})}let Yo=`local-op-auth-signout`,Xo=J(Ji,async(e,t,n)=>{let r=n.host??xo();if(!un.tryAcquire(fo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Yo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=ml(e,i,OP({...no,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,Yr,{},{handler:Yo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Yo,cause:e})}finally{un.release(fo)}},{handler:Yo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Yo})}),Qo=`/api/local-op/auth/set-identity`,es=`local-op-auth-set-identity`,ts=J(xi,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!T){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:es});return}if(!un.tryAcquire(Qo)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:es,extraHeaders:{"Retry-After":`5`}});return}try{TH(T,r,i),$e?.()?.refreshIdentity().catch(()=>{}),q(t,200,Yr,{},{handler:es})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:es,cause:e})}finally{un.release(Qo)}},{handler:es,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:es})});async function ns(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();if(!e){q(t,200,Br,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,Br,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let is=J(d,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Fr,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function os(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();q(t,200,le,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let ss=J(re,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,dt,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function cs(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=_C(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=$e?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=ds({baseDir:T,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),o=_C(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Nt?Nt(o):null;t!==null&&(c=t,l=!0)}else{Zz(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,Lt,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=_C(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Nt?Nt(e):null;t!==null&&!Jq(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,Lt,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function us(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=aK(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,gee,{plan:await xK({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof qG){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof JG){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let ps=J(aa,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=aK(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,nee,{result:await gK(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function ms(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,x,{packs:sK()},{handler:`seed-packs`})}}let hs=J(da,async(e,t,n)=>{if(n.out!==void 0&&!GU(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,Rn,await ER({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function gs(e,t){if(r(e,t,{handler:`installed-agents`}))try{await IP(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let _s=J(g,async(e,t)=>{if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Or,{tags:Le.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function vs(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=Le.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Wn(e),matchingTags:t,snippet:null}));q(t,200,fee,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function ys(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(l),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${Cl}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let bs=/^[A-Za-z0-9_-]+$/;function xs(e,t,n=`template`){return!e||!bs.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Ss(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}${Cl}`))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 Cs(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 Ts=DH({GET:J(g,async(e,t)=>{try{let n=ys(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await mM(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,kk.parse)(await iu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Y.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,Bt,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:J(fe,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=ys(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=yM({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(Oi(e,Di(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await ki(`folder-config-put`))}q(t,200,oe,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function Es(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&RC(o)?(UC(r,new HC({file:`${i}.md`}),n),!0):!1}function Ds(e,t,n){let r=a.documents.get(e);return r&&RC(r)?(UC(n,new HC({file:`${e}.md`}),t),!0):!1}let Os=J(g,EH(async(e,t)=>{let n=Kj(z(l));q(t,200,yi,{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}),ks=e=>{let{body:t}=ea(e);return{frontmatter:rt(e)??{},body:t}},js=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!xs(r,t,`template-get`))return;let i=ys(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Ss(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=Sn(await iu(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,pi,{template:{name:r,folder:l,scope:u,path:R(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ms=J(Xn,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!xs(r,t,`template-put`))return;let i=ys(n.folder,t,`folder`,`template-put`);if(!i||Es(i.folderRel,r,`template-put`,t))return;let a=YM({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Cs(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=Ws(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=bi(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{nS(h.dc.document,a.content,`agent`)},h.origin);let g=await mr(u);if(g?.kind===`failure`){_r(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){vr(t,`template-put`);return}Oi(e,Di(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await ki(`template-put`),q(t,200,cr,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ns=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!xs(r,t,`template-delete`))return;let i=ys(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=_V({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},ut);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Es(i.folderRel,r,`template-delete`,t))return;await Rr([Ws(i.folderRel,r)],`deleted-upstream`);let s=ZM({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!s.ok){let e=s.error.code===`WRITE_ERROR`||s.error.code===`UNLINK_FAILED`||s.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:s.error.code,cause:Error(s.error.message)});return}s.existed&&(Oi(o,Di(`template`,i.folderRel,r),`template-delete: ${s.path}`),await ki(`template-delete`)),q(t,200,Mn,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ps=DH({GET:js,PUT:Ms,POST:J(qr,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!xs(n.fromName,t,`template-move`)||!xs(n.toName,t,`template-move`))return;let r=ys(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=ys(n.toFolder,t,`folder`,`template-move`);if(!i||Es(r.folderRel,n.fromName,`template-move`,t))return;await Rr([Ws(r.folderRel,n.fromName)],`renamed`);let a=await $M({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await ZJ(T,e,t);return n||XJ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Ss(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}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=dr(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=XM({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Cs(n.frontmatter)});t.ok||(o=t.error)}}if(Oi(e,Di(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await ki(`template-move`),Ve?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Ki,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ns},{handler:`template`}),Fs=J(Mi,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!eY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=ir(r);if(oC(i)||cC(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let o=DJ(l,`file`,i);if(!B(o)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let c=a.documents.get(i);if(n.deleteSource){let e=$e?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&RC(c),a=n.has(r);if(i||a){UC(t,new HC({file:r}),`template-import`);return}}let u=``;if(c)u=c.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=OJ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!xs(d,t,`template-import`))return;let f=ys(n.targetFolder,t,`folder`,`template-import`);if(!f||Es(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=ea(u),h=Ft(p),g={};try{h.trim()&&(g=(0,kk.parse)(h))}catch{}let _=n.title||g?.title||cL(u,d),v=g?.description||``,y=Array.isArray(g?.tags)?g.tags:[],b={...g};delete b.template,delete b.title;let x=``;Object.keys(b).length>0&&(x=`${(0,kk.stringify)(b).trim()}\n`),x=x?`---\n${x}---\n${m}`:m;let S=YM({name:d,body:x,frontmatter:{title:_,description:v,tags:y}});if(!S.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:S.error.code,cause:Error(S.error.message)});return}let C=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(C),te=R(f.resolvedContentDir,C).split(/[\\/]/).filter(Boolean).join(`/`),ne=Ws(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=bi(n),se=await s.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{nS(se.dc.document,S.content,`agent`)},se.origin);let ce=await mr(ne);if(ce?.kind===`failure`){_r(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){vr(t,`template-import`);return}Oi(e,Di(`template`,f.folderRel,d),`template-import: ${te}`),n.deleteSource&&(await Rr([i],`deleted-upstream`),At&&At.setDeleted(i),zo(o),w?.({kind:`delete`,path:o,docName:i})),await ki(`template-import`),Ve?.(`files`),q(t,200,Gn,{path:te,created:ee,warnings:S.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Is(e,t,n){return!e||e.length>64||!mt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Ls(e,t,n){let r=uee.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Rs=ft??Xl();function zs(e){return z(e===`global`?Rs:l,`.ok`,`skills`)}let Bs=FL.project;function Vs(){if(!T)return null;let e=[],t=null;for(let n of He){let r=$t[n];if(!r)continue;let i=z(T,...r.split(`/`),Bs);B(z(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=z(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:R(T,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Hs(){let e=Vs();if(!e)return null;let t;try{let{frontmatter:n}=ks(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Bs,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Us(e,t,n){return LL(e)?(G(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is a built-in skill managed by OpenKnowledge and can't be edited, renamed, or deleted.`,{handler:n}),!0):!1}function Ws(e,t){return`${Nn}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Gs(e){return e===`navigation`||e===`relevance`?e:void 0}function Ks(e,t){return R(t===`global`?Rs:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function qs(e){return e===`global`?Rs:T}async function Js(e,t){let n=await _F(e,t);return hz(t,e,He),n!==null}function Ys(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Rl(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()||!mt.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,s;try{let{frontmatter:e}=ks(V(r,`utf-8`));typeof e.description==`string`&&(o=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(s=e.version)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Ks(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Xs=J(g,EH(async(e,t)=>{let n=Ys(zs(`project`),`project`),r=Ys(zs(`global`),`global`),i=T?mF(T).skills:{},a=mF(Rs).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Dz(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Bs)?null:Hs();q(t,200,zi,{skills:[...o(n,i),...o(r,a),...s?[s]:[]],truncated:n.truncated||r.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Zs=O({managed:M().nullable(),importable:P().int().nonnegative()}),Qs=()=>({managed:T?AR(T)?.manageEditorSkills??null:null,importable:T?Hz({projectDir:T,skillsRoot:zs(`project`)}):0}),$s=DH({GET:J(g,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Zs,Qs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(O({manageEditorSkills:M()}),async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await jR(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await Uz({projectDir:T,skillsRoot:zs(`project`)});e.adopted.length+e.collided.length>0&&Ve?.(`files`)}q(t,200,Zs,Qs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),ec=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-get`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Bs&&i===`project`){let e=Vs();if(e){let{frontmatter:n,body:a}=ks(await iu(e.skillMd,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:yz(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=zs(i),o=z(a,r,`SKILL.md`);if(!B(o)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${r}" not found in ${i} scope.`});return}let{frontmatter:s,body:c}=ks(await iu(o,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:Ks(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:yz(z(a,r))}},{handler:`skill-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),tc=J(Kt,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Is(n.name,t,`skill-put`)||Us(n.name,t,`skill-put`))return;let r=EM({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=zs(n.scope),a=z(i,n.name,`SKILL.md`),o=!B(a),c=R(i,a).split(/[\\/]/).filter(Boolean).join(`/`),l=hr(n.scope,n.name);if(Ds(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=bi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{nS(m.dc.document,r.content,`agent`)},m.origin);let h=await mr(l);if(h?.kind===`failure`){_r(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){vr(t,`skill-put`);return}n.scope===`project`&&(Oi(e,Di(`skill`,``,n.name),`${o?`skill-create`:`skill-edit`}: ${c}`),await ki(`skill-put`)),Ve?.(`files`),q(t,200,rn,{path:c,created:o,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),nc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-delete`)||Us(r,t,`skill-delete`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=zs(i),o=n.searchParams,s=_V({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Rr([hr(i,r)],`deleted-upstream`);let c=MM({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(Oi(s,Di(`skill`,``,r),`skill-delete: ${c.path}`),await ki(`skill-delete`)),Ve?.(`files`));let l=qs(i);l&&await Js(l,r),q(t,200,nt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),rc=DH({GET:ec,PUT:tc,POST:J(Zt,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Is(n.fromName,t,`skill-move`)||!Is(n.toName,t,`skill-move`)||Us(n.fromName,t,`skill-move`)||Us(n.toName,t,`skill-move`))return;let r=zs(n.scope);await Rr([hr(n.scope,n.fromName)],`renamed`);let i=await NM({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await ZJ(T,e,t);return n||XJ(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,i.error.message,{handler:`skill-move`,detail:i.error.code});return}let e=i.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:i.error.code,cause:Error(i.error.message)});return}let a=null,o=z(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=ks(V(o,`utf-8`));s=e.body,typeof e.frontmatter.description==`string`&&(c=e.frontmatter.description)}catch{}let l=typeof n.body==`string`?n.body:s,u=n.frontmatter===void 0?c:n.frontmatter.description,d=DM({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{cc(r,n.fromName,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 f=Ks(z(r,n.fromName),n.scope),p=Ks(z(r,n.toName),n.scope);n.scope===`project`&&(Oi(e,Di(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await ki(`skill-move`));let m=qs(n.scope);if(m){let e=await _F(m,n.fromName);if(e){let t=nz(e.hosts);hz(n.fromName,m,t);let i=mz(z(r,n.toName),n.toName,m,t);await gF(m,n.toName,{...e,hosts:i})}}if(Ve?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,ke,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:nc},{handler:`skill`});function ic(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function ac(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function oc(e,t){let n=t.replace(/\.md$/i,``);return`${ei(e).replace(/\/SKILL$/,``)}/${n}`}function sc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Rl(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}function cc(e,t,n){if(!Ie)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Ie.deleteDocument(e),Le?.deleteDocument(e);return}Ie.renameDocument(e,t,r),Le?.renameDocument(e,t,r)};r(ei(t),ei(n),z(e,n,`SKILL.md`));for(let i of sc(e,n))r(oc(t,i),oc(n,i),z(e,n,i));Ve?.(`backlinks`),Ve?.(`graph`)}let lc=DH({GET:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-file-get`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Bs&&i===`project`?Vs():null,s=o&&a===`SKILL.md`?`reference`:ic(a);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let c=o?o.dir:z(zs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${Cl}`)){G(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let u=l,d=a;if(!B(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?_n.map(t=>`${e[1]}${t}`).find(e=>e!==a&&B(z(c,e))):void 0;if(n===void 0){G(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}d=n,u=z(c,n)}let f=await iu(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,yt,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ve,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Is(n.name,t,`skill-file-put`)||Us(n.name,t,`skill-file-put`))return;let r=ic(n.path);if(r===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=zs(n.scope);if(!B(z(i,n.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=n.path.replace(/\\/g,`/`),o=ac(n.scope,r,a),c;if(o){let e=oc(n.name,a);if(Ds(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,a)),c&&kM(z(i,n.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:o,colorSeed:l,clientName:u}=bi(n),d=await s.getSession(e,r,{displayName:o,colorSeed:l,clientName:u});d.dc.document.transact(()=>{nS(d.dc.document,n.content,`agent`)},d.origin);let f=await mr(e);if(f?.kind===`failure`){_r(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){vr(t,`skill-file-put`);return}}else{let e=AM({skillsRoot:i,name:n.name,relPath:a,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Oi(e,Di(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${a}`),await ki(`skill-file-put`)),Ve?.(`files`),q(t,200,Pe,{path:a,created:c,kind:r,content:o},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Is(r,t,`skill-file-delete`)||Us(r,t,`skill-file-delete`))return;let i=Ls(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=ic(a);if(o===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let s=_V({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},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=zs(i);ac(i,o,a)&&await Rr([oc(r,a)],`deleted-upstream`);let l=jM({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:l.error.code,cause:Error(l.error.message)});return}l.existed&&i===`project`&&(Oi(s,Di(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await ki(`skill-file-delete`)),l.existed&&Ve?.(`files`),q(t,200,ct,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),uc=J(Ot,async(e,t,n)=>{try{let e=zs(n.scope);if(!Is(n.name,t,`skill-install`)||Us(n.name,t,`skill-install`))return;if(n.scope===`project`&&!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=qs(n.scope),i=z(e,n.name);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}let a=cz(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?He.filter(e=>n.targets?.some(t=>t===e)):[...He]:n.targets===void 0?uz(r,Yz(r)??void 0):He.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.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`."),c.push(`no-targets`)),a.hasScripts&&(s.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."),c.push(`scripts-present`));let l=nz(mF(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&hz(n.name,r,l);let u=mz(i,n.name,r,o);u.length===0?await _F(r,n.name):await gF(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ve?.(`files`),q(t,200,v,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),dc=J(xn,async(e,t,n)=>{try{if(!Is(n.name,t,`skill-uninstall`)||Us(n.name,t,`skill-uninstall`))return;let e=qs(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Js(e,n.name);Ve?.(`files`),q(t,200,tee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),fc=DH({GET:J(g,EH(async(e,t)=>{let n=T?Yz(T):null;q(t,200,Be,{targets:uz(T??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(hn,EH(async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=uz(T,Yz(T)??void 0),o=zs(`project`);await Xz(T,r);let{reprojected:s,bundleHosts:c}=await Kz({projectDir:T,skillsRoot:o,targets:r});Ve?.(`files`),q(t,200,ln,{targets:r,reprojected:s,bundleHosts:c,removedFrom:a.filter(e=>!i.has(e))},{handler:`skill-targets-put`})},{handler:`skill-targets-put`,title:`Failed to set skill targets.`}),{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),pc=J(we,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Is(n.name,t,`skill-restore`)||Us(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=be?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await OK({shadow:r,contentDir:l,contentRoot:Fe??`.`,name:n.name,version:n.version});if(!i.ok){let[e,n]={"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`]}[i.code];G(t,e,n,i.error,{handler:`skill-restore`,detail:i.code});return}let a=[],o=cz(z(l,`.ok`,`skills`,n.name),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Oi(e,Di(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await ki(`skill-restore`),Ve?.(`files`),q(t,200,Ke,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),mc=J(c,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Is(n.name,t,`skill-update`)||Us(n.name,t,`skill-update`))return;if(!bz(n.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let r=Tz(n.name);if(r===null||r.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let i=z(zs(`project`),n.name,`SKILL.md`);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let a;try{a=Sz(V(i,`utf-8`))}catch{}let o,c=be?.current;if(c)try{let e=Oe?.()??`main`;o=(await nC(c,Fe??`.`,[qS],e,`Before updating ${n.name} (${a??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=hr(`project`,n.name);if(Ds(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=bi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{nS(m.dc.document,r.content,`agent`)},m.origin);let h=await mr(l);if(h?.kind===`failure`){_r(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){vr(t,`skill-update`);return}Oi(e,Di(`skill`,``,n.name),`skill-pack-update: ${n.name} (${a??`unversioned`} → ${r.version})`),await ki(`skill-update`),Ve?.(`files`),q(t,200,tr,{name:n.name,version:r.version,...a===void 0?{}:{previousVersion:a},...o===void 0?{}:{checkpointRef:o}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function hc(e){let t=new Map;for(let n of e){let e=n.path.split(`/`).filter(Boolean);e.pop();for(let r=1;r<=e.length;r++){let i=e.slice(0,r).join(`/`);t.set(i,Math.max(t.get(i)??0,n.modifiedTs))}}return[...t.entries()].map(([e,t])=>Pt({kind:`folder`,path:e,modifiedTs:t}))}function gc(e,t){let n=t.trim().toLowerCase();if(!n||!e)return;let r=e.toLowerCase().indexOf(n);if(r<0)return;let i=Math.max(0,r-80),a=Math.min(e.length,r+n.length+120),o=i>0?`…`:``,s=a<e.length?`…`:``;return`${o}${e.slice(i,a).replace(/\s+/g,` `).trim()}${s}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function _c(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function vc(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 yc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function bc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function xc(e,t,n,r){let i=r.documents.filter(e=>!fr(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Vt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Vt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Vt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Ht?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Vt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Sc(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?gc(e.document.content,t):void 0}}async function Cc(e){let t=performance.now();if(Mc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Nc(),i=await xc(e.query,e.intent,e.semanticParam,n),a=se(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Sc(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0;o={...i.status,applied:n},zN({outcome:i.capable?n?`applied`:i.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:i.capable,embedded:i.status.coverage.embedded,total:i.pageTotal,queryEmbedMs:i.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:a,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...o?{semantic:o}:{},...r?{truncated:!0}:{}}}function wc(){let e=zs(`project`);if(!B(e))return[];let t;try{t=Rl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!mt.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=Wl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function Tc(){let e=[];for(let t of wc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=ks(V(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(n=e.name),r=`${typeof e.description==`string`?e.description:``}\n\n${i}`.trim()}catch{}e.push(Pt({kind:`page`,path:hr(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function Ec(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Dc=new Map;async function Oc(){let e=[],t=[],n=new Set;for(let[r,i]of S()){if(oC(r)||cC(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Pt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=Ec(i),o=Dc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await iu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=cL(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=Pt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Dc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Dc.keys())n.has(e)||Dc.delete(e);let r=fJ(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),Bq().add(1)),{documents:[...e,...Tc(),...i,...hc([...e,...i])],truncated:a}}function kc(){return wc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Ac(){return te?`gen:${te()}|skills${kc()}`:`${[...S()].filter(([e])=>!oC(e)&&!cC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ec(t)}`).join(``)}|skills${kc()}`}let jc=kt===void 0;kt?.then(()=>{jc=!0},e=>{jc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Mc(){return!jc}async function Nc(){let e=`${l}${T??``}`,t=Ac(),n=QJ.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,i=n?.pending,a=(async()=>{let e=i?await i.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await Oc();if(!e)return Hq().add(1,{mode:`cold`}),{corpus:mee(t),truncated:n};let a=ee(e,t);if(a.rebuilt){Hq().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else Hq().add(1,{mode:`incremental`}),F(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();QJ.set(e,{fingerprint:t,pending:a});try{let n=await a;return QJ.get(e)?.pending===a&&QJ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw QJ.get(e)?.pending===a&&QJ.delete(e),t}}function Pc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Nc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Pc();let Fc=DH({GET:J(g,EH(async(e,t)=>{let n=xee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=_c(n.get(`intent`)),o=Gs(n.get(`ranking`)),s=vc(n.get(`scope`)??n.get(`scopes`)),c=yc(n.get(`semantic`)),l=bc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,p,await Cc({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Ur,EH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=_c(n.intent),a=Gs(n.ranking),o=vc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=yc(n.semantic),l=bc(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,p,await Cc({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`}),Ic=J(g,EH(async(e,t)=>{q(t,200,va,{...await mR(Xl())},{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 Lc(e,t){if(r(e,t,{handler:`handoff`}))try{await Nae(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Rc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await ZP(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let zc=J(dee,async(e,t,n)=>{try{if(!T){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!use(e,n.kind)){dL(`invalid-path`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`invalid-path`},{handler:uL});return}let r=hse(T);if(r===null){if(hL(T).kind===`no-remote`){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}dL(`detached-head`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`detached-head`},{handler:uL});return}let i=hL(T);if(i.kind===`no-remote`){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}if(i.kind===`non-github`){dL(`non-github-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`non-github-remote`},{handler:uL});return}if(!bse(T,r)){dL(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Er,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:uL});return}let a=WJ(T,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=dse(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=fse(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Sh(s)}`,u=await pse(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);dL(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Er,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:uL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uL,cause:e})}},{handler:uL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:uL})}),Bc=J(g,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:fH});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(!yr(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:fH});return}if(!uH(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:fH});return}q(t,200,$n,await dH(T,r,i,a),{handler:fH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:fH,cause:e})}},{handler:fH,method:`GET`,skipBodyParse:!0}),Vc=J(Wi,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:jL});return}if(!uH(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:jL});return}let e=WJ(T,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}`;q(t,200,aee,await PL(T,n.branch,r,n.kind),{handler:jL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jL,cause:e})}},{handler:jL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jL})}),Hc=J(Li,async(e,t,n)=>{if(_V(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:_H});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:_H});return}try{q(t,200,ii,await fs(()=>yH(T,n.branch,{fastForward:n.fastForward===!0})),{handler:_H})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:_H,cause:e})}},{handler:_H,method:`POST`});async function Uc(e){let[t,...n]=it,r=[...n,...e];return await new Promise((e,n)=>{let i=ml(t,r,OP({...to,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},bL),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 ${bL}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=AL(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Wc=J(g,async(e,t)=>{if(!un.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:_L,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Uc([`share`,`owners`,`--json`]),n=xse(CL(e));kL(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Ai,n,{handler:_L})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:_L,cause:e})}finally{un.release(`/api/share/publish/owners`)}},{handler:_L,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:_L})}),Gc=J(g,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!SL(r)||!xL(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:vL});return}if(!un.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:vL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Uc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=TL(CL(e));kL(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,di,n,{handler:vL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vL,cause:e})}finally{un.release(`/api/share/publish/name-check`)}},{handler:vL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:vL})}),Kc=J(Un,async(e,t,n)=>{if(!T){kL(`publish-create`,`no-project`),q(t,200,Gr,{ok:!1,error:`no-project`},{handler:yL});return}if(!SL(n.owner)||!xL(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:yL});return}if(!un.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:yL,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,T,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Uc(e),i=OL(CL(r));kL(`publish-create`,i.ok?`ok`:i.error),i.ok&&$e?.()?.refreshRemote().catch(()=>{}),q(t,200,Gr,i,{handler:yL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yL,cause:e})}finally{un.release(`/api/share/publish`)}},{handler:yL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:yL})}),qc=J(_,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{}q(t,200,Xt,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Jc=T?zA(T):null;async function Yc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:LA(e.headers),previewUrl:null,port:Jc?ws(Jc)?.port??0:0,singleFile:an};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,xe,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let Xc=`local-op-embeddings-set-key`,Zc=`local-op-embeddings-clear-key`,Qc=`/api/local-op/embeddings`;function $c(){let e=Jt?.();return{projectDir:T??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let el=J(gr,async(e,t,n)=>{if(!un.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Xc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=$c();await new dP(qt).setForProject(e,r,n.key),Vt?.reloadCredential(),q(t,200,Cr,{keyPresent:!0},{handler:Xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Xc,cause:e})}finally{un.release(Qc)}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Xc})}),tl=J(g,async(e,t)=>{if(!un.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=$c();await new dP(qt).clearForProject(e,n),Vt?.reloadCredential(),q(t,200,Cr,{keyPresent:!1},{handler:Zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Zc,cause:e})}finally{un.release(Qc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zc})}),nl=`local-op-embeddings-test`,rl=`/api/local-op/embeddings/test`,il=J(g,async(e,t)=>{if(!un.tryAcquire(rl)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Jt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await eP(new dP(qt),T??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await nP({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,Dn,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:nl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:nl,cause:e})}finally{un.release(rl)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nl})}),al=J(g,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Vt){let t=Vt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Jt?.()?.baseUrl??`https://api.openai.com/v1`,o=await eP(new dP(qt),T??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,f=0;for(let[e]of m())!oC(e)&&!cC(e)&&!fr(e)&&(f+=1);q(t,200,Lr,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function ol(e,t){let n=Qt?.()??zr;try{let r=await Gi(e,VI(l,n,{docName:t,projectDir:T??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=en?.()??`warning`;if(Ie&&a!==`off`&&!fC(t)){Ie.updateDocumentFromMarkdown(t,e);let r=$I({projectDir:T??l,contentDir:l,baseConfig:n,backlinkIndex:Ie,linksValidation:a,admittedDocNames:Sr,docFilePathFor:e=>FJ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:FJ(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}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function sl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=UI({projectDir:T??l,contentDir:l});return pI(t.schemas,n)}let cl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!eY(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Qt?.()??zr,i=[],a=RI(l,n??void 0,e=>i.push(e)),o=BI(T??l,zI(r,a),e=>i.push(e));n===null&&i.push(...sl(o)),q(t,200,jt,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),ll=J(ce,async(e,t,n)=>{let r;try{r=QI(z(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Ve?.(`lint-config`);try{let e=Qt?.()??zr,n=[],r=RI(l,void 0,e=>n.push(e)),i=BI(T??l,zI(e,r),e=>n.push(e));n.push(...sl(i)),q(t,200,jt,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),ul=J(ua,async(e,t,n)=>{let r;try{let e=z(T??l),t=n.parentPath??[];r=n.delete?Joe(e,n.file):n.field!==void 0&&n.removeField?Koe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?qoe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Woe(e,n.file,n.field,n.constraint,t):Goe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ve?.(`files`),Ve?.(`lint-config`);try{let e=Qt?.()??zr,n=[],r=RI(l,void 0,e=>n.push(e)),i=BI(T??l,zI(e,r),e=>n.push(e));n.push(...sl(i)),q(t,200,jt,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),dl=J(g,async(e,t)=>{try{let e=z(T??l),{schemas:n,truncated:r}=yoe(e),i=new Set(n),a=!1;if(Ct!==void 0){let t=vJ({contentDir:l,contentFilter:Ct,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&&pr(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!bl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,Ln,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),fl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},pl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=FJ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Qt?.()??zr,a=[],o=await HI({projectDir:T??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:fl});q(t,200,b,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof LF){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),hl=J(g,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&&!bJ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Qt?.()??zr;q(t,200,_ee,await WI({projectDir:T??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:fl}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),gl=J(g,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&&!bJ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!bJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=FJ(l,o)??`${o}.md`}let s=Qt?.()??zr;q(t,200,ne,await Zoe($I({projectDir:T??l,contentDir:l,baseConfig:s,liveSourceFor:fl,backlinkIndex:Ie??null,linksValidation:en?.(),admittedDocNames:Sr,docFilePathFor:e=>FJ(l,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),vl=J(hee,async(t,n,r)=>{try{let t=TJ(r.docName,n,`lint-fix`);if(t===null)return;let i=ir(t),a=_V(r,ut);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(oC(i)||cC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=FJ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}EJ(z(l,f),l);let p=Qt?.()??zr,{stored:m}=Ci(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Boe({projectDir:T??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Jn(d),n=Hn[t]??Wr(u??o);Ze?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{aE(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,rE(h))},h.origin),a.kind!==`anonymous`&&cN(i,o,c,u,void 0,a.kind===`agent`?Si({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{Ze?.touchMode(o,`idle`)}let t=await mr(i);if(t?.kind===`failure`){_r(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){vr(n,`lint-fix`);return}lr(i,`lint-fix`);try{b=await Gi(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,It,{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 LF){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof HC){UC(n,e,`lint-fix`);return}if(e instanceof JC){XC(n,e,`lint-fix`);return}if(e instanceof hE){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),xl=`link-preview`,Sl=new PU({cacheDir:an?null:z(T??l,`.ok`,`local`,`link-previews`)}),wl=null,Tl=()=>(wl??=Sl.init(),wl),El=on??TU;async function Dl(e){let t=await El(e);return t.ok?{ok:!0,metadata:await AU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:El})}:{ok:!1,reason:t.reason}}let Ol=()=>{try{return sn?.()===!0}catch{return!1}},kl={"/api/config":Yc,"/api/asset":Ra,"/api/asset-text":Ha,"/api/document":Hi,"/api/documents":Ui,"/api/backlinks":qi,"/api/backlink-counts":Yi,"/api/link-preview":J(zt,async(e,t,n)=>{try{if(!Ol()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,de,{ok:!1,reason:`disabled`},{handler:xl});return}await Tl();let e=!1,r=await Sl.load(n.url,()=>(e=!0,Dl(n.url)));Sl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,de,i,{handler:xl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xl,cause:e})}},{handler:xl,method:`POST`,preBodyGate:(e,t)=>{let n=LU({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:xl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:xl}),!1)}}),"/api/forward-links":Xi,"/api/link-graph":Zi,"/api/dead-links":ta,"/api/orphans":Qi,"/api/hubs":$i,"/api/tags":_s,"/api/pages":Ya,"/api/folder-config":Ts,"/api/template":Ps,"/api/template/import":Fs,"/api/templates":Os,"/api/skill":rc,"/api/skill-file":lc,"/api/skills":Xs,"/api/skills/management":$s,"/api/skill/install":uc,"/api/skill/uninstall":dc,"/api/skill/restore":pc,"/api/skill/update":mc,"/api/skill-targets":fc,"/api/search":Fc,"/api/semantic-status":al,"/api/lint/config":cl,"/api/lint/markdownlint-config":ll,"/api/lint/frontmatter-schema":ul,"/api/lint/frontmatter-schemas":dl,"/api/lint":pl,"/api/lint/audit":hl,"/api/lint/fix":vl,"/api/audit":gl,"/api/suggest-links":k,"/api/page-headings":Ka,"/api/create-page":Wa,"/api/create-folder":Ga,"/api/duplicate-path":E,"/api/rename-path":qa,"/api/delete-path":D,"/api/trash/cleanup":Ja,"/api/upload":Xa,"/api/agent-write":ji,"/api/agent-write-md":Ni,"/api/agent-write-batch":Fi,"/api/frontmatter-patch":Ii,"/api/agent-patch":na,"/api/agent-undo":ra,"/api/agent-activity":ia,"/api/agent-burst-diff":sa,"/api/save-version":ha,"/api/history":ya,"/api/rollback":Sa,"/api/metrics/reconciliation":Ca,"/api/metrics/parse-health":wa,"/api/metrics/agent-presence":ja,"/api/metrics/agent-effects":Ma,"/api/metrics/watcher-recent":Pa,"/api/__embed-detect":Fa,"/api/server-info":Ea,"/api/acp/catalog":ka,"/api/share/construct-url":zc,"/api/share/target-status":Vc,"/api/git/branch-info":Bc,"/api/git/checkout":Hc,"/api/share/publish/owners":Wc,"/api/share/publish/name-check":Gc,"/api/share/publish":Kc,"/api/principal":Aa,"/api/rescue":Ua,"/api/workspace":Ia,"/api/sync/status":ns,"/api/sync/trigger":is,"/api/sync/conflicts":os,"/api/sync/conflict-content":cs,"/api/sync/resolve-conflict":ss,"/api/local-op/clone":j,"/api/local-op/ok-init":so,"/api/local-op/auth/login":Do,"/api/local-op/auth/status":Lo,"/api/local-op/auth/pat":Bo,"/api/local-op/auth/gh-login":jo,"/api/local-op/auth/cancel":Po,"/api/local-op/auth/repos":Ho,"/api/local-op/auth/signout":Xo,"/api/local-op/auth/set-identity":ts,"/api/local-op/embeddings/set-key":el,"/api/local-op/embeddings/clear-key":tl,"/api/local-op/embeddings/test":il,"/api/installed-agents":gs,"/api/spawn-cursor":Rc,"/api/handoff":Lc,"/api/install-skill":hs,"/api/skill/install-state":Ic,"/api/seed/plan":us,"/api/seed/apply":ps,"/api/seed/packs":ms,"/api/client-logs":qc};ye&&(kl[`/api/test-reset`]=la,kl[`/api/test-flush-git`]=ca,kl[`/api/test-rescan-backlinks`]=pa,kl[`/api/test-rescan-files`]=ma);let jl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Ml=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};yN({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:kl[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?OC(e):void 0;if(c!==void 0&&(AC(e,c),typeof t.setHeader==`function`&&t.setHeader(EC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!Xk(r,n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${EC}, ${zn.protocol}, ${zn.runtime}, ${zn.kind}`),t.setHeader(`Access-Control-Expose-Headers`,EC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(jl.has(r)||Ml.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!zk(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(an&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!zk(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=yo.extract(So.active(),e.headers),u=Fo(),d=Date.now();await So.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:bo.SERVER,attributes:{[as]:o,[rs]:s,[bee]:r,[yee]:`http`,[vee]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=kl[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await ba(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await vs(e,t,n))}a||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ls,s),s>=500&&n.setStatus({code:vo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:vo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;Dq().record(e,{[as]:o,[rs]:s,[ls]:t.statusCode})}}))}}}function rY(e){let t=e?.code;return typeof t==`string`?t:void 0}function iY(e){let t;try{t=Rl(e.contentDir,{withFileTypes:!0})}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&gC(n.name,Na)&&e.basenameIndex.add(n.name)}async function aY(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await au(i,{withFileTypes:!0})}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Zk(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await ru(a)}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ou(a)}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Qk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await su(i)}catch(t){let n=rY(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()&&gC(a,xa)&&!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()&&gC(a,xa)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const oY=O({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),sY=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function cY(e){return sY.includes(e)}function lY(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function uY(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!cY(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 dY=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=lY(e,this.payload)}};function fY(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=oY.safeParse(t);return n.success?n.data:void 0}var pY=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const mY=F(`conflict-storage`);var hY=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(zA(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){mY.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){mY.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||Nl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Kl(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return mY.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-CAmPAeqb.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(!Qk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Zz(r,t),$o(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`]),mY.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await dS(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){mY.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}),mY.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(!Qk(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(Zz(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-CAmPAeqb.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);Zz(a,i),$o(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);$o(a,n,`utf-8`);break;case`delete`:B(a)&&zo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function gY(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 _Y(e,t){let n=zA(e);try{Nl(n,{recursive:!0}),Kl(L(n,pe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=os(e);Nl(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`};Kl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const vY=new Map;let yY=!1;function bY(e,t){try{let n=gY(e,t);for(let e of vY.keys())_Y(e,n)}catch{}}function xY(e){vY.set(e,(vY.get(e)??0)+1),yY||(yY=!0,process.on(`uncaughtExceptionMonitor`,bY));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=vY.get(e)??0;n<=1?vY.delete(e):vY.set(e,n-1)}}}function SY(e){let t=e.scheduler??m,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 CY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wY(e){if(!B(e))return{};let t;try{t=(0,kk.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(!CY(t))return{};let n=t.telemetry;if(!CY(n))return{};let r=n.localSink;return CY(r)?r:{}}function TY(e){return typeof e==`boolean`?e:void 0}function EY(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function DY(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function OY(e){if(CY(e))return EY(e.maxBytes)}function kY(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=wY(Ao(`project`,e.projectDir)),n=wY(Ao(`project-local`,e.projectDir));if((TY(n.enabled)??TY(t.enabled)??!0)===!1)return null;let r=OY(n.spans)??OY(t.spans)??52428800,i=OY(n.logs)??OY(t.logs)??26214400,a=DY(n.attributeDenylist)??DY(t.attributeDenylist)??Ra;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var AY;(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})(AY||={});var jY;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(jY||={});const MY=AY.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),NY=e=>{switch(typeof e){case`undefined`:return MY.undefined;case`string`:return MY.string;case`number`:return Number.isNaN(e)?MY.nan:MY.number;case`boolean`:return MY.boolean;case`function`:return MY.function;case`bigint`:return MY.bigint;case`symbol`:return MY.symbol;case`object`:return Array.isArray(e)?MY.array:e===null?MY.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?MY.promise:typeof Map<`u`&&e instanceof Map?MY.map:typeof Set<`u`&&e instanceof Set?MY.set:typeof Date<`u`&&e instanceof Date?MY.date:MY.object;default:return MY.unknown}},X=AY.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 PY=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,AY.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()}};PY.create=e=>new PY(e);const FY=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===MY.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,AY.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${AY.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${AY.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${AY.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:AY.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case X.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,AY.assertNever(e)}return{message:n}};let IY=FY;function LY(){return IY}const RY=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 zY(e,t){let n=LY(),r=RY({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===FY?void 0:FY].filter(e=>!!e)});e.common.issues.push(r)}var BY=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 VY;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 VY;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 VY=Object.freeze({status:`aborted`}),HY=e=>({status:`dirty`,value:e}),UY=e=>({status:`valid`,value:e}),WY=e=>e.status===`aborted`,GY=e=>e.status===`dirty`,KY=e=>e.status===`valid`,qY=e=>typeof Promise<`u`&&e instanceof Promise;var JY;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(JY||={});var YY=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 XY=(e,t)=>{if(KY(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 PY(e.common.issues);return this._error=t,this._error}}};function ZY(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 QY=class{get description(){return this._def.description}_getType(e){return NY(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:NY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new BY,ctx:{common:e.parent.common,data:e.data,parsedType:NY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qY(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:NY(e)};return XY(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:NY(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return KY(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=>KY(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:NY(e)},r=this._parse({data:e,path:n.path,parent:n});return XY(n,await(qY(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:X.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new eZ({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return tZ.create(this,this._def)}nullable(){return nZ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return FX.create(this)}promise(){return $X.create(this,this._def)}or(e){return RX.create([this,e],this._def)}and(e){return HX.create(this,e,this._def)}transform(e){return new eZ({...ZY(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new rZ({...ZY(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new oZ({typeName:Z.ZodBranded,type:this,...ZY(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new iZ({...ZY(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return sZ.create(this,e)}readonly(){return cZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const $Y=/^c[^\s-]{8,}$/i,eX=/^[0-9a-z]+$/,tX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nX=/^[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,rX=/^[a-z0-9_-]{21}$/i,iX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aX=/^[-+]?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)?)??$/,oX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let sX;const cX=/^(?:(?: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])$/,lX=/^(?:(?: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])$/,uX=/^(([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]))$/,dX=/^(([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])$/,fX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mX=`((\\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])))`,hX=RegExp(`^${mX}$`);function gX(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 _X(e){return RegExp(`^${gX(e)}$`)}function vX(e){let t=`${mX}T${gX(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function yX(e,t){return!!((t===`v4`||!t)&&cX.test(e)||(t===`v6`||!t)&&uX.test(e))}function bX(e,t){if(!iX.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 xX(e,t){return!!((t===`v4`||!t)&&lX.test(e)||(t===`v6`||!t)&&dX.test(e))}var SX=class e extends QY{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==MY.string){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.string,received:t.parsedType}),VY}let t=new BY,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?zY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&zY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)oX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)sX||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),sX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)nX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)rX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)$Y.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)eX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)tX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),zY(n,{validation:`url`,code:X.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`regex`,code:X.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?vX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?hX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?_X(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?aX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?yX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?bX(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?xX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?fX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?pX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):AY.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...JY.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...JY.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...JY.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...JY.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...JY.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...JY.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...JY.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...JY.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...JY.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...JY.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...JY.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...JY.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...JY.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...JY.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,...JY.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,...JY.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...JY.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...JY.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...JY.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...JY.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...JY.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...JY.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...JY.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...JY.errToObj(t)})}nonempty(e){return this.min(1,JY.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}};SX.create=e=>new SX({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...ZY(e)});function CX(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 wX=class e extends QY{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)!==MY.number){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.number,received:t.parsedType}),VY}let t,n=new BY;for(let r of this._def.checks)r.kind===`int`?AY.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),zY(t,{code:X.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?CX(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_finite,message:r.message}),n.dirty()):AY.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,JY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JY.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:JY.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:JY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:JY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:JY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:JY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JY.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:JY.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:JY.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:JY.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`&&AY.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)}};wX.create=e=>new wX({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...ZY(e)});var TX=class e extends QY{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)!==MY.bigint)return this._getInvalidInput(e);let t,n=new BY;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),zY(t,{code:X.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):AY.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.bigint,received:t.parsedType}),VY}gte(e,t){return this.setLimit(`min`,e,!0,JY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JY.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:JY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:JY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:JY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:JY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JY.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}};TX.create=e=>new TX({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...ZY(e)});var EX=class extends QY{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==MY.boolean){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.boolean,received:t.parsedType}),VY}return UY(e.data)}};EX.create=e=>new EX({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...ZY(e)});var DX=class e extends QY{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==MY.date){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.date,received:t.parsedType}),VY}if(Number.isNaN(e.data.getTime()))return zY(this._getOrReturnCtx(e),{code:X.invalid_date}),VY;let t=new BY,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):AY.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:JY.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:JY.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)}};DX.create=e=>new DX({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...ZY(e)});var OX=class extends QY{_parse(e){if(this._getType(e)!==MY.symbol){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.symbol,received:t.parsedType}),VY}return UY(e.data)}};OX.create=e=>new OX({typeName:Z.ZodSymbol,...ZY(e)});var kX=class extends QY{_parse(e){if(this._getType(e)!==MY.undefined){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.undefined,received:t.parsedType}),VY}return UY(e.data)}};kX.create=e=>new kX({typeName:Z.ZodUndefined,...ZY(e)});var AX=class extends QY{_parse(e){if(this._getType(e)!==MY.null){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.null,received:t.parsedType}),VY}return UY(e.data)}};AX.create=e=>new AX({typeName:Z.ZodNull,...ZY(e)});var jX=class extends QY{constructor(){super(...arguments),this._any=!0}_parse(e){return UY(e.data)}};jX.create=e=>new jX({typeName:Z.ZodAny,...ZY(e)});var MX=class extends QY{constructor(){super(...arguments),this._unknown=!0}_parse(e){return UY(e.data)}};MX.create=e=>new MX({typeName:Z.ZodUnknown,...ZY(e)});var NX=class extends QY{_parse(e){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.never,received:t.parsedType}),VY}};NX.create=e=>new NX({typeName:Z.ZodNever,...ZY(e)});var PX=class extends QY{_parse(e){if(this._getType(e)!==MY.undefined){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.void,received:t.parsedType}),VY}return UY(e.data)}};PX.create=e=>new PX({typeName:Z.ZodVoid,...ZY(e)});var FX=class e extends QY{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==MY.array)return zY(t,{code:X.invalid_type,expected:MY.array,received:t.parsedType}),VY;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(zY(t,{code:e?X.too_big:X.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(zY(t,{code:X.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(zY(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new YY(t,e,t.path,n)))).then(e=>BY.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new YY(t,e,t.path,n)));return BY.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:JY.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:JY.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:JY.toString(n)}})}nonempty(e){return this.min(1,e)}};FX.create=(e,t)=>new FX({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...ZY(t)});function IX(e){if(e instanceof LX){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=tZ.create(IX(r))}return new LX({...e._def,shape:()=>t})}else if(e instanceof FX)return new FX({...e._def,type:IX(e.element)});else if(e instanceof tZ)return tZ.create(IX(e.unwrap()));else if(e instanceof nZ)return nZ.create(IX(e.unwrap()));else if(e instanceof UX)return UX.create(e.items.map(e=>IX(e)));else return e}var LX=class e extends QY{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=AY.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==MY.object){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.object,received:t.parsedType}),VY}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof NX&&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 YY(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof NX){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&&(zY(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new YY(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=>BY.mergeObjectSync(t,e)):BY.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return JY.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:JY.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of AY.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 AY.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return IX(this)}partial(t){let n={};for(let e of AY.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 AY.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof tZ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return XX(AY.objectKeys(this.shape))}};LX.create=(e,t)=>new LX({shape:()=>e,unknownKeys:`strip`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)}),LX.strictCreate=(e,t)=>new LX({shape:()=>e,unknownKeys:`strict`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)}),LX.lazycreate=(e,t)=>new LX({shape:e,unknownKeys:`strip`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)});var RX=class extends QY{_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 PY(e.ctx.common.issues));return zY(t,{code:X.invalid_union,unionErrors:n}),VY}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 PY(e));return zY(t,{code:X.invalid_union,unionErrors:i}),VY}}get options(){return this._def.options}};RX.create=(e,t)=>new RX({options:e,typeName:Z.ZodUnion,...ZY(t)});const zX=e=>e instanceof JX?zX(e.schema):e instanceof eZ?zX(e.innerType()):e instanceof YX?[e.value]:e instanceof ZX?e.options:e instanceof QX?AY.objectValues(e.enum):e instanceof rZ?zX(e._def.innerType):e instanceof kX?[void 0]:e instanceof AX?[null]:e instanceof tZ?[void 0,...zX(e.unwrap())]:e instanceof nZ?[null,...zX(e.unwrap())]:e instanceof oZ||e instanceof cZ?zX(e.unwrap()):e instanceof iZ?zX(e._def.innerType):[];var BX=class e extends QY{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==MY.object)return zY(t,{code:X.invalid_type,expected:MY.object,received:t.parsedType}),VY;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}):(zY(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),VY)}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=zX(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...ZY(r)})}};function VX(e,t){let n=NY(e),r=NY(t);if(e===t)return{valid:!0,data:e};if(n===MY.object&&r===MY.object){let n=AY.objectKeys(t),r=AY.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=VX(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===MY.array&&r===MY.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=VX(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===MY.date&&r===MY.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var HX=class extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(WY(e)||WY(r))return VY;let i=VX(e.value,r.value);return i.valid?((GY(e)||GY(r))&&t.dirty(),{status:t.value,value:i.data}):(zY(n,{code:X.invalid_intersection_types}),VY)};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}))}};HX.create=(e,t,n)=>new HX({left:e,right:t,typeName:Z.ZodIntersection,...ZY(n)});var UX=class e extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==MY.array)return zY(n,{code:X.invalid_type,expected:MY.array,received:n.parsedType}),VY;if(n.data.length<this._def.items.length)return zY(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),VY;!this._def.rest&&n.data.length>this._def.items.length&&(zY(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new YY(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>BY.mergeArray(t,e)):BY.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};UX.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new UX({items:e,typeName:Z.ZodTuple,rest:null,...ZY(t)})};var WX=class e extends QY{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!==MY.object)return zY(n,{code:X.invalid_type,expected:MY.object,received:n.parsedType}),VY;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new YY(n,e,n.path,e)),value:a._parse(new YY(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?BY.mergeObjectAsync(t,r):BY.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof QY?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...ZY(r)}):new e({keyType:SX.create(),valueType:t,typeName:Z.ZodRecord,...ZY(n)})}},GX=class extends QY{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!==MY.map)return zY(n,{code:X.invalid_type,expected:MY.map,received:n.parsedType}),VY;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new YY(n,e,n.path,[a,`key`])),value:i._parse(new YY(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 VY;(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 VY;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};GX.create=(e,t,n)=>new GX({valueType:t,keyType:e,typeName:Z.ZodMap,...ZY(n)});var KX=class e extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==MY.set)return zY(n,{code:X.invalid_type,expected:MY.set,received:n.parsedType}),VY;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(zY(n,{code:X.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(zY(n,{code:X.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return VY;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 YY(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:JY.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:JY.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};KX.create=(e,t)=>new KX({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...ZY(t)});var qX=class e extends QY{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==MY.function)return zY(t,{code:X.invalid_type,expected:MY.function,received:t.parsedType}),VY;function n(e,n){return RY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LY(),FY].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return RY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LY(),FY].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof $X){let e=this;return UY(async function(...t){let o=new PY([]),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 UY(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new PY([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new PY([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:UX.create(t).rest(MX.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||UX.create([]).rest(MX.create()),returns:n||MX.create(),typeName:Z.ZodFunction,...ZY(r)})}},JX=class extends QY{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})}};JX.create=(e,t)=>new JX({getter:e,typeName:Z.ZodLazy,...ZY(t)});var YX=class extends QY{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return zY(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),VY}return{status:`valid`,value:e.data}}get value(){return this._def.value}};YX.create=(e,t)=>new YX({value:e,typeName:Z.ZodLiteral,...ZY(t)});function XX(e,t){return new ZX({values:e,typeName:Z.ZodEnum,...ZY(t)})}var ZX=class e extends QY{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return zY(t,{expected:AY.joinValues(n),received:t.parsedType,code:X.invalid_type}),VY}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return zY(t,{received:t.data,code:X.invalid_enum_value,options:n}),VY}return UY(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})}};ZX.create=XX;var QX=class extends QY{_parse(e){let t=AY.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==MY.string&&n.parsedType!==MY.number){let e=AY.objectValues(t);return zY(n,{expected:AY.joinValues(e),received:n.parsedType,code:X.invalid_type}),VY}if(this._cache||=new Set(AY.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=AY.objectValues(t);return zY(n,{received:n.data,code:X.invalid_enum_value,options:e}),VY}return UY(e.data)}get enum(){return this._def.values}};QX.create=(e,t)=>new QX({values:e,typeName:Z.ZodNativeEnum,...ZY(t)});var $X=class extends QY{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==MY.promise&&t.common.async===!1?(zY(t,{code:X.invalid_type,expected:MY.promise,received:t.parsedType}),VY):UY((t.parsedType===MY.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$X.create=(e,t)=>new $X({type:e,typeName:Z.ZodPromise,...ZY(t)});var eZ=class extends QY{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{zY(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 VY;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?VY:r.status===`dirty`||t.value===`dirty`?HY(r.value):r});{if(t.value===`aborted`)return VY;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?VY:r.status===`dirty`||t.value===`dirty`?HY(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`?VY:(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`?VY:(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(!KY(e))return VY;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=>KY(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):VY);AY.assertNever(r)}};eZ.create=(e,t,n)=>new eZ({schema:e,typeName:Z.ZodEffects,effect:t,...ZY(n)}),eZ.createWithPreprocess=(e,t,n)=>new eZ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...ZY(n)});var tZ=class extends QY{_parse(e){return this._getType(e)===MY.undefined?UY(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tZ.create=(e,t)=>new tZ({innerType:e,typeName:Z.ZodOptional,...ZY(t)});var nZ=class extends QY{_parse(e){return this._getType(e)===MY.null?UY(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nZ.create=(e,t)=>new nZ({innerType:e,typeName:Z.ZodNullable,...ZY(t)});var rZ=class extends QY{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===MY.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};rZ.create=(e,t)=>new rZ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...ZY(t)});var iZ=class extends QY{_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 qY(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new PY(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new PY(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};iZ.create=(e,t)=>new iZ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...ZY(t)});var aZ=class extends QY{_parse(e){if(this._getType(e)!==MY.nan){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.nan,received:t.parsedType}),VY}return{status:`valid`,value:e.data}}};aZ.create=e=>new aZ({typeName:Z.ZodNaN,...ZY(e)});var oZ=class extends QY{_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}},sZ=class e extends QY{_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`?VY:e.status===`dirty`?(t.dirty(),HY(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`?VY:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},cZ=class extends QY{_parse(e){let t=this._def.innerType._parse(e),n=e=>(KY(e)&&(e.value=Object.freeze(e.value)),e);return qY(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};cZ.create=(e,t)=>new cZ({innerType:e,typeName:Z.ZodReadonly,...ZY(t)}),LX.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),SX.create,wX.create,aZ.create,TX.create,EX.create,DX.create,OX.create,kX.create,AX.create,jX.create,MX.create,NX.create,PX.create,FX.create;const lZ=LX.create;LX.strictCreate,RX.create,BX.create,HX.create,UX.create,WX.create,GX.create,KX.create,qX.create,JX.create,YX.create,ZX.create,QX.create,$X.create,eZ.create,tZ.create,nZ.create,eZ.createWithPreprocess,sZ.create;const uZ=Pa(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ho.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Ba(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wa(e,t,n),e.parseAsync=async(t,n)=>Ea(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Fa(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)=>ba(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),dZ=Pa(`ZodMiniObject`,(e,t)=>{Ca.init(e,t),uZ.init(e,t),$a(e,`shape`,()=>t.shape)});function fZ(e,t){return new dZ({type:`object`,shape:e??{},...Ma(t)})}function pZ(e){return!!e._zod}function mZ(e){let t=Object.values(e);if(t.length===0)return fZ({});let n=t.every(pZ),r=t.every(e=>!pZ(e));if(n)return fZ(e);if(r)return lZ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function hZ(e,t){return pZ(e)?wa(e,t):e.safeParse(t)}async function gZ(e,t){return pZ(e)?await Fa(e,t):await e.safeParseAsync(t)}function _Z(e){if(!e)return;let t;if(t=pZ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function vZ(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 mZ(e)}}if(pZ(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 yZ(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 bZ(e){return e.description}function xZ(e){if(pZ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function SZ(e){if(pZ(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 CZ=`2025-11-25`,wZ=[CZ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],TZ=`io.modelcontextprotocol/related-task`,EZ=co(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),DZ=k([A(),P().int()]),OZ=A();no({ttl:P().optional(),pollInterval:P().optional()});const kZ=O({ttl:P().optional()}),AZ=O({taskId:A()}),jZ=no({progressToken:DZ.optional(),[TZ]:AZ.optional()}),MZ=O({_meta:jZ.optional()}),NZ=MZ.extend({task:kZ.optional()}),PZ=e=>NZ.safeParse(e).success,FZ=O({method:A(),params:MZ.loose().optional()}),IZ=O({_meta:jZ.optional()}),LZ=O({method:A(),params:IZ.loose().optional()}),RZ=no({_meta:jZ.optional()}),zZ=k([A(),P().int()]),BZ=O({jsonrpc:D(`2.0`),id:zZ,...FZ.shape}).strict(),VZ=e=>BZ.safeParse(e).success,HZ=O({jsonrpc:D(`2.0`),...LZ.shape}).strict(),UZ=e=>HZ.safeParse(e).success,WZ=O({jsonrpc:D(`2.0`),id:zZ,result:RZ}).strict(),GZ=e=>WZ.safeParse(e).success;var KZ;(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`})(KZ||={});const qZ=O({jsonrpc:D(`2.0`),id:zZ.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),JZ=e=>qZ.safeParse(e).success,YZ=k([BZ,HZ,WZ,qZ]);k([WZ,qZ]);const XZ=RZ.strict(),ZZ=IZ.extend({requestId:zZ.optional(),reason:A().optional()}),QZ=LZ.extend({method:D(`notifications/cancelled`),params:ZZ}),$Z=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:La([`light`,`dark`]).optional()})).optional()}),eQ=O({name:A(),title:A().optional()}),tQ=eQ.extend({...eQ.shape,...$Z.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),nQ=oo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ao(O({form:ao(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:EZ.optional()}),j(A(),E()).optional())),rQ=no({list:EZ.optional(),cancel:EZ.optional(),requests:no({sampling:no({createMessage:EZ.optional()}).optional(),elicitation:no({create:EZ.optional()}).optional()}).optional()}),iQ=no({list:EZ.optional(),cancel:EZ.optional(),requests:no({tools:no({call:EZ.optional()}).optional()}).optional()}),aQ=O({experimental:j(A(),EZ).optional(),sampling:O({context:EZ.optional(),tools:EZ.optional()}).optional(),elicitation:nQ.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:rQ.optional(),extensions:j(A(),EZ).optional()}),oQ=MZ.extend({protocolVersion:A(),capabilities:aQ,clientInfo:tQ}),sQ=FZ.extend({method:D(`initialize`),params:oQ}),cQ=e=>sQ.safeParse(e).success,lQ=O({experimental:j(A(),EZ).optional(),logging:EZ.optional(),completions:EZ.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:iQ.optional(),extensions:j(A(),EZ).optional()}),uQ=RZ.extend({protocolVersion:A(),capabilities:lQ,serverInfo:tQ,instructions:A().optional()}),dQ=LZ.extend({method:D(`notifications/initialized`),params:IZ.optional()}),fQ=e=>dQ.safeParse(e).success,pQ=FZ.extend({method:D(`ping`),params:MZ.optional()}),mQ=O({progress:P(),total:Ja(P()),message:Ja(A())}),hQ=O({...IZ.shape,...mQ.shape,progressToken:DZ}),gQ=LZ.extend({method:D(`notifications/progress`),params:hQ}),_Q=MZ.extend({cursor:OZ.optional()}),vQ=FZ.extend({params:_Q.optional()}),yQ=RZ.extend({nextCursor:OZ.optional()}),bQ=La([`working`,`input_required`,`completed`,`failed`,`cancelled`]),xQ=O({taskId:A(),status:bQ,ttl:k([P(),ya()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Ja(P()),statusMessage:Ja(A())}),SQ=RZ.extend({task:xQ}),CQ=IZ.merge(xQ),wQ=LZ.extend({method:D(`notifications/tasks/status`),params:CQ}),TQ=FZ.extend({method:D(`tasks/get`),params:MZ.extend({taskId:A()})}),EQ=RZ.merge(xQ),DQ=FZ.extend({method:D(`tasks/result`),params:MZ.extend({taskId:A()})});RZ.loose();const OQ=vQ.extend({method:D(`tasks/list`)}),kQ=yQ.extend({tasks:N(xQ)}),AQ=FZ.extend({method:D(`tasks/cancel`),params:MZ.extend({taskId:A()})}),jQ=RZ.merge(xQ),MQ=O({uri:A(),mimeType:Ja(A()),_meta:j(A(),E()).optional()}),NQ=MQ.extend({text:A()}),PQ=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),FQ=MQ.extend({blob:PQ}),IQ=La([`user`,`assistant`]),LQ=O({audience:N(IQ).optional(),priority:P().min(0).max(1).optional(),lastModified:go({offset:!0}).optional()}),RQ=O({...eQ.shape,...$Z.shape,uri:A(),description:Ja(A()),mimeType:Ja(A()),size:Ja(P()),annotations:LQ.optional(),_meta:Ja(no({}))}),zQ=O({...eQ.shape,...$Z.shape,uriTemplate:A(),description:Ja(A()),mimeType:Ja(A()),annotations:LQ.optional(),_meta:Ja(no({}))}),BQ=vQ.extend({method:D(`resources/list`)}),VQ=yQ.extend({resources:N(RQ)}),HQ=vQ.extend({method:D(`resources/templates/list`)}),UQ=yQ.extend({resourceTemplates:N(zQ)}),WQ=MZ.extend({uri:A()}),GQ=WQ,KQ=FZ.extend({method:D(`resources/read`),params:GQ}),qQ=RZ.extend({contents:N(k([NQ,FQ]))}),JQ=LZ.extend({method:D(`notifications/resources/list_changed`),params:IZ.optional()}),YQ=WQ,XQ=FZ.extend({method:D(`resources/subscribe`),params:YQ}),ZQ=WQ,QQ=FZ.extend({method:D(`resources/unsubscribe`),params:ZQ}),$Q=IZ.extend({uri:A()}),e$=LZ.extend({method:D(`notifications/resources/updated`),params:$Q}),t$=O({name:A(),description:Ja(A()),required:Ja(M())}),n$=O({...eQ.shape,...$Z.shape,description:Ja(A()),arguments:Ja(N(t$)),_meta:Ja(no({}))}),r$=vQ.extend({method:D(`prompts/list`)}),i$=yQ.extend({prompts:N(n$)}),a$=MZ.extend({name:A(),arguments:j(A(),A()).optional()}),o$=FZ.extend({method:D(`prompts/get`),params:a$}),s$=O({type:D(`text`),text:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),c$=O({type:D(`image`),data:PQ,mimeType:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),l$=O({type:D(`audio`),data:PQ,mimeType:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),u$=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),d$=O({type:D(`resource`),resource:k([NQ,FQ]),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),f$=k([s$,c$,l$,RQ.extend({type:D(`resource_link`)}),d$]),p$=O({role:IQ,content:f$}),m$=RZ.extend({description:A().optional(),messages:N(p$)}),h$=LZ.extend({method:D(`notifications/prompts/list_changed`),params:IZ.optional()}),g$=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),_$=O({taskSupport:La([`required`,`optional`,`forbidden`]).optional()}),v$=O({...eQ.shape,...$Z.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),EZ).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),EZ).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:g$.optional(),execution:_$.optional(),_meta:j(A(),E()).optional()}),y$=vQ.extend({method:D(`tools/list`)}),b$=yQ.extend({tools:N(v$)}),x$=RZ.extend({content:N(f$).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});x$.or(RZ.extend({toolResult:E()}));const S$=NZ.extend({name:A(),arguments:j(A(),E()).optional()}),C$=FZ.extend({method:D(`tools/call`),params:S$}),w$=LZ.extend({method:D(`notifications/tools/list_changed`),params:IZ.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const T$=La([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),E$=MZ.extend({level:T$}),D$=FZ.extend({method:D(`logging/setLevel`),params:E$}),O$=IZ.extend({level:T$,logger:A().optional(),data:E()}),k$=LZ.extend({method:D(`notifications/message`),params:O$}),A$=O({hints:N(O({name:A().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),j$=O({mode:La([`auto`,`required`,`none`]).optional()}),M$=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(f$).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),N$=Qa(`type`,[s$,c$,l$]),P$=Qa(`type`,[s$,c$,l$,u$,M$]),F$=O({role:IQ,content:k([P$,N(P$)]),_meta:j(A(),E()).optional()}),I$=NZ.extend({messages:N(F$),modelPreferences:A$.optional(),systemPrompt:A().optional(),includeContext:La([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:EZ.optional(),tools:N(v$).optional(),toolChoice:j$.optional()}),L$=FZ.extend({method:D(`sampling/createMessage`),params:I$}),R$=RZ.extend({model:A(),stopReason:Ja(La([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:IQ,content:N$}),z$=RZ.extend({model:A(),stopReason:Ja(La([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:IQ,content:k([P$,N(P$)])}),B$=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),V$=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:La([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),H$=O({type:La([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),U$=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),W$=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),G$=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([U$,W$]),k([O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({type:D(`string`),enum:N(A())}),default:N(A()).optional()}),O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({anyOf:N(O({const:A(),title:A()}))}),default:N(A()).optional()})])]),B$,V$,H$]),K$=k([NZ.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),G$),required:N(A()).optional()})}),NZ.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),q$=FZ.extend({method:D(`elicitation/create`),params:K$}),J$=IZ.extend({elicitationId:A()}),Y$=LZ.extend({method:D(`notifications/elicitation/complete`),params:J$}),X$=RZ.extend({action:La([`accept`,`decline`,`cancel`]),content:oo(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),Z$=O({type:D(`ref/resource`),uri:A()}),Q$=O({type:D(`ref/prompt`),name:A()}),$$=MZ.extend({ref:k([Q$,Z$]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),e1=FZ.extend({method:D(`completion/complete`),params:$$});function t1(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function n1(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const r1=RZ.extend({completion:no({values:N(A()).max(100),total:Ja(P().int()),hasMore:Ja(M())})}),i1=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),a1=FZ.extend({method:D(`roots/list`),params:MZ.optional()}),o1=RZ.extend({roots:N(i1)}),s1=LZ.extend({method:D(`notifications/roots/list_changed`),params:IZ.optional()});k([pQ,sQ,e1,D$,o$,r$,BQ,HQ,KQ,XQ,QQ,C$,y$,TQ,DQ,OQ,AQ]),k([QZ,gQ,dQ,s1,wQ]),k([XZ,R$,z$,X$,o1,EQ,kQ,SQ]),k([pQ,L$,q$,a1,TQ,DQ,OQ,AQ]),k([QZ,gQ,k$,e$,JQ,w$,h$,wQ,Y$]),k([XZ,uQ,r1,m$,i$,VQ,UQ,qQ,x$,b$,EQ,kQ,SQ]);var c1=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===KZ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new l1(e.elicitations,n)}return new e(t,n,r)}},l1=class extends c1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(KZ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function u1(e){return e===`completed`||e===`failed`||e===`cancelled`}const d1=Symbol(`Let zodToJsonSchema decide on which parser to use`),f1={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`},p1=e=>typeof e==`string`?{...f1,name:e}:{...f1,...e},m1=e=>{let t=p1(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 h1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function g1(e,t,n,r,i){e[t]=n,h1(e,t,r,i)}const _1=(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 v1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?_1(t,e.currentPath):t.join(`/`)}}function y1(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=l0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&g1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&g1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(g1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),g1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function b1(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?g1(n,`minimum`,r.value,r.message,t):g1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),g1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?g1(n,`maximum`,r.value,r.message,t):g1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),g1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:g1(n,`multipleOf`,r.value,r.message,t);break}return n}function x1(){return{type:`boolean`}}function S1(e,t){return l0(e.type._def,t)}const C1=(e,t)=>l0(e.innerType._def,t);function w1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>w1(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return T1(e,t)}}const T1=(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`:g1(n,`minimum`,r.value,r.message,t);break;case`max`:g1(n,`maximum`,r.value,r.message,t);break}return n};function E1(e,t){return{...l0(e.innerType._def,t),default:e.defaultValue()}}function D1(e,t){return t.effectStrategy===`input`?l0(e.schema._def,t):v1(t)}function O1(e){return{type:`string`,enum:Array.from(e.values)}}const k1=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function A1(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(k1(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 j1(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 M1;const N1={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:()=>(M1===void 0&&(M1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),M1),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 P1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:g1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:g1(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`:R1(n,`email`,r.message,t);break;case`format:idn-email`:R1(n,`idn-email`,r.message,t);break;case`pattern:zod`:z1(n,N1.email,r.message,t);break}break;case`url`:R1(n,`uri`,r.message,t);break;case`uuid`:R1(n,`uuid`,r.message,t);break;case`regex`:z1(n,r.regex,r.message,t);break;case`cuid`:z1(n,N1.cuid,r.message,t);break;case`cuid2`:z1(n,N1.cuid2,r.message,t);break;case`startsWith`:z1(n,RegExp(`^${F1(r.value,t)}`),r.message,t);break;case`endsWith`:z1(n,RegExp(`${F1(r.value,t)}$`),r.message,t);break;case`datetime`:R1(n,`date-time`,r.message,t);break;case`date`:R1(n,`date`,r.message,t);break;case`time`:R1(n,`time`,r.message,t);break;case`duration`:R1(n,`duration`,r.message,t);break;case`length`:g1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),g1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:z1(n,RegExp(F1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&R1(n,`ipv4`,r.message,t),r.version!==`v4`&&R1(n,`ipv6`,r.message,t);break;case`base64url`:z1(n,N1.base64url,r.message,t);break;case`jwt`:z1(n,N1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&z1(n,N1.ipv4Cidr,r.message,t),r.version!==`v4`&&z1(n,N1.ipv6Cidr,r.message,t);break;case`emoji`:z1(n,N1.emoji(),r.message,t);break;case`ulid`:z1(n,N1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:R1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:g1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:z1(n,N1.base64,r.message,t);break}break;case`nanoid`:z1(n,N1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function F1(e,t){return t.patternStrategy===`escape`?L1(e):e}const I1=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function L1(e){let t=``;for(let n=0;n<e.length;n++)I1.has(e[n])||(t+=`\\`),t+=e[n];return t}function R1(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}}})):g1(e,`format`,t,n,r)}function z1(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:B1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):g1(e,`pattern`,B1(t,r),n,r)}function B1(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
1228
+ `);l=n.pop()??``;for(let e of n){if(!e.trim())continue;let n=null;try{n=JSON.parse(e)}catch{}if(n&&n.type===`error`){i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess reported an error.`,{detail:typeof n.message==`string`?n.message:void 0});continue}if(!t.writableEnded&&!t.destroyed)try{t.write(`${e}\n`)}catch{}}}),u.stderr.on(`data`,e=>{Y.debug({msg:e.toString(`utf-8`).trim()},`[local-op/auth/repos] stderr`)}),u.on(`close`,e=>{clearTimeout(d),c||(c=!0,e!==0&&!t.writableEnded&&i(500,`urn:ok:error:auth-failed`,`Auth repos subprocess exited with code ${e}.`),t.end(),un.release(uo))}),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()),un.release(uo))}),t.on(`close`,()=>{c||(c=!0,clearTimeout(d),u.kill(`SIGTERM`),un.release(uo))})}let Yo=`local-op-auth-signout`,Xo=J(Ji,async(e,t,n)=>{let r=n.host??xo();if(!un.tryAcquire(fo)){G(t,429,`urn:ok:error:concurrent-operation`,`An auth signout operation is already in progress.`,{handler:Yo,extraHeaders:{"Retry-After":`5`}});return}try{let[e,...n]=it,i=[...n,`auth`,`signout`,`--host`,r];await new Promise((t,n)=>{let r=ml(e,i,OP({...no,env:{...process.env}})),a=setTimeout(()=>{r.kill(`SIGTERM`)},3e4);r.on(`close`,()=>{clearTimeout(a),t()}),r.on(`error`,e=>{clearTimeout(a),n(e)})}),q(t,200,Yr,{},{handler:Yo})}catch(e){G(t,500,`urn:ok:error:auth-failed`,`Auth signout failed.`,{handler:Yo,cause:e})}finally{un.release(fo)}},{handler:Yo,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Yo})}),Qo=`/api/local-op/auth/set-identity`,es=`local-op-auth-set-identity`,ts=J(xi,async(e,t,n)=>{let r=n.name.trim(),i=n.email.trim();if(!T){G(t,503,`urn:ok:error:no-project-dir`,`No project directory configured.`,{handler:es});return}if(!un.tryAcquire(Qo)){G(t,429,`urn:ok:error:concurrent-operation`,`A set-identity operation is already in progress.`,{handler:es,extraHeaders:{"Retry-After":`5`}});return}try{TH(T,r,i),$e?.()?.refreshIdentity().catch(()=>{}),q(t,200,Yr,{},{handler:es})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Set-identity failed.`,{handler:es,cause:e})}finally{un.release(Qo)}},{handler:es,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:es})});async function ns(e,t){if(r(e,t,{handler:`sync-status`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-status`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();if(!e){q(t,200,Br,{state:`dormant`,lastSyncUtc:null,lastFetchUtc:null,lastPushedSha:null,ahead:0,behind:0,consecutiveFailures:0,conflictCount:0,hasRemote:!1,syncEnabled:!1,identityUnresolved:!1,remote:null},{handler:`sync-status`});return}await e.refreshRemote(),q(t,200,Br,e.getStatus(),{handler:`sync-status`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-status`,cause:e})}}}let is=J(d,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`});return}let i=n.op??`sync`;q(t,202,Fr,{op:i},{handler:`sync-trigger`}),r.trigger(i)},{handler:`sync-trigger`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-trigger`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-trigger`}),!1):!1});async function os(e,t){if(r(e,t,{handler:`sync-conflicts`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflicts`,extraHeaders:{Allow:`GET`}});return}try{let e=$e?.();q(t,200,le,{conflicts:e?e.getConflicts():[]},{handler:`sync-conflicts`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`sync-conflicts`,cause:e})}}}let ss=J(re,async(e,t,n)=>{let r=$e?.();if(!r){G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`});return}let{file:i,strategy:a,content:o}=n;try{await r.resolveConflict(i,a,o),q(t,200,dt,{},{handler:`sync-resolve-conflict`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve conflict.`,{handler:`sync-resolve-conflict`,cause:e,detail:e instanceof Error?e.message:void 0})}},{handler:`sync-resolve-conflict`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`sync-resolve-conflict`})?$e?.()?!0:(G(t,503,`urn:ok:error:sync-not-active`,`Sync engine not active.`,{handler:`sync-resolve-conflict`}),!1):!1});async function cs(e,t){if(!r(e,t,{handler:`sync-conflict-content`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`sync-conflict-content`,extraHeaders:{Allow:`GET`}});return}if(!T){G(t,503,`urn:ok:error:project-repo-not-configured`,`Project repo not configured.`,{handler:`sync-conflict-content`});return}let n=new URL(e.url??`/`,`http://${e.headers.host??`localhost`}`),i=n.searchParams.get(`file`);if(!i){G(t,400,`urn:ok:error:invalid-request`,`Missing required query param: file.`,{handler:`sync-conflict-content`});return}if(i.includes(`..`)||i.startsWith(`/`)){G(t,400,`urn:ok:error:invalid-request`,`Invalid file path.`,{handler:`sync-conflict-content`});return}let o=_C(i),s=a.documents.get(o)?.getMap(`lifecycle`).get(`status`)===`conflict`,c=$e?.(),l=c?c.getConflicts().some(e=>e.file===i):!1;if(!s&&!l){G(t,404,`urn:ok:error:no-conflict-tracked`,`No conflict is tracked for this path.`,{handler:`sync-conflict-content`,extensions:{file:i}});return}let u=n.searchParams.get(`source`),d=ds({baseDir:T,timeout:{block:15e3}}),f=c?.getConflicts().find(e=>e.file===i&&e.variant===`working-tree`);if(f){try{let e=async e=>{if(!e)return``;try{return await d.raw([`cat-file`,`blob`,e])}catch(e){throw console.warn(JSON.stringify({event:`conflict-content-readblob-failed`,file:i,detail:e instanceof Error?e.message:String(e),handler:`sync-conflict-content`})),e}},n=await e(f.theirsSha),r=await e(f.baseSha),o=_C(i),s=a.documents.get(o),c=``,l=!1,u=null;if(s){let e=s.getMap(`lifecycle`).get(`status`);u=typeof e==`string`&&e.length>0?e:null;let t=Nt?Nt(o):null;t!==null&&(c=t,l=!0)}else{Zz(L(T,i),T);try{c=V(L(T,i),`utf-8`),l=!0}catch{l=!1}}let p=l?n.length===0?`modify-delete`:`both-modified`:`delete-modify`;q(t,200,Lt,{file:i,base:r,ours:c,theirs:n,kind:p,lifecycleStatus:u},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}return}async function p(e){try{return{present:!0,content:await d.raw([`show`,`:${e}:${i}`])}}catch(t){let n=t instanceof Error?t.message:String(t);if(!/pathspec|did not match|exists on disk, but not in|is in the index, but not at stage/i.test(n))throw console.warn(JSON.stringify({event:`showstage-unexpected-error`,stage:e,file:i,detail:n,handler:`sync-conflict-content`})),t;return{present:!1}}}try{let[e,n,r]=await Promise.all([p(1),p(2),p(3)]),o=e.present?e.content:``,s=r.present?r.content:``,c=n.present&&r.present?`both-modified`:!n.present&&r.present?`delete-modify`:n.present&&!r.present?`modify-delete`:`both-modified`,l=n.present?n.content:``,d=null;if(u===`ytext`){let e=_C(i),t=a.documents.get(e);if(t){let n=t.getMap(`lifecycle`).get(`status`);if(d=typeof n==`string`&&n.length>0?n:null,c!==`delete-modify`){let t=Nt?Nt(e):null;t!==null&&!Jq(t)?l=t:t!==null&&console.warn(JSON.stringify({event:`ytext-conflict-marker-detected`,"doc.name":e,handler:`sync-conflict-content`}))}}else Y.warn({docName:e},`[conflict-content] doc ${e} not loaded; lifecycleStatus unavailable`)}q(t,200,Lt,{file:i,base:o,ours:l,theirs:s,kind:c,lifecycleStatus:d},{handler:`sync-conflict-content`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read conflict content.`,{handler:`sync-conflict-content`,cause:e})}}async function us(e,t){if(!r(e,t,{handler:`seed-plan`}))return;if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-plan`,extraHeaders:{Allow:`GET`}});return}let n=new URL(e.url??`/`,`http://localhost`),i=n.searchParams.get(`rootDir`)??void 0,a=n.searchParams.get(`packId`),o=aK(a);if(a!==null&&a!==``&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-plan`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,gee,{plan:await xK({projectDir:l,rootDir:i,packId:o})},{handler:`seed-plan`})}catch(e){if(e instanceof qG){G(t,422,`urn:ok:error:seed-prerequisite-missing`,`Seed prerequisite missing.`,{handler:`seed-plan`,cause:e});return}if(e instanceof JG){G(t,400,`urn:ok:error:seed-invalid-root`,`Invalid seed root directory.`,{handler:`seed-plan`,detail:`The provided root directory is not within the workspace content directory.`,cause:e});return}G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`seed-plan`,cause:e})}}let ps=J(aa,async(e,t,n)=>{let r=n.plan;if(!r||typeof r!=`object`){G(t,400,`urn:ok:error:invalid-request`,`Invalid plan payload.`,{handler:`seed-apply`});return}let i=r,a=n.packId,o=aK(a);if(typeof a==`string`&&a.length>0&&o===void 0){G(t,400,`urn:ok:error:invalid-request`,`Unknown packId.`,{handler:`seed-apply`,detail:`Pack id "${a}" is not registered.`});return}try{q(t,200,nee,{result:await gK(i,{projectDir:l,packId:o})},{handler:`seed-apply`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to apply seed plan.`,{handler:`seed-apply`,cause:e})}},{handler:`seed-apply`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`seed-apply`})});async function ms(e,t){if(r(e,t,{handler:`seed-packs`})){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`seed-packs`,extraHeaders:{Allow:`GET`}});return}q(t,200,x,{packs:sK()},{handler:`seed-packs`})}}let hs=J(da,async(e,t,n)=>{if(n.out!==void 0&&!GU(n.out)){G(t,400,`urn:ok:error:invalid-request`,`Output path must be within home directory.`,{handler:`install-skill`});return}try{q(t,200,Rn,await ER({...n.noOpen===void 0?{}:{noOpen:n.noOpen},...n.out===void 0?{}:{out:n.out}}),{handler:`install-skill`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`install-skill`,cause:e})}},{handler:`install-skill`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`install-skill`})});async function gs(e,t){if(r(e,t,{handler:`installed-agents`}))try{await IP(e,t,In.probeAll)}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[installed-agents] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`installed-agents`,cause:n}))}}let _s=J(g,async(e,t)=>{if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-list`});return}try{q(t,200,Or,{tags:Le.getAllTags()},{handler:`tags-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tags.`,{handler:`tags-list`,cause:e})}},{handler:`tags-list`,method:`GET`,skipBodyParse:!0});async function vs(e,t,n){if(e.method!==`GET`){G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`tags-for-name`,extraHeaders:{Allow:`GET`}});return}if(!Le){G(t,503,`urn:ok:error:tag-index-not-configured`,`Tag index not configured.`,{handler:`tags-for-name`});return}let r;try{r=decodeURIComponent(n)}catch{G(t,400,`urn:ok:error:invalid-request`,`Invalid tag name encoding.`,{handler:`tags-for-name`});return}if(!r){G(t,400,`urn:ok:error:invalid-request`,`Missing tag name.`,{handler:`tags-for-name`});return}try{let e=Le.getDocsForTagWithMatches(r).map(({docName:e,matchingTags:t})=>({docName:e,title:Wn(e),matchingTags:t,snippet:null}));q(t,200,fee,{name:r,docs:e},{handler:`tags-for-name`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read tag membership.`,{handler:`tags-for-name`,cause:e})}}function ys(e,t,n=`path`,r=`folder-config`){let i=e.replace(/^\.\//,``).replace(/^\/+/,``).replace(/\/+$/,``);if(i.split(`/`).some(e=>e===`..`)||e.startsWith(`/`))return G(t,400,`urn:ok:error:invalid-request`,`Invalid ${n}: must be project-root-relative.`,{handler:r}),null;let a=z(l),o=i===``?a:z(a,i);return o!==a&&!o.startsWith(`${a}${Cl}`)?(G(t,400,`urn:ok:error:invalid-request`,`Path escapes content directory.`,{handler:r}),null):{folderRel:i,resolvedContentDir:a}}let bs=/^[A-Za-z0-9_-]+$/;function xs(e,t,n=`template`){return!e||!bs.test(e)?(G(t,400,`urn:ok:error:invalid-request`,"Invalid name: must be letters / digits / `_` / `-` only (no `.md` extension).",{handler:n}),!1):!0}function Ss(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}${Cl}`))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 Cs(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 Ts=DH({GET:J(g,async(e,t)=>{try{let n=ys(new URL(e.url??``,`http://localhost`).searchParams.get(`path`)??``,t,`path`,`folder-config-get`);if(!n)return;let r=await mM(n.folderRel,{projectDir:n.resolvedContentDir}),i=z(z(n.resolvedContentDir,n.folderRel,`.ok`),`frontmatter.yml`),a=null;if(B(i))try{let e=(0,kk.parse)(await iu(i,`utf-8`));a=e&&typeof e==`object`&&!Array.isArray(e)?e:{}}catch(e){let t=e instanceof Error?e.message:String(e);Y.warn({path:i,reason:t},`[folder-config:get] malformed YAML in ${i}: ${t}`),a=null}q(t,200,Bt,{folder:r,frontmatter_local:a},{handler:`folder-config-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read folder config.`,{handler:`folder-config-get`,cause:e})}},{handler:`folder-config-get`,method:`GET`,skipBodyParse:!0}),PUT:J(fe,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Folder configuration is not available in single-file mode.`,{handler:`folder-config-put`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`folder-config-put`});return}let r=ys(n.path,t,`path`,`folder-config-put`);if(!r)return;let i=[];if(n.frontmatter!==void 0){let a=yM({anchorDir:r.resolvedContentDir,folderRel:r.folderRel,patch:n.frontmatter});if(!a.ok){let e=a.error.code===`WRITE_ERROR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to write folder config.`:a.error.message,{handler:`folder-config-put`,detail:a.error.code,cause:Error(a.error.message)});return}i.push({path:a.path,action:a.action}),a.action!==`noop`&&(Oi(e,Di(`folder-frontmatter`,r.folderRel),`folder-frontmatter-${a.action===`deleted`?`delete`:`edit`}: ${a.path}`),await ki(`folder-config-put`))}q(t,200,oe,{applied:i},{handler:`folder-config-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write folder config.`,{handler:`folder-config-put`,cause:e})}},{handler:`folder-config-put`,method:`PUT`})},{handler:`folder-config`});function Es(e,t,n,r){if(!t)return!1;let i=e===``?`.ok/templates/${t}`:`${e.replace(/\/$/,``)}/.ok/templates/${t}`,o=a.documents.get(i);return o&&RC(o)?(UC(r,new HC({file:`${i}.md`}),n),!0):!1}function Ds(e,t,n){let r=a.documents.get(e);return r&&RC(r)?(UC(n,new HC({file:`${e}.md`}),t),!0):!1}let Os=J(g,EH(async(e,t)=>{let n=Kj(z(l));q(t,200,yi,{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}),ks=e=>{let{body:t}=ea(e);return{frontmatter:rt(e)??{},body:t}},js=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!xs(r,t,`template-get`))return;let i=ys(n.searchParams.get(`folder`)??``,t,`folder`,`template-get`);if(!i)return;let{folderRel:a,resolvedContentDir:o}=i,s=Ss(o,a,r);if(!s){G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-get`,detail:`Template "${r}" not found for folder "${a||`.`}". Walked leaf → root.`});return}let{abs:c,folder:l,scope:u}=s,d=Sn(await iu(c,`utf-8`)),f=d.identity,p=d.starterContent;q(t,200,pi,{template:{name:r,folder:l,scope:u,path:R(o,c).split(/[\\/]/).filter(Boolean).join(`/`),frontmatter:f,body:p}},{handler:`template-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read template.`,{handler:`template-get`,cause:e})}},{handler:`template-get`,method:`GET`,skipBodyParse:!0}),Ms=J(Xn,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-put`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-put`});return}let r=n.name;if(!xs(r,t,`template-put`))return;let i=ys(n.folder,t,`folder`,`template-put`);if(!i||Es(i.folderRel,r,`template-put`,t))return;let a=YM({name:r,body:typeof n.body==`string`?n.body:``,frontmatter:Cs(n.frontmatter)});if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-put`,detail:a.error.code,cause:Error(a.error.message)});return}let o=z(i.resolvedContentDir,i.folderRel,`.ok`,`templates`,`${r}.md`),c=!B(o),l=R(i.resolvedContentDir,o).split(/[\\/]/).filter(Boolean).join(`/`),u=Ws(i.folderRel,r),{agentId:d,agentName:f,colorSeed:p,clientName:m}=bi(n),h=await s.getSession(u,d,{displayName:f,colorSeed:p,clientName:m});h.dc.document.transact(()=>{nS(h.dc.document,a.content,`agent`)},h.origin);let g=await mr(u);if(g?.kind===`failure`){_r(t,g.failure,`template-put`);return}if(g?.kind===`divergence`){vr(t,`template-put`);return}Oi(e,Di(`template`,i.folderRel,r),`${c?`template-create`:`template-edit`}: ${l}`),await ki(`template-put`),q(t,200,cr,{path:l,created:c,warnings:a.warnings},{handler:`template-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write template.`,{handler:`template-put`,cause:e})}},{handler:`template-put`,method:`PUT`}),Ns=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!xs(r,t,`template-delete`))return;let i=ys(n.searchParams.get(`folder`)??``,t,`folder`,`template-delete`);if(!i)return;let a=n.searchParams,o=_V({agentId:a.get(`agentId`)??void 0,agentName:a.get(`agentName`)??void 0,colorSeed:a.get(`colorSeed`)??void 0,clientName:a.get(`clientName`)??void 0,clientVersion:a.get(`clientVersion`)??void 0,label:a.get(`label`)??void 0,summary:a.get(`summary`)??void 0},ut);if(o.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-delete`});return}if(Es(i.folderRel,r,`template-delete`,t))return;await Rr([Ws(i.folderRel,r)],`deleted-upstream`);let s=ZM({projectDir:i.resolvedContentDir,folder:i.folderRel,name:r});if(!s.ok){let e=s.error.code===`WRITE_ERROR`||s.error.code===`UNLINK_FAILED`||s.error.code===`BAD_PROJECT_DIR`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete template.`:`Invalid template request.`,{handler:`template-delete`,detail:s.error.code,cause:Error(s.error.message)});return}s.existed&&(Oi(o,Di(`template`,i.folderRel,r),`template-delete: ${s.path}`),await ki(`template-delete`)),q(t,200,Mn,{existed:s.existed,path:s.path},{handler:`template-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete template.`,{handler:`template-delete`,cause:e})}},{handler:`template-delete`,method:`DELETE`,skipBodyParse:!0}),Ps=DH({GET:js,PUT:Ms,POST:J(qr,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-move`});return}if(!xs(n.fromName,t,`template-move`)||!xs(n.toName,t,`template-move`))return;let r=ys(n.fromFolder,t,`folder`,`template-move`);if(!r)return;let i=ys(n.toFolder,t,`folder`,`template-move`);if(!i||Es(r.folderRel,n.fromName,`template-move`,t))return;await Rr([Ws(r.folderRel,n.fromName)],`renamed`);let a=await $M({projectDir:r.resolvedContentDir,fromFolder:r.folderRel,fromName:n.fromName,toFolder:i.folderRel,toName:n.toName,relocate:async(e,t)=>{let n=await ZJ(T,e,t);return n||XJ(e,t),n}});if(!a.ok){if(a.error.code===`TEMPLATE_NOT_FOUND`){let e=Ss(r.resolvedContentDir,r.folderRel,n.fromName);if(e?.scope===`inherited`){G(t,400,`urn:ok:error:invalid-request`,`Template "${n.fromName}" is inherited from "${e.folder||`(root)`}", not local to "${r.folderRel||`(root)`}". Move it from the folder that owns it, or create a local copy here first (then move that).`,{handler:`template-move`,detail:`TEMPLATE_INHERITED`});return}G(t,404,`urn:ok:error:template-not-found`,`Template not found.`,{handler:`template-move`,detail:a.error.message});return}if(a.error.code===`TEMPLATE_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,a.error.message,{handler:`template-move`,detail:a.error.code});return}let e=a.error.code===`WRITE_ERROR`||a.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move template.`:`Invalid template move request.`,{handler:`template-move`,detail:a.error.code,cause:Error(a.error.message)});return}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=dr(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=XM({projectDir:i.resolvedContentDir,folder:i.folderRel,name:n.toName,body:e,frontmatter:Cs(n.frontmatter)});t.ok||(o=t.error)}}if(Oi(e,Di(`template`,i.folderRel,n.toName),`template-rename: ${a.fromPath} -> ${a.toPath}`,[{from:a.fromPath,to:a.toPath}]),await ki(`template-move`),Ve?.(`files`),o){let e=o.code===`WRITE_ERROR`||o.code===`READ_FAILED`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Template moved to "${a.toPath}", but updating its content failed.`,{handler:`template-move`,detail:o.code,cause:Error(o.message)});return}q(t,200,Ki,{from:a.fromPath,to:a.toPath,committed:a.committed},{handler:`template-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move template.`,{handler:`template-move`,cause:e})}},{handler:`template-move`,method:`POST`}),DELETE:Ns},{handler:`template`}),Fs=J(Mi,async(e,t,n)=>{try{if(an){G(t,403,`urn:ok:error:single-file-mode`,`Templates are not available in single-file mode.`,{handler:`template-import`});return}let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`template-import`});return}let r=n.sourcePath;if(!eY(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid sourcePath.`,{handler:`template-import`});return}let i=ir(r);if(oC(i)||cC(i)){G(t,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`template-import`});return}let o=DJ(l,`file`,i);if(!B(o)){G(t,404,`urn:ok:error:doc-not-found`,`Source document not found: ${i}.`,{handler:`template-import`});return}let c=a.documents.get(i);if(n.deleteSource){let e=$e?.(),n=new Set(e?e.getConflicts().map(e=>e.file):[]),i=c!==void 0&&RC(c),a=n.has(r);if(i||a){UC(t,new HC({file:r}),`template-import`);return}}let u=``;if(c)u=c.getText(`source`).toString();else{let e=await a.openDirectConnection(i);try{let n=e.document;if(!n){G(t,500,`urn:ok:error:doc-not-available`,`Source document is not available.`,{handler:`template-import`});return}u=n.getText(`source`).toString()}finally{await e.disconnect()}}let d=n.name;if(!d){let{basename:e}=OJ(r);d=e.replace(/\.(md|mdx)$/i,``).replace(/[^A-Za-z0-9_-]/g,`-`).toLowerCase(),d=d.replace(/^[-_]+|[-_]+$/g,``),d||=`imported-template`}if(!xs(d,t,`template-import`))return;let f=ys(n.targetFolder,t,`folder`,`template-import`);if(!f||Es(f.folderRel,d,`template-import`,t))return;let{frontmatter:p,body:m}=ea(u),h=Ft(p),g={};try{h.trim()&&(g=(0,kk.parse)(h))}catch{}let _=n.title||g?.title||cL(u,d),v=g?.description||``,y=Array.isArray(g?.tags)?g.tags:[],b={...g};delete b.template,delete b.title;let x=``;Object.keys(b).length>0&&(x=`${(0,kk.stringify)(b).trim()}\n`),x=x?`---\n${x}---\n${m}`:m;let S=YM({name:d,body:x,frontmatter:{title:_,description:v,tags:y}});if(!S.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid template request.`,{handler:`template-import`,detail:S.error.code,cause:Error(S.error.message)});return}let C=z(f.resolvedContentDir,f.folderRel,`.ok`,`templates`,`${d}.md`),ee=!B(C),te=R(f.resolvedContentDir,C).split(/[\\/]/).filter(Boolean).join(`/`),ne=Ws(f.folderRel,d),{agentId:re,agentName:ie,colorSeed:ae,clientName:oe}=bi(n),se=await s.getSession(ne,re,{displayName:ie,colorSeed:ae,clientName:oe});se.dc.document.transact(()=>{nS(se.dc.document,S.content,`agent`)},se.origin);let ce=await mr(ne);if(ce?.kind===`failure`){_r(t,ce.failure,`template-import`);return}if(ce?.kind===`divergence`){vr(t,`template-import`);return}Oi(e,Di(`template`,f.folderRel,d),`template-import: ${te}`),n.deleteSource&&(await Rr([i],`deleted-upstream`),At&&At.setDeleted(i),zo(o),w?.({kind:`delete`,path:o,docName:i})),await ki(`template-import`),Ve?.(`files`),q(t,200,Gn,{path:te,created:ee,warnings:S.warnings},{handler:`template-import`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to import template.`,{handler:`template-import`,cause:e})}},{handler:`template-import`,method:`POST`});function Is(e,t,n){return!e||e.length>64||!mt.test(e)?(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill name: lowercase letters, digits, and hyphens only (≤64 chars; no slashes, dots, spaces, or uppercase).`,{handler:n}),!1):!0}function Ls(e,t,n){let r=uee.safeParse(e??`project`);return r.success?r.data:(G(t,400,`urn:ok:error:invalid-request`,`Invalid skill scope (expected "project" or "global").`,{handler:n}),null)}let Rs=ft??Xl();function zs(e){return z(e===`global`?Rs:l,`.ok`,`skills`)}let Bs=FL.project;function Vs(){if(!T)return null;let e=[],t=null;for(let n of He){let r=$t[n];if(!r)continue;let i=z(T,...r.split(`/`),Bs);B(z(i,`SKILL.md`))&&(e.push(n),t===null&&(t=i))}if(t===null)return null;let n=z(t,`SKILL.md`);return{dir:t,skillMd:n,hosts:e,relPath:R(T,n).split(/[\\/]/).filter(Boolean).join(`/`)}}function Hs(){let e=Vs();if(!e)return null;let t;try{let{frontmatter:n}=ks(V(e.skillMd,`utf-8`));typeof n.description==`string`&&(t=n.description)}catch{}return{name:Bs,...t===void 0?{}:{description:t},scope:`project`,path:e.relPath,absolutePath:e.skillMd,installed:e.hosts.length>0,hosts:e.hosts,managed:!0}}function Us(e,t,n){return LL(e)?(G(t,400,`urn:ok:error:reserved-doc-name`,`"${e}" is a built-in skill managed by OpenKnowledge and can't be edited, renamed, or deleted.`,{handler:n}),!0):!1}function Ws(e,t){return`${Nn}${[...e?e.split(`/`).filter(Boolean).map(encodeURIComponent):[],encodeURIComponent(t)].join(`/`)}`}function Gs(e){return e===`navigation`||e===`relevance`?e:void 0}function Ks(e,t){return R(t===`global`?Rs:l,e).split(/[\\/]/).filter(Boolean).join(`/`)}function qs(e){return e===`global`?Rs:T}async function Js(e,t){let n=await _F(e,t);return hz(t,e,He),n!==null}function Ys(e,t){let n=[];if(!B(e))return{skills:n,truncated:!1};let r;try{r=Rl(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()||!mt.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,s;try{let{frontmatter:e}=ks(V(r,`utf-8`));typeof e.description==`string`&&(o=e.description),typeof e.version==`string`&&e.version.trim()!==``&&(s=e.version)}catch{}n.push({name:a.name,...o===void 0?{}:{description:o},scope:t,path:Ks(r,t),absolutePath:r,...s===void 0?{}:{installedVersion:s}})}return{skills:n,truncated:i}}let Xs=J(g,EH(async(e,t)=>{let n=Ys(zs(`project`),`project`),r=Ys(zs(`global`),`global`),i=T?mF(T).skills:{},a=mF(Rs).skills,o=(e,t)=>e.skills.map(e=>{let n=t[e.name]?.hosts??[],r=Dz(e.name,e.installedVersion);return{...e,installed:n.length>0,hosts:n,...r}}),s=n.skills.some(e=>e.name===Bs)?null:Hs();q(t,200,zi,{skills:[...o(n,i),...o(r,a),...s?[s]:[]],truncated:n.truncated||r.truncated},{handler:`skills-list`})},{handler:`skills-list`,title:`Failed to list skills.`}),{handler:`skills-list`,method:`GET`,skipBodyParse:!0}),Zs=O({managed:M().nullable(),importable:P().int().nonnegative()}),Qs=()=>({managed:T?AR(T)?.manageEditorSkills??null:null,importable:T?Hz({projectDir:T,skillsRoot:zs(`project`)}):0}),$s=DH({GET:J(g,async(e,t)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-get`,detail:`NO_PROJECT_ROOT`});return}q(t,200,Zs,Qs(),{handler:`skills-management-get`})},{handler:`skills-management-get`,method:`GET`,skipBodyParse:!0}),PUT:J(O({manageEditorSkills:M()}),async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`No project root resolved.`,{handler:`skills-management-put`,detail:`NO_PROJECT_ROOT`});return}if(await jR(T,{manageEditorSkills:n.manageEditorSkills,surface:`ui`}),n.manageEditorSkills){let e=await Uz({projectDir:T,skillsRoot:zs(`project`)});e.adopted.length+e.collided.length>0&&Ve?.(`files`)}q(t,200,Zs,Qs(),{handler:`skills-management-put`})},{handler:`skills-management-put`,method:`PUT`})},{handler:`skills-management`}),ec=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-get`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-get`);if(i===null)return;if(r===Bs&&i===`project`){let e=Vs();if(e){let{frontmatter:n,body:a}=ks(await iu(e.skillMd,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:e.relPath,frontmatter:{name:typeof n.name==`string`?n.name:r,description:typeof n.description==`string`?n.description:``},body:a,files:yz(e.dir),managed:!0}},{handler:`skill-get`});return}}let a=zs(i),o=z(a,r,`SKILL.md`);if(!B(o)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-get`,detail:`Skill "${r}" not found in ${i} scope.`});return}let{frontmatter:s,body:c}=ks(await iu(o,`utf-8`));q(t,200,Xe,{skill:{name:r,scope:i,path:Ks(o,i),frontmatter:{name:typeof s.name==`string`?s.name:r,description:typeof s.description==`string`?s.description:``},body:c,files:yz(z(a,r))}},{handler:`skill-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill.`,{handler:`skill-get`,cause:e})}},{handler:`skill-get`,method:`GET`,skipBodyParse:!0}),tc=J(Kt,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-put`});return}if(!Is(n.name,t,`skill-put`)||Us(n.name,t,`skill-put`))return;let r=EM({name:n.name,body:typeof n.body==`string`?n.body:``,frontmatter:{name:n.frontmatter.name,description:n.frontmatter.description}});if(!r.ok){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill request.`,{handler:`skill-put`,detail:r.error.code,cause:Error(r.error.message)});return}let i=zs(n.scope),a=z(i,n.name,`SKILL.md`),o=!B(a),c=R(i,a).split(/[\\/]/).filter(Boolean).join(`/`),l=hr(n.scope,n.name);if(Ds(l,`skill-put`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=bi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{nS(m.dc.document,r.content,`agent`)},m.origin);let h=await mr(l);if(h?.kind===`failure`){_r(t,h.failure,`skill-put`);return}if(h?.kind===`divergence`){vr(t,`skill-put`);return}n.scope===`project`&&(Oi(e,Di(`skill`,``,n.name),`${o?`skill-create`:`skill-edit`}: ${c}`),await ki(`skill-put`)),Ve?.(`files`),q(t,200,rn,{path:c,created:o,warnings:r.warnings},{handler:`skill-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill.`,{handler:`skill-put`,cause:e})}},{handler:`skill-put`,method:`PUT`}),nc=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-delete`)||Us(r,t,`skill-delete`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-delete`);if(i===null)return;let a=zs(i),o=n.searchParams,s=_V({agentId:o.get(`agentId`)??void 0,agentName:o.get(`agentName`)??void 0,colorSeed:o.get(`colorSeed`)??void 0,clientName:o.get(`clientName`)??void 0,clientVersion:o.get(`clientVersion`)??void 0,label:o.get(`label`)??void 0,summary:o.get(`summary`)??void 0},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-delete`});return}await Rr([hr(i,r)],`deleted-upstream`);let c=MM({skillsRoot:a,name:r});if(!c.ok){let e=c.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill.`:`Invalid skill request.`,{handler:`skill-delete`,detail:c.error.code,cause:Error(c.error.message)});return}c.existed&&(i===`project`&&(Oi(s,Di(`skill`,``,r),`skill-delete: ${c.path}`),await ki(`skill-delete`)),Ve?.(`files`));let l=qs(i);l&&await Js(l,r),q(t,200,nt,{existed:c.existed,path:c.path},{handler:`skill-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill.`,{handler:`skill-delete`,cause:e})}},{handler:`skill-delete`,method:`DELETE`,skipBodyParse:!0}),rc=DH({GET:ec,PUT:tc,POST:J(Zt,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-move`});return}if(!Is(n.fromName,t,`skill-move`)||!Is(n.toName,t,`skill-move`)||Us(n.fromName,t,`skill-move`)||Us(n.toName,t,`skill-move`))return;let r=zs(n.scope);await Rr([hr(n.scope,n.fromName)],`renamed`);let i=await NM({skillsRoot:r,fromName:n.fromName,toName:n.toName,relocate:async(e,t)=>{let n=await ZJ(T,e,t);return n||XJ(e,t),n}});if(!i.ok){if(i.error.code===`SKILL_NOT_FOUND`){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-move`,detail:i.error.message});return}if(i.error.code===`SKILL_EXISTS`){G(t,409,`urn:ok:error:doc-already-exists`,i.error.message,{handler:`skill-move`,detail:i.error.code});return}let e=i.error.code===`MOVE_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to move skill.`:`Invalid skill move request.`,{handler:`skill-move`,detail:i.error.code,cause:Error(i.error.message)});return}let a=null,o=z(r,n.toName,`SKILL.md`),s=``,c=``;try{let e=ks(V(o,`utf-8`));s=e.body,typeof e.frontmatter.description==`string`&&(c=e.frontmatter.description)}catch{}let l=typeof n.body==`string`?n.body:s,u=n.frontmatter===void 0?c:n.frontmatter.description,d=DM({skillsRoot:r,name:n.toName,body:l,frontmatter:{name:n.toName,description:u}});if(d.ok||(a=d.error),n.scope===`project`&&!a)try{cc(r,n.fromName,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 f=Ks(z(r,n.fromName),n.scope),p=Ks(z(r,n.toName),n.scope);n.scope===`project`&&(Oi(e,Di(`skill`,``,n.toName),`skill-rename: ${f} -> ${p}`,[{from:f,to:p}]),await ki(`skill-move`));let m=qs(n.scope);if(m){let e=await _F(m,n.fromName);if(e){let t=nz(e.hosts);hz(n.fromName,m,t);let i=mz(z(r,n.toName),n.toName,m,t);await gF(m,n.toName,{...e,hosts:i})}}if(Ve?.(`files`),a){let e=a.code===`WRITE_ERROR`;G(t,e?500:400,e?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,`Skill renamed to "${n.toName}", but updating its SKILL.md failed — its name frontmatter may not match the new directory.`,{handler:`skill-move`,detail:a.code,cause:Error(a.message)});return}q(t,200,ke,{from:f,to:p,committed:i.committed},{handler:`skill-move`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to move skill.`,{handler:`skill-move`,cause:e})}},{handler:`skill-move`,method:`POST`}),DELETE:nc},{handler:`skill`});function ic(e){if(e.includes(`\0`))return null;let t=e.replace(/\\/g,`/`).split(`/`).filter(e=>e!==``&&e!==`.`);return t.length<2||t.some(e=>e===`..`)?null:t[0]===`references`?`reference`:t[0]===`scripts`?`script`:null}function ac(e,t,n){return e===`project`&&t===`reference`&&n.toLowerCase().endsWith(`.md`)}function oc(e,t){let n=t.replace(/\.md$/i,``);return`${ei(e).replace(/\/SKILL$/,``)}/${n}`}function sc(e,t){let n=z(e,t,`references`);if(!B(n))return[];let r=[],i=(e,t)=>{for(let n of Rl(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}function cc(e,t,n){if(!Ie)return;let r=(e,t,n)=>{let r;try{r=V(n,`utf-8`)}catch{Ie.deleteDocument(e),Le?.deleteDocument(e);return}Ie.renameDocument(e,t,r),Le?.renameDocument(e,t,r)};r(ei(t),ei(n),z(e,n,`SKILL.md`));for(let i of sc(e,n))r(oc(t,i),oc(n,i),z(e,n,i));Ve?.(`backlinks`),Ve?.(`graph`)}let lc=DH({GET:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`name`)??``;if(!Is(r,t,`skill-file-get`))return;let i=Ls(n.searchParams.get(`scope`),t,`skill-file-get`);if(i===null)return;let a=n.searchParams.get(`path`)??``,o=r===Bs&&i===`project`?Vs():null,s=o&&a===`SKILL.md`?`reference`:ic(a);if(s===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-get`});return}let c=o?o.dir:z(zs(i),r),l=z(c,a);if(l!==c&&!l.startsWith(`${c}${Cl}`)){G(t,400,`urn:ok:error:invalid-request`,`Skill file path escapes the skill dir.`,{handler:`skill-file-get`});return}let u=l,d=a;if(!B(u)){let e=a.match(/^(.*)\.(?:md|mdx)$/),n=e?_n.map(t=>`${e[1]}${t}`).find(e=>e!==a&&B(z(c,e))):void 0;if(n===void 0){G(t,404,`urn:ok:error:not-found`,`Skill file not found.`,{handler:`skill-file-get`,detail:`${a} not found in skill "${r}" (${i}).`});return}d=n,u=z(c,n)}let f=await iu(u);if(f.includes(0)){G(t,415,`urn:ok:error:invalid-request`,`Skill file is binary — only text bundle files are readable via MCP.`,{handler:`skill-file-get`});return}q(t,200,yt,{path:d.replace(/\\/g,`/`),kind:s,text:f.toString(`utf-8`)},{handler:`skill-file-get`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to read skill file.`,{handler:`skill-file-get`,cause:e})}},{handler:`skill-file-get`,method:`GET`,skipBodyParse:!0}),PUT:J(ve,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-put`});return}if(!Is(n.name,t,`skill-file-put`)||Us(n.name,t,`skill-file-put`))return;let r=ic(n.path);if(r===null){G(t,400,`urn:ok:error:invalid-request`,"Invalid skill file path (must be a file under references/ or scripts/, no `..`).",{handler:`skill-file-put`});return}if(Buffer.byteLength(n.content,`utf-8`)>262144){G(t,400,`urn:ok:error:invalid-request`,`Skill file exceeds the 256 KB per-file cap.`,{handler:`skill-file-put`});return}let i=zs(n.scope);if(!B(z(i,n.name,`SKILL.md`))){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-file-put`,detail:`Create skill "${n.name}" before adding bundle files.`});return}let a=n.path.replace(/\\/g,`/`),o=ac(n.scope,r,a),c;if(o){let e=oc(n.name,a);if(Ds(e,`skill-file-put`,t))return;if(c=!B(z(i,n.name,a)),c&&kM(z(i,n.name))>=50){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" already holds 50 bundle files (the cap) — delete one before adding another.`,{handler:`skill-file-put`});return}let{agentId:r,agentName:o,colorSeed:l,clientName:u}=bi(n),d=await s.getSession(e,r,{displayName:o,colorSeed:l,clientName:u});d.dc.document.transact(()=>{nS(d.dc.document,n.content,`agent`)},d.origin);let f=await mr(e);if(f?.kind===`failure`){_r(t,f.failure,`skill-file-put`);return}if(f?.kind===`divergence`){vr(t,`skill-file-put`);return}}else{let e=AM({skillsRoot:i,name:n.name,relPath:a,content:n.content});if(!e.ok){let n=e.error.code===`WRITE_ERROR`?500:e.error.code===`SKILL_NOT_FOUND`?404:400;G(t,n,n===500?`urn:ok:error:internal-server-error`:n===404?`urn:ok:error:not-found`:`urn:ok:error:invalid-request`,n===500?`Failed to write skill file.`:`Invalid skill file request.`,{handler:`skill-file-put`,detail:e.error.code,cause:Error(e.error.message)});return}c=e.created}n.scope===`project`&&(Oi(e,Di(`skill`,``,n.name),`${c?`skill-file-create`:`skill-file-edit`}: .ok/skills/${n.name}/${a}`),await ki(`skill-file-put`)),Ve?.(`files`),q(t,200,Pe,{path:a,created:c,kind:r,content:o},{handler:`skill-file-put`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write skill file.`,{handler:`skill-file-put`,cause:e})}},{handler:`skill-file-put`,method:`PUT`}),DELETE:J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams,r=n.get(`name`)??``;if(!Is(r,t,`skill-file-delete`)||Us(r,t,`skill-file-delete`))return;let i=Ls(n.get(`scope`),t,`skill-file-delete`);if(i===null)return;let a=(n.get(`path`)??``).replace(/\\/g,`/`),o=ic(a);if(o===null){G(t,400,`urn:ok:error:invalid-request`,`Invalid skill file path (must be a file under references/ or scripts/).`,{handler:`skill-file-delete`});return}let s=_V({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},ut);if(s.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-file-delete`});return}let c=zs(i);ac(i,o,a)&&await Rr([oc(r,a)],`deleted-upstream`);let l=jM({skillsRoot:c,name:r,relPath:a});if(!l.ok){let e=l.error.code===`UNLINK_FAILED`?500:400;G(t,e,e===500?`urn:ok:error:internal-server-error`:`urn:ok:error:invalid-request`,e===500?`Failed to delete skill file.`:`Invalid skill file request.`,{handler:`skill-file-delete`,detail:l.error.code,cause:Error(l.error.message)});return}l.existed&&i===`project`&&(Oi(s,Di(`skill`,``,r),`skill-file-delete: .ok/skills/${r}/${a}`),await ki(`skill-file-delete`)),l.existed&&Ve?.(`files`),q(t,200,ct,{path:a,existed:l.existed,kind:o},{handler:`skill-file-delete`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to delete skill file.`,{handler:`skill-file-delete`,cause:e})}},{handler:`skill-file-delete`,method:`DELETE`,skipBodyParse:!0})},{handler:`skill-file`}),uc=J(Ot,async(e,t,n)=>{try{let e=zs(n.scope);if(!Is(n.name,t,`skill-install`)||Us(n.name,t,`skill-install`))return;if(n.scope===`project`&&!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot install — no project root is resolved for this server. Skills project into editor host dirs at the project root.`,{handler:`skill-install`,detail:`NO_PROJECT_ROOT`});return}let r=qs(n.scope),i=z(e,n.name);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill not found.`,{handler:`skill-install`,detail:`Skill "${n.name}" not found in ${n.scope} scope — create it with write({ skill }) first.`});return}let a=cz(i,n.name);if(!a.ok){G(t,400,`urn:ok:error:invalid-request`,`Skill "${n.name}" cannot be installed: ${a.errors.join(` `)}`,{handler:`skill-install`,detail:`INVALID_SKILL_SOURCE`});return}let o=n.scope===`global`?n.targets?He.filter(e=>n.targets?.some(t=>t===e)):[...He]:n.targets===void 0?uz(r,Yz(r)??void 0):He.filter(e=>n.targets?.some(t=>t===e)),s=[],c=[];o.length===0&&n.targets===void 0&&(s.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`."),c.push(`no-targets`)),a.hasScripts&&(s.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."),c.push(`scripts-present`));let l=nz(mF(r).skills[n.name]?.hosts??[]).filter(e=>!o.includes(e));l.length>0&&hz(n.name,r,l);let u=mz(i,n.name,r,o);u.length===0?await _F(r,n.name):await gF(r,n.name,{hosts:u,scope:n.scope,scripts:a.hasScripts,installedAt:new Date().toISOString()}),Ve?.(`files`),q(t,200,v,{name:n.name,hosts:u,scripts:a.hasScripts,warnings:s,warningCodes:c},{handler:`skill-install`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to install skill.`,{handler:`skill-install`,cause:e})}},{handler:`skill-install`,method:`POST`}),dc=J(xn,async(e,t,n)=>{try{if(!Is(n.name,t,`skill-uninstall`)||Us(n.name,t,`skill-uninstall`))return;let e=qs(n.scope);if(!e){G(t,400,`urn:ok:error:invalid-request`,`Cannot uninstall — no project root is resolved for this server.`,{handler:`skill-uninstall`,detail:`NO_PROJECT_ROOT`});return}let r=await Js(e,n.name);Ve?.(`files`),q(t,200,tee,{name:n.name,uninstalled:r},{handler:`skill-uninstall`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to uninstall skill.`,{handler:`skill-uninstall`,cause:e})}},{handler:`skill-uninstall`,method:`POST`}),fc=DH({GET:J(g,EH(async(e,t)=>{let n=T?Yz(T):null;q(t,200,Be,{targets:uz(T??``,n??void 0),configured:n!==null},{handler:`skill-targets-get`})},{handler:`skill-targets-get`,title:`Failed to read skill targets.`}),{handler:`skill-targets-get`,method:`GET`,skipBodyParse:!0}),PUT:J(hn,EH(async(e,t,n)=>{if(!T){G(t,400,`urn:ok:error:invalid-request`,`Cannot set skill targets — no project root is resolved for this server.`,{handler:`skill-targets-put`,detail:`NO_PROJECT_ROOT`});return}let r=n.targets,i=new Set(r),a=uz(T,Yz(T)??void 0),o=zs(`project`);await Xz(T,r);let{reprojected:s,bundleHosts:c}=await Kz({projectDir:T,skillsRoot:o,targets:r});Ve?.(`files`),q(t,200,ln,{targets:r,reprojected:s,bundleHosts:c,removedFrom:a.filter(e=>!i.has(e))},{handler:`skill-targets-put`})},{handler:`skill-targets-put`,title:`Failed to set skill targets.`}),{handler:`skill-targets-put`,method:`PUT`})},{handler:`skill-targets`}),pc=J(we,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-restore`});return}if(!Is(n.name,t,`skill-restore`)||Us(n.name,t,`skill-restore`))return;if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Global skills are unversioned — there is no version history to restore from.`,{handler:`skill-restore`,detail:`GLOBAL_SCOPE_UNVERSIONED`});return}let r=be?.current;if(!r){G(t,409,`urn:ok:error:shadow-not-configured`,`No version history available to restore from.`,{handler:`skill-restore`,detail:`NO_SHADOW_REPO`});return}let i=await OK({shadow:r,contentDir:l,contentRoot:Fe??`.`,name:n.name,version:n.version});if(!i.ok){let[e,n]={"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`]}[i.code];G(t,e,n,i.error,{handler:`skill-restore`,detail:i.code});return}let a=[],o=cz(z(l,`.ok`,`skills`,n.name),n.name);o.ok||a.push(`Restored, but the skill no longer validates: ${o.errors.join(` `)}`),a.push("Run `install` to push the restored version to your editors."),Oi(e,Di(`skill`,``,n.name),`skill-restore: ${n.name} @ ${n.version.slice(0,8)}`),await ki(`skill-restore`),Ve?.(`files`),q(t,200,Ke,{name:n.name,version:n.version,restoredFiles:i.restoredFiles,warnings:a},{handler:`skill-restore`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to restore skill.`,{handler:`skill-restore`,cause:e})}},{handler:`skill-restore`,method:`POST`}),mc=J(c,async(e,t,n)=>{try{let e=_V(n,ut);if(e.kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`skill-update`});return}if(!Is(n.name,t,`skill-update`)||Us(n.name,t,`skill-update`))return;if(!bz(n.name)){G(t,400,`urn:ok:error:invalid-request`,"Only starter-pack skills (`open-knowledge-pack-*`) can be updated from the bundle.",{handler:`skill-update`,detail:`NOT_A_PACK_SKILL`});return}if(n.scope===`global`){G(t,400,`urn:ok:error:invalid-request`,`Pack skills are project-scope — there is no global-scope pack to update.`,{handler:`skill-update`,detail:`GLOBAL_SCOPE`});return}let r=Tz(n.name);if(r===null||r.version===void 0){G(t,404,`urn:ok:error:not-found`,`No bundled version is available for this pack skill.`,{handler:`skill-update`,detail:`NO_BUNDLED_VERSION`});return}let i=z(zs(`project`),n.name,`SKILL.md`);if(!B(i)){G(t,404,`urn:ok:error:not-found`,`Skill is not installed.`,{handler:`skill-update`,detail:`SKILL_ABSENT`});return}let a;try{a=Sz(V(i,`utf-8`))}catch{}let o,c=be?.current;if(c)try{let e=Oe?.()??`main`;o=(await nC(c,Fe??`.`,[qS],e,`Before updating ${n.name} (${a??`unversioned`} → ${r.version})`)).checkpointRef}catch(e){F(`skills`).warn({err:e,skill:n.name},`pre-update checkpoint failed — proceeding with overwrite`)}let l=hr(`project`,n.name);if(Ds(l,`skill-update`,t))return;let{agentId:u,agentName:d,colorSeed:f,clientName:p}=bi(n),m=await s.getSession(l,u,{displayName:d,colorSeed:f,clientName:p});m.dc.document.transact(()=>{nS(m.dc.document,r.content,`agent`)},m.origin);let h=await mr(l);if(h?.kind===`failure`){_r(t,h.failure,`skill-update`);return}if(h?.kind===`divergence`){vr(t,`skill-update`);return}Oi(e,Di(`skill`,``,n.name),`skill-pack-update: ${n.name} (${a??`unversioned`} → ${r.version})`),await ki(`skill-update`),Ve?.(`files`),q(t,200,tr,{name:n.name,version:r.version,...a===void 0?{}:{previousVersion:a},...o===void 0?{}:{checkpointRef:o}},{handler:`skill-update`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to update skill.`,{handler:`skill-update`,cause:e})}},{handler:`skill-update`,method:`POST`});function hc(e){let t=new Map;for(let n of e){let e=n.path.split(`/`).filter(Boolean);e.pop();for(let r=1;r<=e.length;r++){let i=e.slice(0,r).join(`/`);t.set(i,Math.max(t.get(i)??0,n.modifiedTs))}}return[...t.entries()].map(([e,t])=>Pt({kind:`folder`,path:e,modifiedTs:t}))}function gc(e,t){let n=t.trim().toLowerCase();if(!n||!e)return;let r=e.toLowerCase().indexOf(n);if(r<0)return;let i=Math.max(0,r-80),a=Math.min(e.length,r+n.length+120),o=i>0?`…`:``,s=a<e.length?`…`:``;return`${o}${e.slice(i,a).replace(/\s+/g,` `).trim()}${s}`.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g,`�`)}function _c(e){return e===`autocomplete`||e===`full_text`||e===`omnibar`?e:`omnibar`}function vc(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 yc(e){if(typeof e==`boolean`)return e;if(e===`true`)return!0;if(e===`false`)return!1}function bc(e){return e===`omnibar`||e===`mcp`||e===`http`?e:`http`}async function xc(e,t,n,r){let i=r.documents.filter(e=>!fr(e.path)),a=i.reduce((e,t)=>e+ +(t.kind===`page`),0);if(!Vt?.isEnabled()||n!==!0)return{queryEmbedMs:null,pageTotal:a,capable:!1};Vt.embedCorpus(i);let o,s=null;if(t===`full_text`&&e.trim().length>=3){let t=performance.now(),n=await Vt.queryScores(e,i);if(s=performance.now()-t,n&&n.size>0){let e=Ht?.();o=e===void 0?{scores:n}:{scores:n,similarityFloor:e}}}let c=Vt.getStatus();return{input:o,status:{capable:c.capable,applied:!1,coverage:{embedded:c.embeddedCount,total:a}},queryEmbedMs:s,pageTotal:a,capable:c.capable}}function Sc(e,t){return{kind:e.document.kind,path:e.document.path,title:e.document.title,score:e.score,signals:e.signals,snippet:e.document.kind===`page`?gc(e.document.content,t):void 0}}async function Cc(e){let t=performance.now();if(Mc())return{query:e.query,intent:e.intent,results:[],elapsedMs:Math.max(0,performance.now()-t),ready:!1};let{corpus:n,truncated:r}=await Nc(),i=await xc(e.query,e.intent,e.semanticParam,n),a=se(n,e.query,{intent:e.intent,ranking:e.ranking,scopes:e.scopes,limit:e.limit,semantic:i.input}).map(t=>Sc(t,e.query)),o;if(i.status){let t=a.reduce((e,t)=>e+(t.signals.vector===void 0?0:1),0),n=t>0;o={...i.status,applied:n},zN({outcome:i.capable?n?`applied`:i.status.coverage.embedded===0?`warming`:`no_match`:`incapable`,source:e.source,capable:i.capable,embedded:i.status.coverage.embedded,total:i.pageTotal,queryEmbedMs:i.queryEmbedMs,vectorContributors:t})}return{query:e.query,intent:e.intent,results:a,elapsedMs:Math.max(0,performance.now()-t),ready:!0,...o?{semantic:o}:{},...r?{truncated:!0}:{}}}function wc(){let e=zs(`project`);if(!B(e))return[];let t;try{t=Rl(e,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of t.sort((e,t)=>e.name.localeCompare(t.name))){if(!r.isDirectory()||!mt.test(r.name))continue;let t=z(e,r.name,`SKILL.md`);try{let e=Wl(t);n.push({name:r.name,absolutePath:t,mtimeMs:e.mtimeMs,size:e.size})}catch{}}return n}function Tc(){let e=[];for(let t of wc()){let n=t.name,r=``;try{let{frontmatter:e,body:i}=ks(V(t.absolutePath,`utf-8`));typeof e.name==`string`&&e.name&&(n=e.name),r=`${typeof e.description==`string`?e.description:``}\n\n${i}`.trim()}catch{}e.push(Pt({kind:`page`,path:hr(`project`,t.name),title:n,content:r,modifiedTs:t.mtimeMs}))}return e}function Ec(e){return`${e.modified}\0${e.size}\0${e.canonicalPath}\0${e.inode}\0${e.aliases.join(`\0`)}`}let Dc=new Map;async function Oc(){let e=[],t=[],n=new Set;for(let[r,i]of S()){if(oC(r)||cC(r)||r.startsWith(`.ok/skills/`))continue;if(i.kind===`file`){t.push(Pt({kind:`file`,path:r,modifiedTs:Date.parse(i.modified),aliases:i.aliases}));continue}n.add(r);let a=Ec(i),o=Dc.get(r);if(o&&o.key===a){e.push(o.doc);continue}let s=``,c=r,l=!1;try{s=await iu(i.canonicalPath,`utf-8`)}catch(e){l=!0,Y.warn({docName:r,err:e},`[search] Failed to read ${r}`)}if(!l)try{c=cL(s,r)}catch(e){Y.warn({docName:r,err:e},`[search] Failed to extract title for ${r}`)}let u=Pt({kind:`page`,path:r,title:c,content:s,modifiedTs:Date.parse(i.modified),aliases:i.aliases});l||Dc.set(r,{key:a,doc:u}),e.push(u)}for(let e of Dc.keys())n.has(e)||Dc.delete(e);let r=fJ(),i=t,a=!1;return t.length>r&&(a=!0,i=[...t].sort((e,t)=>e.path.split(`/`).length-t.path.split(`/`).length||e.path.localeCompare(t.path)).slice(0,r),F(`search`).warn({dropped:t.length-i.length,retained:i.length,limit:r},`[search] corpus name-only file tier truncated at OK_SEARCH_MAX_ENTRIES`),Bq().add(1)),{documents:[...e,...Tc(),...i,...hc([...e,...i])],truncated:a}}function kc(){return wc().map(e=>`${e.name} ${e.mtimeMs} ${e.size}`).join(``)}function Ac(){return te?`gen:${te()}|skills${kc()}`:`${[...S()].filter(([e])=>!oC(e)&&!cC(e)).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}\0${Ec(t)}`).join(``)}|skills${kc()}`}let jc=kt===void 0;kt?.then(()=>{jc=!0},e=>{jc=!0,Y.warn({err:e,handler:`search`},`[api] ready gate rejected — search serves the partial index`)});function Mc(){return!jc}async function Nc(){let e=`${l}${T??``}`,t=Ac(),n=QJ.get(e);if(n?.fingerprint===t&&n.corpus)return{corpus:n.corpus,truncated:n.truncated??!1};if(n?.fingerprint===t&&n.pending)return n.pending;let r=n?.corpus,i=n?.pending,a=(async()=>{let e=i?await i.then(e=>e.corpus,()=>void 0):r,{documents:t,truncated:n}=await Oc();if(!e)return Hq().add(1,{mode:`cold`}),{corpus:mee(t),truncated:n};let a=ee(e,t);if(a.rebuilt){Hq().add(1,{mode:`rebuild`,reason:a.rebuildReason});let e=a.rebuildReason===`mutation-failed`?`warn`:`debug`;F(`search`)[e]({reason:a.rebuildReason,documents:t.length},`[search] corpus update fell back to a full index rebuild`)}else Hq().add(1,{mode:`incremental`}),F(`search`).debug({inserted:a.inserted,updated:a.updated,removed:a.removed},`[search] corpus updated incrementally`);return{corpus:a.corpus,truncated:n}})();QJ.set(e,{fingerprint:t,pending:a});try{let n=await a;return QJ.get(e)?.pending===a&&QJ.set(e,{fingerprint:t,corpus:n.corpus,truncated:n.truncated}),n}catch(t){throw QJ.get(e)?.pending===a&&QJ.delete(e),t}}function Pc(){if(process.env.NODE_ENV!==`test`)for(let e of[0,1e3,3e3])setTimeout(()=>{Nc().catch(e=>{Y.warn({err:e},`[search] Failed to prewarm workspace search cache`)})},e)}Pc();let Fc=DH({GET:J(g,EH(async(e,t)=>{let n=xee(e),r=n.get(`limit`),i=n.get(`query`)??``,a=_c(n.get(`intent`)),o=Gs(n.get(`ranking`)),s=vc(n.get(`scope`)??n.get(`scopes`)),c=yc(n.get(`semantic`)),l=bc(n.get(`source`)),u=r===null?void 0:Number(r);if(i.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-get`});return}q(t,200,p,await Cc({query:i,intent:a,ranking:o,scopes:s,limit:u,semanticParam:c,source:l}),{handler:`search-get`})},{handler:`search-get`,title:`Failed to search workspace.`}),{handler:`search-get`,method:`GET`,skipBodyParse:!0}),POST:J(Ur,EH(async(e,t,n)=>{let r=typeof n.query==`string`?n.query:``,i=_c(n.intent),a=Gs(n.ranking),o=vc(n.scopes??n.scope),s=typeof n.limit==`number`?n.limit:void 0,c=yc(n.semantic),l=bc(n.source);if(r.length>200){G(t,400,`urn:ok:error:invalid-request`,`Query is too long (max 200 chars).`,{handler:`search-post`});return}q(t,200,p,await Cc({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`}),Ic=J(g,EH(async(e,t)=>{q(t,200,va,{...await mR(Xl())},{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 Lc(e,t){if(r(e,t,{handler:`handoff`}))try{await Nae(e,t,{contentDir:l,platform:process.platform,isSchemeRegistered:In.probeWithCache})}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[handoff] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`handoff`,cause:n}))}}async function Rc(e,t){if(r(e,t,{handler:`spawn-cursor`}))try{await ZP(e,t,{contentDir:l,platform:process.platform})}catch(n){t.headersSent||(Y.error({err:n,requestId:jC(e)},`[spawn-cursor] route wrapper failed`),G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`spawn-cursor`,cause:n}))}}let zc=J(dee,async(e,t,n)=>{try{if(!T){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}let e=n.kind===`doc`?n.docPath:n.folderPath;if(!use(e,n.kind)){dL(`invalid-path`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`invalid-path`},{handler:uL});return}let r=hse(T);if(r===null){if(hL(T).kind===`no-remote`){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}dL(`detached-head`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`detached-head`},{handler:uL});return}let i=hL(T);if(i.kind===`no-remote`){dL(`no-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`no-remote`},{handler:uL});return}if(i.kind===`non-github`){dL(`non-github-remote`,{kind:n.kind}),q(t,200,Er,{ok:!1,error:`non-github-remote`},{handler:uL});return}if(!bse(T,r)){dL(`branch-not-on-origin`,{branchExists:!1,kind:n.kind}),q(t,200,Er,{ok:!1,error:`branch-not-on-origin`,branch:r},{handler:uL});return}let a=WJ(T,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=dse(i.host,i.owner,i.repo,r,n.docPath);else{let e=n.folderPath===``?a:n.folderPath;s=fse(i.host,i.owner,i.repo,r,e)}let c=`https://openknowledge.ai/d/${Sh(s)}`,u=await pse(T,r,a===``?e:e===``?a:`${a}/${e}`,n.kind);dL(`ok`,{branchExists:!0,kind:n.kind,freshness:u}),q(t,200,Er,{ok:!0,shareUrl:c,sharedUrl:s,branch:r,freshness:u},{handler:uL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:uL,cause:e})}},{handler:uL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:uL})}),Bc=J(g,async(e,t)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:fH});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(!yr(r)){G(t,400,`urn:ok:error:invalid-request`,`branch query param missing or malformed.`,{handler:fH});return}if(!uH(i,a)){G(t,400,`urn:ok:error:invalid-request`,`path query param missing or malformed.`,{handler:fH});return}q(t,200,$n,await dH(T,r,i,a),{handler:fH})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:fH,cause:e})}},{handler:fH,method:`GET`,skipBodyParse:!0}),Vc=J(Wi,async(e,t,n)=>{try{if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:jL});return}if(!uH(n.path,n.kind)){G(t,400,`urn:ok:error:invalid-request`,`path is missing or malformed.`,{handler:jL});return}let e=WJ(T,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}`;q(t,200,aee,await PL(T,n.branch,r,n.kind),{handler:jL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:jL,cause:e})}},{handler:jL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:jL})}),Hc=J(Li,async(e,t,n)=>{if(_V(n,ut).kind===`invalid-summary`){G(t,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:_H});return}if(!T){G(t,500,`urn:ok:error:internal-server-error`,`projectDir is not configured for this server.`,{handler:_H});return}try{q(t,200,ii,await fs(()=>yH(T,n.branch,{fastForward:n.fastForward===!0})),{handler:_H})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:_H,cause:e})}},{handler:_H,method:`POST`});async function Uc(e){let[t,...n]=it,r=[...n,...e];return await new Promise((e,n)=>{let i=ml(t,r,OP({...to,env:{...process.env}})),a=!1,o=setTimeout(()=>{a=!0,i.kill(`SIGTERM`)},bL),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 ${bL}ms`));return}let r=Buffer.concat(s).toString(`utf-8`);if(t!==0){let e=AL(Buffer.concat(c).toString(`utf-8`)).slice(0,500);Y.warn({code:t,stderr:e},`[share] subprocess exited code=${t} stderr=${e}`)}e({stdout:r,code:t})}),i.on(`error`,e=>{clearTimeout(o),n(e)})})}let Wc=J(g,async(e,t)=>{if(!un.tryAcquire(`/api/share/publish/owners`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share owners operation is already in progress.`,{handler:_L,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Uc([`share`,`owners`,`--json`]),n=xse(CL(e));kL(`owners-list`,n.ok?`ok`:n.error,n.ok?{count:n.owners.length}:void 0),q(t,200,Ai,n,{handler:_L})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:_L,cause:e})}finally{un.release(`/api/share/publish/owners`)}},{handler:_L,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:_L})}),Gc=J(g,async(e,t)=>{let n=new URL(e.url??``,`http://localhost`),r=n.searchParams.get(`owner`)??``,i=n.searchParams.get(`name`)??``;if(!SL(r)||!xL(i)){G(t,400,`urn:ok:error:invalid-request`,`owner and name query params must be valid GitHub identifiers.`,{handler:vL});return}if(!un.tryAcquire(`/api/share/publish/name-check`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share name-check operation is already in progress.`,{handler:vL,extraHeaders:{"Retry-After":`5`}});return}try{let{stdout:e}=await Uc([`share`,`name-check`,`--owner`,r,`--name`,i,`--json`]),n=TL(CL(e));kL(`name-check`,n.ok?`ok`:n.error,n.ok?{available:n.available}:void 0),q(t,200,di,n,{handler:vL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:vL,cause:e})}finally{un.release(`/api/share/publish/name-check`)}},{handler:vL,method:`GET`,skipBodyParse:!0,preBodyGate:(e,t)=>r(e,t,{handler:vL})}),Kc=J(Un,async(e,t,n)=>{if(!T){kL(`publish-create`,`no-project`),q(t,200,Gr,{ok:!1,error:`no-project`},{handler:yL});return}if(!SL(n.owner)||!xL(n.name)){G(t,400,`urn:ok:error:invalid-request`,`owner and name must be valid GitHub identifiers.`,{handler:yL});return}if(!un.tryAcquire(`/api/share/publish`)){G(t,429,`urn:ok:error:concurrent-operation`,`A share publish operation is already in progress.`,{handler:yL,extraHeaders:{"Retry-After":`5`}});return}try{let e=[`share`,`publish`,`--owner`,n.owner,`--name`,n.name,`--visibility`,n.visibility,`--project-dir`,T,`--json`];n.description!==void 0&&n.description.length>0&&e.push(`--description`,n.description);let{stdout:r}=await Uc(e),i=OL(CL(r));kL(`publish-create`,i.ok?`ok`:i.error),i.ok&&$e?.()?.refreshRemote().catch(()=>{}),q(t,200,Gr,i,{handler:yL})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:yL,cause:e})}finally{un.release(`/api/share/publish`)}},{handler:yL,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:yL})}),qc=J(_,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{}q(t,200,Xt,{accepted:n.entries.length},{handler:`client-logs`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`client-logs`,cause:e})}},{handler:`client-logs`,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:`client-logs`})}),Jc=T?zA(T):null;async function Yc(e,t){if(e.method===`GET`||e.method===`HEAD`){try{let n={collabUrl:LA(e.headers),previewUrl:null,port:Jc?ws(Jc)?.port??0:0,singleFile:an};if(e.method===`HEAD`){t.setHeader(`Content-Type`,`application/json`),t.setHeader(`Cache-Control`,`no-store`),t.setHeader(`X-Content-Type-Options`,`nosniff`),t.statusCode=200,t.end();return}q(t,200,xe,n,{handler:`api-config`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`api-config`,cause:e})}return}G(t,405,`urn:ok:error:method-not-allowed`,`Method not allowed.`,{handler:`api-config`,extraHeaders:{Allow:`GET, HEAD`}})}let Xc=`local-op-embeddings-set-key`,Zc=`local-op-embeddings-clear-key`,Qc=`/api/local-op/embeddings`;function $c(){let e=Jt?.();return{projectDir:T??l,baseUrl:e?.baseUrl??`https://api.openai.com/v1`}}let el=J(gr,async(e,t,n)=>{if(!un.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Xc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:r}=$c();await new dP(qt).setForProject(e,r,n.key),Vt?.reloadCredential(),q(t,200,Cr,{keyPresent:!0},{handler:Xc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to store the key.`,{handler:Xc,cause:e})}finally{un.release(Qc)}},{handler:Xc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Xc})}),tl=J(g,async(e,t)=>{if(!un.tryAcquire(Qc)){G(t,429,`urn:ok:error:concurrent-operation`,`An embeddings key operation is already in progress.`,{handler:Zc,extraHeaders:{"Retry-After":`5`}});return}try{let{projectDir:e,baseUrl:n}=$c();await new dP(qt).clearForProject(e,n),Vt?.reloadCredential(),q(t,200,Cr,{keyPresent:!1},{handler:Zc,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to clear the key.`,{handler:Zc,cause:e})}finally{un.release(Qc)}},{handler:Zc,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:Zc})}),nl=`local-op-embeddings-test`,rl=`/api/local-op/embeddings/test`,il=J(g,async(e,t)=>{if(!un.tryAcquire(rl)){G(t,429,`urn:ok:error:concurrent-operation`,`A connection test is already in progress.`,{handler:nl,extraHeaders:{"Retry-After":`5`}});return}try{let e=Jt?.()??{baseUrl:`https://api.openai.com/v1`,model:`text-embedding-3-small`,dimensions:void 0},n=await eP(new dP(qt),T??l,e.baseUrl),r={endpoint:e.baseUrl,model:e.model},i=n.apiKey||n.keyless?await nP({baseUrl:e.baseUrl,model:e.model,dimensions:e.dimensions,apiKey:n.apiKey??void 0}):{ok:!1,reason:`no_key`,status:void 0};q(t,200,Dn,i.ok?{ok:!0,...r,dimensions:i.dimensions}:{ok:!1,...r,reason:i.reason,status:i.status},{handler:nl,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to test the embeddings endpoint.`,{handler:nl,cause:e})}finally{un.release(rl)}},{handler:nl,method:`POST`,preBodyGate:(e,t)=>r(e,t,{handler:nl})}),al=J(g,async(e,t)=>{try{let e=!1,n=!1,r=!1,i=0;if(Vt){let t=Vt.getStatus();e=t.enabled,n=t.ready,r=t.capable,i=t.embeddedCount}let a=Jt?.()?.baseUrl??`https://api.openai.com/v1`,o=await eP(new dP(qt),T??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,f=0;for(let[e]of m())!oC(e)&&!cC(e)&&!fr(e)&&(f+=1);q(t,200,Lr,{enabled:e,keyPresent:s,keyNotRequired:c,keySource:u,keyHint:d,ready:n,capable:r,embedded:i,total:f},{handler:`semantic-status`,extraHeaders:{"Cache-Control":`no-store`}})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:`semantic-status`,cause:e})}},{handler:`semantic-status`,method:`GET`,skipBodyParse:!0});async function ol(e,t){let n=Qt?.()??zr;try{let r=await Gi(e,VI(l,n,{docName:t,projectDir:T??l,onProblem:e=>Y.warn({problem:e,docName:t},`[lint] native config problem`)}),t),i=[],a=en?.()??`warning`;if(Ie&&a!==`off`&&!fC(t)){Ie.updateDocumentFromMarkdown(t,e);let r=$I({projectDir:T??l,contentDir:l,baseConfig:n,backlinkIndex:Ie,linksValidation:a,admittedDocNames:Sr,docFilePathFor:e=>FJ(l,e)}).find(e=>e.id===`links`);r&&(i=(await r.run({targetPath:FJ(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}:{}}))}catch(e){return Y.warn({err:e,docName:t},`[lint] advisory validation pass failed post-write; omitting advisories`),[]}}function sl(e){let t=e.plugins.frontmatter;if(!t.enabled||t.schemas.length===0)return[];let n=UI({projectDir:T??l,contentDir:l});return pI(t.schemas,n)}let cl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`);if(n!==null&&(n===``||!eY(n))){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`lint-config`});return}let r=Qt?.()??zr,i=[],a=RI(l,n??void 0,e=>i.push(e)),o=BI(T??l,zI(r,a),e=>i.push(e));n===null&&i.push(...sl(o)),q(t,200,jt,{effective:o,configFile:a?.file??null,configProblems:i},{handler:`lint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to resolve lint config.`,{handler:`lint-config`,cause:e})}},{handler:`lint-config`,method:`GET`,skipBodyParse:!0}),ll=J(ce,async(e,t,n)=>{let r;try{r=QI(z(l),n.ruleId,n.value)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write markdownlint config.`,{handler:`markdownlint-config`,cause:e});return}if(r.action===`declined-executable`){G(t,409,`urn:ok:error:config-not-writable`,`The native markdownlint config (${r.file}) is an executable module OK will not rewrite — edit it directly or convert it to JSON/JSONC/YAML.`,{handler:`markdownlint-config`});return}Ve?.(`lint-config`);try{let e=Qt?.()??zr,n=[],r=RI(l,void 0,e=>n.push(e)),i=BI(T??l,zI(e,r),e=>n.push(e));n.push(...sl(i)),q(t,200,jt,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`markdownlint-config`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The markdownlint rule was saved, but the effective config could not be re-read.`,{handler:`markdownlint-config`,cause:e})}},{handler:`markdownlint-config`,method:`POST`}),ul=J(ua,async(e,t,n)=>{let r;try{let e=z(T??l),t=n.parentPath??[];r=n.delete?Joe(e,n.file):n.field!==void 0&&n.removeField?Koe(e,n.file,n.field,t):n.field!==void 0&&n.renameTo!==void 0?qoe(e,n.file,n.field,n.renameTo,t):n.field!==void 0&&n.constraint!==void 0?Woe(e,n.file,n.field,n.constraint,t):Goe(e,n.file)}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to write the frontmatter schema.`,{handler:`frontmatter-schema`,cause:e});return}if(r.action===`refused`){G(t,409,`urn:ok:error:config-not-writable`,`The frontmatter schema (${r.file}) was not written: ${r.reason}.`,{handler:`frontmatter-schema`});return}(r.action===`created`||r.action===`deleted`)&&Ve?.(`files`),Ve?.(`lint-config`);try{let e=Qt?.()??zr,n=[],r=RI(l,void 0,e=>n.push(e)),i=BI(T??l,zI(e,r),e=>n.push(e));n.push(...sl(i)),q(t,200,jt,{effective:i,configFile:r?.file??null,configProblems:n},{handler:`frontmatter-schema`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`The schema was saved, but the effective config could not be re-read.`,{handler:`frontmatter-schema`,cause:e})}},{handler:`frontmatter-schema`,method:`POST`}),dl=J(g,async(e,t)=>{try{let e=z(T??l),{schemas:n,truncated:r}=yoe(e),i=new Set(n),a=!1;if(Ct!==void 0){let t=vJ({contentDir:l,contentFilter:Ct,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&&pr(a)){let t=R(e,z(l,a));!t.startsWith(`..`)&&!bl(t)&&i.add(t)}n=await t.next()}a=n.value.truncated}let o=[...i].sort((e,t)=>e.localeCompare(t));q(t,200,Ln,{schemas:o.slice(0,500),truncated:r||a||o.length>500},{handler:`frontmatter-schemas-list`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to list frontmatter schemas.`,{handler:`frontmatter-schemas-list`,cause:e})}},{handler:`frontmatter-schemas-list`,method:`GET`,skipBodyParse:!0}),fl=e=>{let t=e.replace(/\.(md|mdx)$/i,``),n=a.documents.get(t);return n===void 0?null:n.getText(`source`).toString()},pl=J(g,async(e,t)=>{try{let n=new URL(e.url??``,`http://localhost`).searchParams.get(`doc`)??``;if(n===``||!eY(n)){G(t,400,`urn:ok:error:invalid-request`,`Missing or invalid doc.`,{handler:`lint`});return}let r=FJ(l,n);if(r===null){G(t,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint`});return}let i=Qt?.()??zr,a=[],o=await HI({projectDir:T??l,contentDir:l,baseConfig:i,docRelPath:r,onConfigProblem:e=>a.push(e),liveSourceFor:fl});q(t,200,b,a.length>0?{...o,warnings:a}:o,{handler:`lint`})}catch(e){if(e instanceof LF){G(t,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint`});return}G(t,500,`urn:ok:error:internal-server-error`,`Failed to lint document.`,{handler:`lint`,cause:e})}},{handler:`lint`,method:`GET`,skipBodyParse:!0}),hl=J(g,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&&!bJ(r)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`lint-audit`});return}let i=Qt?.()??zr;q(t,200,_ee,await WI({projectDir:T??l,contentDir:l,baseConfig:i,targetPath:r,liveSourceFor:fl}),{handler:`lint-audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`lint-audit`,cause:e})}},{handler:`lint-audit`,method:`GET`,skipBodyParse:!0}),gl=J(g,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&&!bJ(i)){G(t,400,`urn:ok:error:invalid-request`,`Invalid path.`,{handler:`audit`});return}let a=n.searchParams.get(`doc`),o=a===null||a===``?void 0:a;if(o!==void 0){if(i!==void 0||!bJ(o)){G(t,400,`urn:ok:error:invalid-request`,`Invalid doc.`,{handler:`audit`});return}i=FJ(l,o)??`${o}.md`}let s=Qt?.()??zr;q(t,200,ne,await Zoe($I({projectDir:T??l,contentDir:l,baseConfig:s,liveSourceFor:fl,backlinkIndex:Ie??null,linksValidation:en?.(),admittedDocNames:Sr,docFilePathFor:e=>FJ(l,e)}),{targetPath:i}),{handler:`audit`})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Failed to audit project.`,{handler:`audit`,cause:e})}},{handler:`audit`,method:`GET`,skipBodyParse:!0}),vl=J(hee,async(t,n,r)=>{try{let t=TJ(r.docName,n,`lint-fix`);if(t===null)return;let i=ir(t),a=_V(r,ut);if(a.kind===`invalid-summary`){G(n,400,`urn:ok:error:invalid-request`,`Summary must be a string.`,{handler:`lint-fix`});return}let o=a.kind===`anonymous`?`principal-anonymous`:a.writerId,c=a.kind===`anonymous`?`Anonymous`:a.displayName,u=a.kind===`anonymous`?o:a.colorSeed,d=a.kind===`agent`?a.clientName:void 0;if(oC(i)||cC(i)){G(n,400,`urn:ok:error:reserved-doc-name`,`'${i}' is a reserved document name.`,{handler:`lint-fix`});return}let f=FJ(l,i);if(f===null){G(n,404,`urn:ok:error:doc-not-found`,`Document not found.`,{handler:`lint-fix`});return}EJ(z(l,f),l);let p=Qt?.()??zr,{stored:m}=Ci(a.summary),h=await s.getSession(i,o,{displayName:c,colorSeed:u,clientName:d}),g=h.dc.document.getText(`source`).toString(),{cfg:_,before:v,fixed:y}=await Boe({projectDir:T??l,contentDir:l,baseConfig:p,docRelPath:f,source:g}),b=v,x;if(y!==g){try{let t=Jn(d),n=Hn[t]??Wr(u??o);Ze?.setPresence(o,{displayName:c,icon:t,color:n,currentDoc:i,mode:`writing`,ts:Date.now()}),h.dc.document.transact(()=>{aE(h.dc.document,y,`patch`,e.resolveEmbed?{resolveEmbed:e.resolveEmbed,sourcePath:i}:void 0,void 0,rE(h))},h.origin),a.kind!==`anonymous`&&cN(i,o,c,u,void 0,a.kind===`agent`?Si({clientName:a.clientName,clientVersion:a.clientVersion,label:a.label}):a.actor,m)}finally{Ze?.touchMode(o,`idle`)}let t=await mr(i);if(t?.kind===`failure`){_r(n,t.failure,`lint-fix`);return}if(t?.kind===`divergence`){vr(n,`lint-fix`);return}lr(i,`lint-fix`);try{b=await Gi(h.dc.document.getText(`source`).toString(),_,f)}catch(e){x=`Re-lint after fix failed: ${e instanceof Error?e.message:String(e)}`,Y.warn({err:e,handler:`lint-fix`},`post-write re-lint failed; reporting pre-fix diagnostics`),b=v}}let S=b.filter(e=>e.severity===`error`).length,C=b.length-S;q(n,200,It,{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 LF){G(n,400,`urn:ok:error:path-escape`,`Path escape detected.`,{handler:`lint-fix`});return}if(e instanceof HC){UC(n,e,`lint-fix`);return}if(e instanceof JC){XC(n,e,`lint-fix`);return}if(e instanceof hE){G(n,503,`urn:ok:error:too-many-agent-sessions`,`Too many agent sessions.`,{handler:`lint-fix`,cause:e,extraHeaders:{"Retry-After":`10`}});return}Y.error({err:e},`[lint-fix] handler failed`),G(n,500,`urn:ok:error:internal-server-error`,`Failed to fix document.`,{handler:`lint-fix`,cause:e})}},{handler:`lint-fix`,method:`POST`}),xl=`link-preview`,Sl=new PU({cacheDir:an?null:z(T??l,`.ok`,`local`,`link-previews`)}),wl=null,Tl=()=>(wl??=Sl.init(),wl),El=on??TU;async function Dl(e){let t=await El(e);return t.ok?{ok:!0,metadata:await AU({html:new TextDecoder().decode(t.body),requestUrl:e,finalUrl:t.finalUrl,fetch:El})}:{ok:!1,reason:t.reason}}let Ol=()=>{try{return sn?.()===!0}catch{return!1}},kl={"/api/config":Yc,"/api/asset":Ra,"/api/asset-text":Ha,"/api/document":Hi,"/api/documents":Ui,"/api/backlinks":qi,"/api/backlink-counts":Yi,"/api/link-preview":J(zt,async(e,t,n)=>{try{if(!Ol()){Y.debug({outcome:`disabled`},`[link-preview] request outcome`),q(t,200,de,{ok:!1,reason:`disabled`},{handler:xl});return}await Tl();let e=!1,r=await Sl.load(n.url,()=>(e=!0,Dl(n.url)));Sl.persist();let i=r.ok?r:{ok:!1,reason:`blocked`};Y.debug({outcome:e?r.ok?`fetched-ok`:`fallback`:`cache-hit`},`[link-preview] request outcome`),q(t,200,de,i,{handler:xl})}catch(e){G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:xl,cause:e})}},{handler:xl,method:`POST`,preBodyGate:(e,t)=>{let n=LU({origin:e.headers.origin,contentType:e.headers[`content-type`]});return n.ok?!0:(n.reason===`origin`?G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:xl}):G(t,400,`urn:ok:error:invalid-request`,`Content-Type must be application/json.`,{handler:xl}),!1)}}),"/api/forward-links":Xi,"/api/link-graph":Zi,"/api/dead-links":ta,"/api/orphans":Qi,"/api/hubs":$i,"/api/tags":_s,"/api/pages":Ya,"/api/folder-config":Ts,"/api/template":Ps,"/api/template/import":Fs,"/api/templates":Os,"/api/skill":rc,"/api/skill-file":lc,"/api/skills":Xs,"/api/skills/management":$s,"/api/skill/install":uc,"/api/skill/uninstall":dc,"/api/skill/restore":pc,"/api/skill/update":mc,"/api/skill-targets":fc,"/api/search":Fc,"/api/semantic-status":al,"/api/lint/config":cl,"/api/lint/markdownlint-config":ll,"/api/lint/frontmatter-schema":ul,"/api/lint/frontmatter-schemas":dl,"/api/lint":pl,"/api/lint/audit":hl,"/api/lint/fix":vl,"/api/audit":gl,"/api/suggest-links":k,"/api/page-headings":Ka,"/api/create-page":Wa,"/api/create-folder":Ga,"/api/duplicate-path":E,"/api/rename-path":qa,"/api/delete-path":D,"/api/trash/cleanup":Ja,"/api/upload":Xa,"/api/agent-write":ji,"/api/agent-write-md":Ni,"/api/agent-write-batch":Fi,"/api/frontmatter-patch":Ii,"/api/agent-patch":na,"/api/agent-undo":ra,"/api/agent-activity":ia,"/api/agent-burst-diff":sa,"/api/save-version":ha,"/api/history":ya,"/api/rollback":Sa,"/api/metrics/reconciliation":Ca,"/api/metrics/parse-health":wa,"/api/metrics/agent-presence":ja,"/api/metrics/agent-effects":Ma,"/api/metrics/watcher-recent":Pa,"/api/__embed-detect":Fa,"/api/server-info":Ea,"/api/acp/catalog":ka,"/api/share/construct-url":zc,"/api/share/target-status":Vc,"/api/git/branch-info":Bc,"/api/git/checkout":Hc,"/api/share/publish/owners":Wc,"/api/share/publish/name-check":Gc,"/api/share/publish":Kc,"/api/principal":Aa,"/api/rescue":Ua,"/api/workspace":Ia,"/api/sync/status":ns,"/api/sync/trigger":is,"/api/sync/conflicts":os,"/api/sync/conflict-content":cs,"/api/sync/resolve-conflict":ss,"/api/local-op/clone":j,"/api/local-op/ok-init":so,"/api/local-op/auth/login":Do,"/api/local-op/auth/status":Lo,"/api/local-op/auth/pat":Bo,"/api/local-op/auth/gh-login":jo,"/api/local-op/auth/cancel":Po,"/api/local-op/auth/repos":Ho,"/api/local-op/auth/signout":Xo,"/api/local-op/auth/set-identity":ts,"/api/local-op/embeddings/set-key":el,"/api/local-op/embeddings/clear-key":tl,"/api/local-op/embeddings/test":il,"/api/installed-agents":gs,"/api/spawn-cursor":Rc,"/api/handoff":Lc,"/api/install-skill":hs,"/api/skill/install-state":Ic,"/api/seed/plan":us,"/api/seed/apply":ps,"/api/seed/packs":ms,"/api/client-logs":qc};ye&&(kl[`/api/test-reset`]=la,kl[`/api/test-flush-git`]=ca,kl[`/api/test-rescan-backlinks`]=pa,kl[`/api/test-rescan-files`]=ma);let jl=new Set(`/api/upload./api/lint/markdownlint-config./api/lint/frontmatter-schema./api/lint/fix./api/create-page./api/create-folder./api/duplicate-path./api/rename-path./api/delete-path./api/trash/cleanup./api/agent-write./api/agent-write-md./api/agent-write-batch./api/frontmatter-patch./api/agent-patch./api/agent-undo./api/save-version./api/rollback./api/sync/trigger./api/sync/resolve-conflict./api/git/checkout./api/test-reset./api/test-flush-git./api/test-rescan-backlinks./api/test-rescan-files./api/install-skill./api/folder-config./api/template./api/template/import./api/skill./api/skill-file./api/skill/install./api/skill/uninstall./api/skill/restore./api/skill/update./api/skills/management./api/skill-targets./api/seed/apply./api/client-logs`.split(`.`)),Ml=[`/api/local-op/`];return{priority:100,async onRequest({request:e,response:t}){let r=e.url?.split(`?`)[0];if(!r)return;let a=t=>{let n=e.headers[t];if(n!==void 0)return Array.isArray(n)?n.join(`, `):n};yN({ts:Date.now(),url:r,method:e.method??``,ua:a(`user-agent`),origin:a(`origin`),referer:a(`referer`),host:a(`host`),remote:e.socket?.remoteAddress,secChUa:a(`sec-ch-ua`),secChUaMobile:a(`sec-ch-ua-mobile`),secChUaPlatform:a(`sec-ch-ua-platform`),secFetchSite:a(`sec-fetch-site`),secFetchDest:a(`sec-fetch-dest`),secFetchMode:a(`sec-fetch-mode`),secFetchUser:a(`sec-fetch-user`)});let o=e.method??`GET`,s=r;r.startsWith(`/api/history/`)?s=`/api/history/:sha`:r.startsWith(`/api/tags/`)?s=`/api/tags/:name`:kl[r]||(s=`/api/*`);let c=r.startsWith(`/api/`)?OC(e):void 0;if(c!==void 0&&(AC(e,c),typeof t.setHeader==`function`&&t.setHeader(EC,c),typeof t.once==`function`)){let e=Date.now(),n=!1,r=()=>{n||(n=!0,Y.info({event:`api.access`,requestId:c,method:o,route:s,status:t.statusCode,durationMs:Date.now()-e,...t.writableFinished?{}:{aborted:!0}},`${o} ${s} ${t.statusCode}`))};t.once(`finish`,r),t.once(`close`,r)}if(r.startsWith(`/api/`)){let r=e.headers.origin;if(r!==void 0&&!Xk(r,n)){G(t,403,`urn:ok:error:invalid-origin`,`Origin not allowed.`,{handler:`api-origin-gate`});return}if(typeof t.setHeader==`function`&&(r!==void 0&&(t.setHeader(`Access-Control-Allow-Origin`,r),t.setHeader(`Vary`,`Origin`)),t.setHeader(`Access-Control-Allow-Methods`,`GET, POST, PUT, DELETE, OPTIONS`),t.setHeader(`Access-Control-Allow-Headers`,`Content-Type, Authorization, traceparent, tracestate, baggage, ${EC}, ${zn.protocol}, ${zn.runtime}, ${zn.kind}`),t.setHeader(`Access-Control-Expose-Headers`,EC)),e.method===`OPTIONS`){t.writeHead(204),t.end();return}}if(jl.has(r)||Ml.some(e=>r.startsWith(e))){let n=e.socket?.remoteAddress;if(n!==void 0&&!zk(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-mutating-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-mutating-gate`});return}}if(an&&r.startsWith(`/api/`)){let n=e.socket?.remoteAddress;if(n!==void 0&&!zk(n)){G(t,403,`urn:ok:error:loopback-required`,`Loopback required.`,{handler:`api-ephemeral-gate`});return}if(!i(e.headers.host)){G(t,403,`urn:ok:error:host-not-allowed`,`Host header not allowed.`,{handler:`api-ephemeral-gate`});return}}if(!r.startsWith(`/api/`))return;let l=yo.extract(So.active(),e.headers),u=Fo(),d=Date.now();await So.with(l,()=>u.startActiveSpan(`HTTP ${o} ${s}`,{kind:bo.SERVER,attributes:{[as]:o,[rs]:s,[bee]:r,[yee]:`http`,[vee]:e.headers[`user-agent`]??``,"ok.request.id":c}},async n=>{try{let i=kl[r],a=!1;if(i)a=!0,await i(e,t);else if(r.startsWith(`/api/history/`)){let n=decodeURIComponent(r.slice(13));n&&(a=!0,await ba(e,t,n))}else if(r.startsWith(`/api/tags/`)){let n=r.slice(10);n&&(a=!0,await vs(e,t,n))}a||G(t,404,`urn:ok:error:not-found`,`API endpoint not found.`,{handler:`api-dispatch`,detail:`No handler for ${o} ${r}`});let s=t.statusCode;n.setAttribute(ls,s),s>=500&&n.setStatus({code:vo.ERROR,message:`status ${s}`})}catch(e){throw n.recordException(e),n.setStatus({code:vo.ERROR,message:e instanceof Error?e.message:String(e)}),!t.headersSent&&!t.writableEnded&&!t.destroyed&&G(t,500,`urn:ok:error:internal-server-error`,`Internal server error.`,{handler:s,cause:e}),e}finally{n.end();let e=(Date.now()-d)/1e3;Dq().record(e,{[as]:o,[rs]:s,[ls]:t.statusCode})}}))}}}function rY(e){let t=e?.code;return typeof t==`string`?t:void 0}function iY(e){let t;try{t=Rl(e.contentDir,{withFileTypes:!0})}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,e.contentDir);return}for(let n of t)n.isFile()&&gC(n.name,Na)&&e.basenameIndex.add(n.name)}async function aY(e){let t=e.contentDir,n=new Set;async function r(i){let a;try{a=await au(i,{withFileTypes:!0})}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`read-failed`,n,i);return}for(let o of a){let a=L(i,o.name),s=Zk(R(t,a));if(s.startsWith(`..`)||e.contentFilter?.isDirExcluded(s)&&o.isDirectory())continue;let c;try{c=await ru(a)}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`lstat-failed`,n,a);continue}if(c.isSymbolicLink()){let i;try{i=await ou(a)}catch(t){let n=rY(t);n!==`ENOENT`&&e.onSkip?.(`realpath-failed`,n,a);continue}if(!Qk(i,t)){e.onSkip?.(`symlink-escape`,void 0,a);continue}let o;try{o=await su(i)}catch(t){let n=rY(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()&&gC(a,xa)&&!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()&&gC(a,xa)&&!e.contentFilter?.isExcluded(s)&&e.basenameIndex.add(s)}}await r(t)}const oY=O({principalId:A().optional(),tabSessionId:A().optional(),expectedServerInstanceId:A().optional(),expectedBranch:A().optional(),expectedDocLineageEpoch:A().optional(),clientProtocolVersion:P().optional(),clientRuntimeVersion:A().optional(),clientKind:A().optional()}).loose(),sY=[`server-instance-mismatch`,`branch-mismatch`,`rename-redirect`,`doc-deleted`,`doc-lineage-mismatch`];function cY(e){return sY.includes(e)}function lY(e,t){return typeof t!=`string`||t.length===0?e:`${e}:${t}`}function uY(e){if(e.length===0)return{kind:null,payload:void 0};let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t);if(!cY(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 dY=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=lY(e,this.payload)}};function fY(e){if(typeof e!=`string`||e.length===0)return;let t;try{t=JSON.parse(e)}catch{return}let n=oY.safeParse(t);return n.success?n.data:void 0}var pY=class extends Error{constructor(e){super(e),this.name=`AutoStartDisabledError`}};const mY=F(`conflict-storage`);var hY=class{storePath;projectDir;branch;conflicts=[];constructor(e,t=`main`){this.storePath=L(zA(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){mY.warn({path:this.storePath},`[conflicts] unknown schema version — resetting`),this.conflicts=[];return}this.branch=t.branch??this.branch,this.conflicts=t.conflicts??[]}catch(e){mY.warn({err:e},`[conflicts] failed to load conflicts.json — starting empty`),this.conflicts=[]}}save(){try{let e=I(this.storePath);B(e)||Nl(e,{recursive:!0});let t={version:1,branch:this.branch,conflicts:this.conflicts};return Kl(this.storePath,JSON.stringify(t,null,2),`utf-8`),!0}catch(e){return mY.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-BeQ4qN_k.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(!Qk(r,t))throw Error(`[conflicts] file path escapes project directory: ${e}`);Zz(r,t),$o(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`]),mY.info({file:e},`[conflicts] all conflicts resolved — merge commit created`)}catch(t){let n=new Date().toISOString(),r=!1;try{let e=await dS(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){mY.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}),mY.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(!Qk(a,i))throw Error(`[conflicts] file path escapes project directory: ${e.file}`);switch(Zz(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-BeQ4qN_k.mjs`),n=await t(this.projectDir,{credentialArgs:r}).git.raw([`cat-file`,`blob`,e.theirsSha]);Zz(a,i),$o(a,n,`utf-8`);break}case`content`:if(n===void 0)throw Error(`[conflicts] strategy 'content' requires content parameter`);$o(a,n,`utf-8`);break;case`delete`:B(a)&&zo(a);break;default:throw Error(`[conflicts] unknown resolve strategy: ${t}`)}this.removeConflict(e.file)}};function gY(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 _Y(e,t){let n=zA(e);try{Nl(n,{recursive:!0}),Kl(L(n,pe),`${JSON.stringify(t,null,2)}\n`)}catch{}try{let n=os(e);Nl(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`};Kl(n,`${JSON.stringify(r)}\n`,{flag:`a`})}catch{}}const vY=new Map;let yY=!1;function bY(e,t){try{let n=gY(e,t);for(let e of vY.keys())_Y(e,n)}catch{}}function xY(e){vY.set(e,(vY.get(e)??0)+1),yY||(yY=!0,process.on(`uncaughtExceptionMonitor`,bY));let t=!1;return{uninstall:()=>{if(t)return;t=!0;let n=vY.get(e)??0;n<=1?vY.delete(e):vY.set(e,n-1)}}}function SY(e){let t=e.scheduler??m,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 CY(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function wY(e){if(!B(e))return{};let t;try{t=(0,kk.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(!CY(t))return{};let n=t.telemetry;if(!CY(n))return{};let r=n.localSink;return CY(r)?r:{}}function TY(e){return typeof e==`boolean`?e:void 0}function EY(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:void 0}function DY(e){if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}function OY(e){if(CY(e))return EY(e.maxBytes)}function kY(e){if(process.env.OK_DISABLE_LOCAL_SINK===`1`||process.env.OK_DISABLE_LOCAL_SINK===`true`)return null;let t=wY(Ao(`project`,e.projectDir)),n=wY(Ao(`project-local`,e.projectDir));if((TY(n.enabled)??TY(t.enabled)??!0)===!1)return null;let r=OY(n.spans)??OY(t.spans)??52428800,i=OY(n.logs)??OY(t.logs)??26214400,a=DY(n.attributeDenylist)??DY(t.attributeDenylist)??Ra;return{telemetry:{projectDir:e.projectDir,spansMaxBytes:r,attributeDenylist:a},logs:{projectDir:e.projectDir,maxBytes:i}}}var AY;(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})(AY||={});var jY;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(jY||={});const MY=AY.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),NY=e=>{switch(typeof e){case`undefined`:return MY.undefined;case`string`:return MY.string;case`number`:return Number.isNaN(e)?MY.nan:MY.number;case`boolean`:return MY.boolean;case`function`:return MY.function;case`bigint`:return MY.bigint;case`symbol`:return MY.symbol;case`object`:return Array.isArray(e)?MY.array:e===null?MY.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?MY.promise:typeof Map<`u`&&e instanceof Map?MY.map:typeof Set<`u`&&e instanceof Set?MY.set:typeof Date<`u`&&e instanceof Date?MY.date:MY.object;default:return MY.unknown}},X=AY.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 PY=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,AY.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()}};PY.create=e=>new PY(e);const FY=(e,t)=>{let n;switch(e.code){case X.invalid_type:n=e.received===MY.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case X.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,AY.jsonStringifyReplacer)}`;break;case X.unrecognized_keys:n=`Unrecognized key(s) in object: ${AY.joinValues(e.keys,`, `)}`;break;case X.invalid_union:n=`Invalid input`;break;case X.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${AY.joinValues(e.options)}`;break;case X.invalid_enum_value:n=`Invalid enum value. Expected ${AY.joinValues(e.options)}, received '${e.received}'`;break;case X.invalid_arguments:n=`Invalid function arguments`;break;case X.invalid_return_type:n=`Invalid function return type`;break;case X.invalid_date:n=`Invalid date`;break;case X.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:AY.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case X.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case X.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case X.custom:n=`Invalid input`;break;case X.invalid_intersection_types:n=`Intersection results could not be merged`;break;case X.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case X.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,AY.assertNever(e)}return{message:n}};let IY=FY;function LY(){return IY}const RY=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 zY(e,t){let n=LY(),r=RY({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===FY?void 0:FY].filter(e=>!!e)});e.common.issues.push(r)}var BY=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 VY;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 VY;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 VY=Object.freeze({status:`aborted`}),HY=e=>({status:`dirty`,value:e}),UY=e=>({status:`valid`,value:e}),WY=e=>e.status===`aborted`,GY=e=>e.status===`dirty`,KY=e=>e.status===`valid`,qY=e=>typeof Promise<`u`&&e instanceof Promise;var JY;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(JY||={});var YY=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 XY=(e,t)=>{if(KY(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 PY(e.common.issues);return this._error=t,this._error}}};function ZY(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 QY=class{get description(){return this._def.description}_getType(e){return NY(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:NY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new BY,ctx:{common:e.parent.common,data:e.data,parsedType:NY(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(qY(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:NY(e)};return XY(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:NY(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return KY(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=>KY(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:NY(e)},r=this._parse({data:e,path:n.path,parent:n});return XY(n,await(qY(r)?r:Promise.resolve(r)))}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:X.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new eZ({schema:this,typeName:Z.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return tZ.create(this,this._def)}nullable(){return nZ.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return FX.create(this)}promise(){return $X.create(this,this._def)}or(e){return RX.create([this,e],this._def)}and(e){return HX.create(this,e,this._def)}transform(e){return new eZ({...ZY(this._def),schema:this,typeName:Z.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new rZ({...ZY(this._def),innerType:this,defaultValue:t,typeName:Z.ZodDefault})}brand(){return new oZ({typeName:Z.ZodBranded,type:this,...ZY(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new iZ({...ZY(this._def),innerType:this,catchValue:t,typeName:Z.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return sZ.create(this,e)}readonly(){return cZ.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const $Y=/^c[^\s-]{8,}$/i,eX=/^[0-9a-z]+$/,tX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,nX=/^[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,rX=/^[a-z0-9_-]{21}$/i,iX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,aX=/^[-+]?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)?)??$/,oX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let sX;const cX=/^(?:(?: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])$/,lX=/^(?:(?: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])$/,uX=/^(([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]))$/,dX=/^(([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])$/,fX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,pX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,mX=`((\\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])))`,hX=RegExp(`^${mX}$`);function gX(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 _X(e){return RegExp(`^${gX(e)}$`)}function vX(e){let t=`${mX}T${gX(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function yX(e,t){return!!((t===`v4`||!t)&&cX.test(e)||(t===`v6`||!t)&&uX.test(e))}function bX(e,t){if(!iX.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 xX(e,t){return!!((t===`v4`||!t)&&lX.test(e)||(t===`v6`||!t)&&dX.test(e))}var SX=class e extends QY{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==MY.string){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.string,received:t.parsedType}),VY}let t=new BY,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?zY(n,{code:X.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&zY(n,{code:X.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)oX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`email`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)sX||=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`),sX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`emoji`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)nX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`uuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)rX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`nanoid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)$Y.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cuid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)eX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cuid2`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)tX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`ulid`,code:X.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),zY(n,{validation:`url`,code:X.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`regex`,code:X.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?vX(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?hX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?_X(r).test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{code:X.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?aX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`duration`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?yX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`ip`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?bX(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`jwt`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?xX(e.data,r.version)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`cidr`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?fX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`base64`,code:X.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?pX.test(e.data)||(n=this._getOrReturnCtx(e,n),zY(n,{validation:`base64url`,code:X.invalid_string,message:r.message}),t.dirty()):AY.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:X.invalid_string,...JY.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...JY.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...JY.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...JY.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...JY.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...JY.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...JY.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...JY.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...JY.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...JY.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...JY.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...JY.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...JY.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...JY.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,...JY.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,...JY.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...JY.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...JY.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...JY.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...JY.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...JY.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...JY.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...JY.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...JY.errToObj(t)})}nonempty(e){return this.min(1,JY.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}};SX.create=e=>new SX({checks:[],typeName:Z.ZodString,coerce:e?.coerce??!1,...ZY(e)});function CX(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 wX=class e extends QY{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)!==MY.number){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.number,received:t.parsedType}),VY}let t,n=new BY;for(let r of this._def.checks)r.kind===`int`?AY.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),zY(t,{code:X.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?CX(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_finite,message:r.message}),n.dirty()):AY.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,JY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JY.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:JY.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:JY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:JY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:JY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:JY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JY.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:JY.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:JY.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:JY.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`&&AY.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)}};wX.create=e=>new wX({checks:[],typeName:Z.ZodNumber,coerce:e?.coerce||!1,...ZY(e)});var TX=class e extends QY{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)!==MY.bigint)return this._getInvalidInput(e);let t,n=new BY;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),zY(t,{code:X.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),zY(t,{code:X.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):AY.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.bigint,received:t.parsedType}),VY}gte(e,t){return this.setLimit(`min`,e,!0,JY.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,JY.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,JY.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,JY.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:JY.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:JY.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:JY.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:JY.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:JY.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:JY.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}};TX.create=e=>new TX({checks:[],typeName:Z.ZodBigInt,coerce:e?.coerce??!1,...ZY(e)});var EX=class extends QY{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==MY.boolean){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.boolean,received:t.parsedType}),VY}return UY(e.data)}};EX.create=e=>new EX({typeName:Z.ZodBoolean,coerce:e?.coerce||!1,...ZY(e)});var DX=class e extends QY{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==MY.date){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.date,received:t.parsedType}),VY}if(Number.isNaN(e.data.getTime()))return zY(this._getOrReturnCtx(e),{code:X.invalid_date}),VY;let t=new BY,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),zY(n,{code:X.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):AY.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:JY.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:JY.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)}};DX.create=e=>new DX({checks:[],coerce:e?.coerce||!1,typeName:Z.ZodDate,...ZY(e)});var OX=class extends QY{_parse(e){if(this._getType(e)!==MY.symbol){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.symbol,received:t.parsedType}),VY}return UY(e.data)}};OX.create=e=>new OX({typeName:Z.ZodSymbol,...ZY(e)});var kX=class extends QY{_parse(e){if(this._getType(e)!==MY.undefined){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.undefined,received:t.parsedType}),VY}return UY(e.data)}};kX.create=e=>new kX({typeName:Z.ZodUndefined,...ZY(e)});var AX=class extends QY{_parse(e){if(this._getType(e)!==MY.null){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.null,received:t.parsedType}),VY}return UY(e.data)}};AX.create=e=>new AX({typeName:Z.ZodNull,...ZY(e)});var jX=class extends QY{constructor(){super(...arguments),this._any=!0}_parse(e){return UY(e.data)}};jX.create=e=>new jX({typeName:Z.ZodAny,...ZY(e)});var MX=class extends QY{constructor(){super(...arguments),this._unknown=!0}_parse(e){return UY(e.data)}};MX.create=e=>new MX({typeName:Z.ZodUnknown,...ZY(e)});var NX=class extends QY{_parse(e){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.never,received:t.parsedType}),VY}};NX.create=e=>new NX({typeName:Z.ZodNever,...ZY(e)});var PX=class extends QY{_parse(e){if(this._getType(e)!==MY.undefined){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.void,received:t.parsedType}),VY}return UY(e.data)}};PX.create=e=>new PX({typeName:Z.ZodVoid,...ZY(e)});var FX=class e extends QY{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==MY.array)return zY(t,{code:X.invalid_type,expected:MY.array,received:t.parsedType}),VY;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(zY(t,{code:e?X.too_big:X.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(zY(t,{code:X.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(zY(t,{code:X.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new YY(t,e,t.path,n)))).then(e=>BY.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new YY(t,e,t.path,n)));return BY.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:JY.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:JY.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:JY.toString(n)}})}nonempty(e){return this.min(1,e)}};FX.create=(e,t)=>new FX({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Z.ZodArray,...ZY(t)});function IX(e){if(e instanceof LX){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=tZ.create(IX(r))}return new LX({...e._def,shape:()=>t})}else if(e instanceof FX)return new FX({...e._def,type:IX(e.element)});else if(e instanceof tZ)return tZ.create(IX(e.unwrap()));else if(e instanceof nZ)return nZ.create(IX(e.unwrap()));else if(e instanceof UX)return UX.create(e.items.map(e=>IX(e)));else return e}var LX=class e extends QY{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=AY.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==MY.object){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.object,received:t.parsedType}),VY}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof NX&&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 YY(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof NX){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&&(zY(n,{code:X.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new YY(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=>BY.mergeObjectSync(t,e)):BY.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return JY.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:JY.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Z.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of AY.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 AY.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return IX(this)}partial(t){let n={};for(let e of AY.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 AY.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof tZ;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return XX(AY.objectKeys(this.shape))}};LX.create=(e,t)=>new LX({shape:()=>e,unknownKeys:`strip`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)}),LX.strictCreate=(e,t)=>new LX({shape:()=>e,unknownKeys:`strict`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)}),LX.lazycreate=(e,t)=>new LX({shape:e,unknownKeys:`strip`,catchall:NX.create(),typeName:Z.ZodObject,...ZY(t)});var RX=class extends QY{_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 PY(e.ctx.common.issues));return zY(t,{code:X.invalid_union,unionErrors:n}),VY}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 PY(e));return zY(t,{code:X.invalid_union,unionErrors:i}),VY}}get options(){return this._def.options}};RX.create=(e,t)=>new RX({options:e,typeName:Z.ZodUnion,...ZY(t)});const zX=e=>e instanceof JX?zX(e.schema):e instanceof eZ?zX(e.innerType()):e instanceof YX?[e.value]:e instanceof ZX?e.options:e instanceof QX?AY.objectValues(e.enum):e instanceof rZ?zX(e._def.innerType):e instanceof kX?[void 0]:e instanceof AX?[null]:e instanceof tZ?[void 0,...zX(e.unwrap())]:e instanceof nZ?[null,...zX(e.unwrap())]:e instanceof oZ||e instanceof cZ?zX(e.unwrap()):e instanceof iZ?zX(e._def.innerType):[];var BX=class e extends QY{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==MY.object)return zY(t,{code:X.invalid_type,expected:MY.object,received:t.parsedType}),VY;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}):(zY(t,{code:X.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),VY)}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=zX(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:Z.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...ZY(r)})}};function VX(e,t){let n=NY(e),r=NY(t);if(e===t)return{valid:!0,data:e};if(n===MY.object&&r===MY.object){let n=AY.objectKeys(t),r=AY.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=VX(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}else if(n===MY.array&&r===MY.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=VX(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}else if(n===MY.date&&r===MY.date&&+e==+t)return{valid:!0,data:e};else return{valid:!1}}var HX=class extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(WY(e)||WY(r))return VY;let i=VX(e.value,r.value);return i.valid?((GY(e)||GY(r))&&t.dirty(),{status:t.value,value:i.data}):(zY(n,{code:X.invalid_intersection_types}),VY)};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}))}};HX.create=(e,t,n)=>new HX({left:e,right:t,typeName:Z.ZodIntersection,...ZY(n)});var UX=class e extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==MY.array)return zY(n,{code:X.invalid_type,expected:MY.array,received:n.parsedType}),VY;if(n.data.length<this._def.items.length)return zY(n,{code:X.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),VY;!this._def.rest&&n.data.length>this._def.items.length&&(zY(n,{code:X.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new YY(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>BY.mergeArray(t,e)):BY.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};UX.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new UX({items:e,typeName:Z.ZodTuple,rest:null,...ZY(t)})};var WX=class e extends QY{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!==MY.object)return zY(n,{code:X.invalid_type,expected:MY.object,received:n.parsedType}),VY;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new YY(n,e,n.path,e)),value:a._parse(new YY(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?BY.mergeObjectAsync(t,r):BY.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof QY?new e({keyType:t,valueType:n,typeName:Z.ZodRecord,...ZY(r)}):new e({keyType:SX.create(),valueType:t,typeName:Z.ZodRecord,...ZY(n)})}},GX=class extends QY{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!==MY.map)return zY(n,{code:X.invalid_type,expected:MY.map,received:n.parsedType}),VY;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new YY(n,e,n.path,[a,`key`])),value:i._parse(new YY(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 VY;(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 VY;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};GX.create=(e,t,n)=>new GX({valueType:t,keyType:e,typeName:Z.ZodMap,...ZY(n)});var KX=class e extends QY{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==MY.set)return zY(n,{code:X.invalid_type,expected:MY.set,received:n.parsedType}),VY;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(zY(n,{code:X.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(zY(n,{code:X.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=new Set;for(let r of e){if(r.status===`aborted`)return VY;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 YY(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:JY.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:JY.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};KX.create=(e,t)=>new KX({valueType:e,minSize:null,maxSize:null,typeName:Z.ZodSet,...ZY(t)});var qX=class e extends QY{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==MY.function)return zY(t,{code:X.invalid_type,expected:MY.function,received:t.parsedType}),VY;function n(e,n){return RY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LY(),FY].filter(e=>!!e),issueData:{code:X.invalid_arguments,argumentsError:n}})}function r(e,n){return RY({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,LY(),FY].filter(e=>!!e),issueData:{code:X.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof $X){let e=this;return UY(async function(...t){let o=new PY([]),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 UY(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new PY([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new PY([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:UX.create(t).rest(MX.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||UX.create([]).rest(MX.create()),returns:n||MX.create(),typeName:Z.ZodFunction,...ZY(r)})}},JX=class extends QY{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})}};JX.create=(e,t)=>new JX({getter:e,typeName:Z.ZodLazy,...ZY(t)});var YX=class extends QY{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return zY(t,{received:t.data,code:X.invalid_literal,expected:this._def.value}),VY}return{status:`valid`,value:e.data}}get value(){return this._def.value}};YX.create=(e,t)=>new YX({value:e,typeName:Z.ZodLiteral,...ZY(t)});function XX(e,t){return new ZX({values:e,typeName:Z.ZodEnum,...ZY(t)})}var ZX=class e extends QY{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return zY(t,{expected:AY.joinValues(n),received:t.parsedType,code:X.invalid_type}),VY}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return zY(t,{received:t.data,code:X.invalid_enum_value,options:n}),VY}return UY(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})}};ZX.create=XX;var QX=class extends QY{_parse(e){let t=AY.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==MY.string&&n.parsedType!==MY.number){let e=AY.objectValues(t);return zY(n,{expected:AY.joinValues(e),received:n.parsedType,code:X.invalid_type}),VY}if(this._cache||=new Set(AY.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=AY.objectValues(t);return zY(n,{received:n.data,code:X.invalid_enum_value,options:e}),VY}return UY(e.data)}get enum(){return this._def.values}};QX.create=(e,t)=>new QX({values:e,typeName:Z.ZodNativeEnum,...ZY(t)});var $X=class extends QY{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);return t.parsedType!==MY.promise&&t.common.async===!1?(zY(t,{code:X.invalid_type,expected:MY.promise,received:t.parsedType}),VY):UY((t.parsedType===MY.promise?t.data:Promise.resolve(t.data)).then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};$X.create=(e,t)=>new $X({type:e,typeName:Z.ZodPromise,...ZY(t)});var eZ=class extends QY{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Z.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{zY(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 VY;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?VY:r.status===`dirty`||t.value===`dirty`?HY(r.value):r});{if(t.value===`aborted`)return VY;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?VY:r.status===`dirty`||t.value===`dirty`?HY(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`?VY:(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`?VY:(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(!KY(e))return VY;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=>KY(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):VY);AY.assertNever(r)}};eZ.create=(e,t,n)=>new eZ({schema:e,typeName:Z.ZodEffects,effect:t,...ZY(n)}),eZ.createWithPreprocess=(e,t,n)=>new eZ({schema:t,effect:{type:`preprocess`,transform:e},typeName:Z.ZodEffects,...ZY(n)});var tZ=class extends QY{_parse(e){return this._getType(e)===MY.undefined?UY(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};tZ.create=(e,t)=>new tZ({innerType:e,typeName:Z.ZodOptional,...ZY(t)});var nZ=class extends QY{_parse(e){return this._getType(e)===MY.null?UY(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};nZ.create=(e,t)=>new nZ({innerType:e,typeName:Z.ZodNullable,...ZY(t)});var rZ=class extends QY{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===MY.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};rZ.create=(e,t)=>new rZ({innerType:e,typeName:Z.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...ZY(t)});var iZ=class extends QY{_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 qY(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new PY(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new PY(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};iZ.create=(e,t)=>new iZ({innerType:e,typeName:Z.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...ZY(t)});var aZ=class extends QY{_parse(e){if(this._getType(e)!==MY.nan){let t=this._getOrReturnCtx(e);return zY(t,{code:X.invalid_type,expected:MY.nan,received:t.parsedType}),VY}return{status:`valid`,value:e.data}}};aZ.create=e=>new aZ({typeName:Z.ZodNaN,...ZY(e)});var oZ=class extends QY{_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}},sZ=class e extends QY{_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`?VY:e.status===`dirty`?(t.dirty(),HY(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`?VY:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:Z.ZodPipeline})}},cZ=class extends QY{_parse(e){let t=this._def.innerType._parse(e),n=e=>(KY(e)&&(e.value=Object.freeze(e.value)),e);return qY(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};cZ.create=(e,t)=>new cZ({innerType:e,typeName:Z.ZodReadonly,...ZY(t)}),LX.lazycreate;var Z;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(Z||={}),SX.create,wX.create,aZ.create,TX.create,EX.create,DX.create,OX.create,kX.create,AX.create,jX.create,MX.create,NX.create,PX.create,FX.create;const lZ=LX.create;LX.strictCreate,RX.create,BX.create,HX.create,UX.create,WX.create,GX.create,KX.create,qX.create,JX.create,YX.create,ZX.create,QX.create,$X.create,eZ.create,tZ.create,nZ.create,eZ.createWithPreprocess,sZ.create;const uZ=Pa(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);ho.init(e,t),e.def=t,e.type=t.type,e.parse=(t,n)=>Ba(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>wa(e,t,n),e.parseAsync=async(t,n)=>Ea(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>Fa(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)=>ba(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.apply=t=>t(e)}),dZ=Pa(`ZodMiniObject`,(e,t)=>{Ca.init(e,t),uZ.init(e,t),$a(e,`shape`,()=>t.shape)});function fZ(e,t){return new dZ({type:`object`,shape:e??{},...Ma(t)})}function pZ(e){return!!e._zod}function mZ(e){let t=Object.values(e);if(t.length===0)return fZ({});let n=t.every(pZ),r=t.every(e=>!pZ(e));if(n)return fZ(e);if(r)return lZ(e);throw Error(`Mixed Zod versions detected in object shape.`)}function hZ(e,t){return pZ(e)?wa(e,t):e.safeParse(t)}async function gZ(e,t){return pZ(e)?await Fa(e,t):await e.safeParseAsync(t)}function _Z(e){if(!e)return;let t;if(t=pZ(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function vZ(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 mZ(e)}}if(pZ(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 yZ(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 bZ(e){return e.description}function xZ(e){if(pZ(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function SZ(e){if(pZ(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 CZ=`2025-11-25`,wZ=[CZ,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],TZ=`io.modelcontextprotocol/related-task`,EZ=co(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),DZ=k([A(),P().int()]),OZ=A();no({ttl:P().optional(),pollInterval:P().optional()});const kZ=O({ttl:P().optional()}),AZ=O({taskId:A()}),jZ=no({progressToken:DZ.optional(),[TZ]:AZ.optional()}),MZ=O({_meta:jZ.optional()}),NZ=MZ.extend({task:kZ.optional()}),PZ=e=>NZ.safeParse(e).success,FZ=O({method:A(),params:MZ.loose().optional()}),IZ=O({_meta:jZ.optional()}),LZ=O({method:A(),params:IZ.loose().optional()}),RZ=no({_meta:jZ.optional()}),zZ=k([A(),P().int()]),BZ=O({jsonrpc:D(`2.0`),id:zZ,...FZ.shape}).strict(),VZ=e=>BZ.safeParse(e).success,HZ=O({jsonrpc:D(`2.0`),...LZ.shape}).strict(),UZ=e=>HZ.safeParse(e).success,WZ=O({jsonrpc:D(`2.0`),id:zZ,result:RZ}).strict(),GZ=e=>WZ.safeParse(e).success;var KZ;(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`})(KZ||={});const qZ=O({jsonrpc:D(`2.0`),id:zZ.optional(),error:O({code:P().int(),message:A(),data:E().optional()})}).strict(),JZ=e=>qZ.safeParse(e).success,YZ=k([BZ,HZ,WZ,qZ]);k([WZ,qZ]);const XZ=RZ.strict(),ZZ=IZ.extend({requestId:zZ.optional(),reason:A().optional()}),QZ=LZ.extend({method:D(`notifications/cancelled`),params:ZZ}),$Z=O({icons:N(O({src:A(),mimeType:A().optional(),sizes:N(A()).optional(),theme:La([`light`,`dark`]).optional()})).optional()}),eQ=O({name:A(),title:A().optional()}),tQ=eQ.extend({...eQ.shape,...$Z.shape,version:A(),websiteUrl:A().optional(),description:A().optional()}),nQ=oo(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,ao(O({form:ao(O({applyDefaults:M().optional()}),j(A(),E())).optional(),url:EZ.optional()}),j(A(),E()).optional())),rQ=no({list:EZ.optional(),cancel:EZ.optional(),requests:no({sampling:no({createMessage:EZ.optional()}).optional(),elicitation:no({create:EZ.optional()}).optional()}).optional()}),iQ=no({list:EZ.optional(),cancel:EZ.optional(),requests:no({tools:no({call:EZ.optional()}).optional()}).optional()}),aQ=O({experimental:j(A(),EZ).optional(),sampling:O({context:EZ.optional(),tools:EZ.optional()}).optional(),elicitation:nQ.optional(),roots:O({listChanged:M().optional()}).optional(),tasks:rQ.optional(),extensions:j(A(),EZ).optional()}),oQ=MZ.extend({protocolVersion:A(),capabilities:aQ,clientInfo:tQ}),sQ=FZ.extend({method:D(`initialize`),params:oQ}),cQ=e=>sQ.safeParse(e).success,lQ=O({experimental:j(A(),EZ).optional(),logging:EZ.optional(),completions:EZ.optional(),prompts:O({listChanged:M().optional()}).optional(),resources:O({subscribe:M().optional(),listChanged:M().optional()}).optional(),tools:O({listChanged:M().optional()}).optional(),tasks:iQ.optional(),extensions:j(A(),EZ).optional()}),uQ=RZ.extend({protocolVersion:A(),capabilities:lQ,serverInfo:tQ,instructions:A().optional()}),dQ=LZ.extend({method:D(`notifications/initialized`),params:IZ.optional()}),fQ=e=>dQ.safeParse(e).success,pQ=FZ.extend({method:D(`ping`),params:MZ.optional()}),mQ=O({progress:P(),total:Ja(P()),message:Ja(A())}),hQ=O({...IZ.shape,...mQ.shape,progressToken:DZ}),gQ=LZ.extend({method:D(`notifications/progress`),params:hQ}),_Q=MZ.extend({cursor:OZ.optional()}),vQ=FZ.extend({params:_Q.optional()}),yQ=RZ.extend({nextCursor:OZ.optional()}),bQ=La([`working`,`input_required`,`completed`,`failed`,`cancelled`]),xQ=O({taskId:A(),status:bQ,ttl:k([P(),ya()]),createdAt:A(),lastUpdatedAt:A(),pollInterval:Ja(P()),statusMessage:Ja(A())}),SQ=RZ.extend({task:xQ}),CQ=IZ.merge(xQ),wQ=LZ.extend({method:D(`notifications/tasks/status`),params:CQ}),TQ=FZ.extend({method:D(`tasks/get`),params:MZ.extend({taskId:A()})}),EQ=RZ.merge(xQ),DQ=FZ.extend({method:D(`tasks/result`),params:MZ.extend({taskId:A()})});RZ.loose();const OQ=vQ.extend({method:D(`tasks/list`)}),kQ=yQ.extend({tasks:N(xQ)}),AQ=FZ.extend({method:D(`tasks/cancel`),params:MZ.extend({taskId:A()})}),jQ=RZ.merge(xQ),MQ=O({uri:A(),mimeType:Ja(A()),_meta:j(A(),E()).optional()}),NQ=MQ.extend({text:A()}),PQ=A().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),FQ=MQ.extend({blob:PQ}),IQ=La([`user`,`assistant`]),LQ=O({audience:N(IQ).optional(),priority:P().min(0).max(1).optional(),lastModified:go({offset:!0}).optional()}),RQ=O({...eQ.shape,...$Z.shape,uri:A(),description:Ja(A()),mimeType:Ja(A()),size:Ja(P()),annotations:LQ.optional(),_meta:Ja(no({}))}),zQ=O({...eQ.shape,...$Z.shape,uriTemplate:A(),description:Ja(A()),mimeType:Ja(A()),annotations:LQ.optional(),_meta:Ja(no({}))}),BQ=vQ.extend({method:D(`resources/list`)}),VQ=yQ.extend({resources:N(RQ)}),HQ=vQ.extend({method:D(`resources/templates/list`)}),UQ=yQ.extend({resourceTemplates:N(zQ)}),WQ=MZ.extend({uri:A()}),GQ=WQ,KQ=FZ.extend({method:D(`resources/read`),params:GQ}),qQ=RZ.extend({contents:N(k([NQ,FQ]))}),JQ=LZ.extend({method:D(`notifications/resources/list_changed`),params:IZ.optional()}),YQ=WQ,XQ=FZ.extend({method:D(`resources/subscribe`),params:YQ}),ZQ=WQ,QQ=FZ.extend({method:D(`resources/unsubscribe`),params:ZQ}),$Q=IZ.extend({uri:A()}),e$=LZ.extend({method:D(`notifications/resources/updated`),params:$Q}),t$=O({name:A(),description:Ja(A()),required:Ja(M())}),n$=O({...eQ.shape,...$Z.shape,description:Ja(A()),arguments:Ja(N(t$)),_meta:Ja(no({}))}),r$=vQ.extend({method:D(`prompts/list`)}),i$=yQ.extend({prompts:N(n$)}),a$=MZ.extend({name:A(),arguments:j(A(),A()).optional()}),o$=FZ.extend({method:D(`prompts/get`),params:a$}),s$=O({type:D(`text`),text:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),c$=O({type:D(`image`),data:PQ,mimeType:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),l$=O({type:D(`audio`),data:PQ,mimeType:A(),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),u$=O({type:D(`tool_use`),name:A(),id:A(),input:j(A(),E()),_meta:j(A(),E()).optional()}),d$=O({type:D(`resource`),resource:k([NQ,FQ]),annotations:LQ.optional(),_meta:j(A(),E()).optional()}),f$=k([s$,c$,l$,RQ.extend({type:D(`resource_link`)}),d$]),p$=O({role:IQ,content:f$}),m$=RZ.extend({description:A().optional(),messages:N(p$)}),h$=LZ.extend({method:D(`notifications/prompts/list_changed`),params:IZ.optional()}),g$=O({title:A().optional(),readOnlyHint:M().optional(),destructiveHint:M().optional(),idempotentHint:M().optional(),openWorldHint:M().optional()}),_$=O({taskSupport:La([`required`,`optional`,`forbidden`]).optional()}),v$=O({...eQ.shape,...$Z.shape,description:A().optional(),inputSchema:O({type:D(`object`),properties:j(A(),EZ).optional(),required:N(A()).optional()}).catchall(E()),outputSchema:O({type:D(`object`),properties:j(A(),EZ).optional(),required:N(A()).optional()}).catchall(E()).optional(),annotations:g$.optional(),execution:_$.optional(),_meta:j(A(),E()).optional()}),y$=vQ.extend({method:D(`tools/list`)}),b$=yQ.extend({tools:N(v$)}),x$=RZ.extend({content:N(f$).default([]),structuredContent:j(A(),E()).optional(),isError:M().optional()});x$.or(RZ.extend({toolResult:E()}));const S$=NZ.extend({name:A(),arguments:j(A(),E()).optional()}),C$=FZ.extend({method:D(`tools/call`),params:S$}),w$=LZ.extend({method:D(`notifications/tools/list_changed`),params:IZ.optional()});O({autoRefresh:M().default(!0),debounceMs:P().int().nonnegative().default(300)});const T$=La([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),E$=MZ.extend({level:T$}),D$=FZ.extend({method:D(`logging/setLevel`),params:E$}),O$=IZ.extend({level:T$,logger:A().optional(),data:E()}),k$=LZ.extend({method:D(`notifications/message`),params:O$}),A$=O({hints:N(O({name:A().optional()})).optional(),costPriority:P().min(0).max(1).optional(),speedPriority:P().min(0).max(1).optional(),intelligencePriority:P().min(0).max(1).optional()}),j$=O({mode:La([`auto`,`required`,`none`]).optional()}),M$=O({type:D(`tool_result`),toolUseId:A().describe(`The unique identifier for the corresponding tool call.`),content:N(f$).default([]),structuredContent:O({}).loose().optional(),isError:M().optional(),_meta:j(A(),E()).optional()}),N$=Qa(`type`,[s$,c$,l$]),P$=Qa(`type`,[s$,c$,l$,u$,M$]),F$=O({role:IQ,content:k([P$,N(P$)]),_meta:j(A(),E()).optional()}),I$=NZ.extend({messages:N(F$),modelPreferences:A$.optional(),systemPrompt:A().optional(),includeContext:La([`none`,`thisServer`,`allServers`]).optional(),temperature:P().optional(),maxTokens:P().int(),stopSequences:N(A()).optional(),metadata:EZ.optional(),tools:N(v$).optional(),toolChoice:j$.optional()}),L$=FZ.extend({method:D(`sampling/createMessage`),params:I$}),R$=RZ.extend({model:A(),stopReason:Ja(La([`endTurn`,`stopSequence`,`maxTokens`]).or(A())),role:IQ,content:N$}),z$=RZ.extend({model:A(),stopReason:Ja(La([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(A())),role:IQ,content:k([P$,N(P$)])}),B$=O({type:D(`boolean`),title:A().optional(),description:A().optional(),default:M().optional()}),V$=O({type:D(`string`),title:A().optional(),description:A().optional(),minLength:P().optional(),maxLength:P().optional(),format:La([`email`,`uri`,`date`,`date-time`]).optional(),default:A().optional()}),H$=O({type:La([`number`,`integer`]),title:A().optional(),description:A().optional(),minimum:P().optional(),maximum:P().optional(),default:P().optional()}),U$=O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),default:A().optional()}),W$=O({type:D(`string`),title:A().optional(),description:A().optional(),oneOf:N(O({const:A(),title:A()})),default:A().optional()}),G$=k([k([O({type:D(`string`),title:A().optional(),description:A().optional(),enum:N(A()),enumNames:N(A()).optional(),default:A().optional()}),k([U$,W$]),k([O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({type:D(`string`),enum:N(A())}),default:N(A()).optional()}),O({type:D(`array`),title:A().optional(),description:A().optional(),minItems:P().optional(),maxItems:P().optional(),items:O({anyOf:N(O({const:A(),title:A()}))}),default:N(A()).optional()})])]),B$,V$,H$]),K$=k([NZ.extend({mode:D(`form`).optional(),message:A(),requestedSchema:O({type:D(`object`),properties:j(A(),G$),required:N(A()).optional()})}),NZ.extend({mode:D(`url`),message:A(),elicitationId:A(),url:A().url()})]),q$=FZ.extend({method:D(`elicitation/create`),params:K$}),J$=IZ.extend({elicitationId:A()}),Y$=LZ.extend({method:D(`notifications/elicitation/complete`),params:J$}),X$=RZ.extend({action:La([`accept`,`decline`,`cancel`]),content:oo(e=>e===null?void 0:e,j(A(),k([A(),P(),M(),N(A())])).optional())}),Z$=O({type:D(`ref/resource`),uri:A()}),Q$=O({type:D(`ref/prompt`),name:A()}),$$=MZ.extend({ref:k([Q$,Z$]),argument:O({name:A(),value:A()}),context:O({arguments:j(A(),A()).optional()}).optional()}),e1=FZ.extend({method:D(`completion/complete`),params:$$});function t1(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function n1(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const r1=RZ.extend({completion:no({values:N(A()).max(100),total:Ja(P().int()),hasMore:Ja(M())})}),i1=O({uri:A().startsWith(`file://`),name:A().optional(),_meta:j(A(),E()).optional()}),a1=FZ.extend({method:D(`roots/list`),params:MZ.optional()}),o1=RZ.extend({roots:N(i1)}),s1=LZ.extend({method:D(`notifications/roots/list_changed`),params:IZ.optional()});k([pQ,sQ,e1,D$,o$,r$,BQ,HQ,KQ,XQ,QQ,C$,y$,TQ,DQ,OQ,AQ]),k([QZ,gQ,dQ,s1,wQ]),k([XZ,R$,z$,X$,o1,EQ,kQ,SQ]),k([pQ,L$,q$,a1,TQ,DQ,OQ,AQ]),k([QZ,gQ,k$,e$,JQ,w$,h$,wQ,Y$]),k([XZ,uQ,r1,m$,i$,VQ,UQ,qQ,x$,b$,EQ,kQ,SQ]);var c1=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===KZ.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new l1(e.elicitations,n)}return new e(t,n,r)}},l1=class extends c1{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(KZ.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function u1(e){return e===`completed`||e===`failed`||e===`cancelled`}const d1=Symbol(`Let zodToJsonSchema decide on which parser to use`),f1={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`},p1=e=>typeof e==`string`?{...f1,name:e}:{...f1,...e},m1=e=>{let t=p1(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 h1(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function g1(e,t,n,r,i){e[t]=n,h1(e,t,r,i)}const _1=(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 v1(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?_1(t,e.currentPath):t.join(`/`)}}function y1(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==Z.ZodAny&&(n.items=l0(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&g1(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&g1(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(g1(n,`minItems`,e.exactLength.value,e.exactLength.message,t),g1(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function b1(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?g1(n,`minimum`,r.value,r.message,t):g1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),g1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?g1(n,`maximum`,r.value,r.message,t):g1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),g1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:g1(n,`multipleOf`,r.value,r.message,t);break}return n}function x1(){return{type:`boolean`}}function S1(e,t){return l0(e.type._def,t)}const C1=(e,t)=>l0(e.innerType._def,t);function w1(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>w1(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return T1(e,t)}}const T1=(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`:g1(n,`minimum`,r.value,r.message,t);break;case`max`:g1(n,`maximum`,r.value,r.message,t);break}return n};function E1(e,t){return{...l0(e.innerType._def,t),default:e.defaultValue()}}function D1(e,t){return t.effectStrategy===`input`?l0(e.schema._def,t):v1(t)}function O1(e){return{type:`string`,enum:Array.from(e.values)}}const k1=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function A1(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(k1(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 j1(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 M1;const N1={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:()=>(M1===void 0&&(M1=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),M1),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 P1(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:g1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:g1(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`:R1(n,`email`,r.message,t);break;case`format:idn-email`:R1(n,`idn-email`,r.message,t);break;case`pattern:zod`:z1(n,N1.email,r.message,t);break}break;case`url`:R1(n,`uri`,r.message,t);break;case`uuid`:R1(n,`uuid`,r.message,t);break;case`regex`:z1(n,r.regex,r.message,t);break;case`cuid`:z1(n,N1.cuid,r.message,t);break;case`cuid2`:z1(n,N1.cuid2,r.message,t);break;case`startsWith`:z1(n,RegExp(`^${F1(r.value,t)}`),r.message,t);break;case`endsWith`:z1(n,RegExp(`${F1(r.value,t)}$`),r.message,t);break;case`datetime`:R1(n,`date-time`,r.message,t);break;case`date`:R1(n,`date`,r.message,t);break;case`time`:R1(n,`time`,r.message,t);break;case`duration`:R1(n,`duration`,r.message,t);break;case`length`:g1(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),g1(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:z1(n,RegExp(F1(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&R1(n,`ipv4`,r.message,t),r.version!==`v4`&&R1(n,`ipv6`,r.message,t);break;case`base64url`:z1(n,N1.base64url,r.message,t);break;case`jwt`:z1(n,N1.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&z1(n,N1.ipv4Cidr,r.message,t),r.version!==`v4`&&z1(n,N1.ipv6Cidr,r.message,t);break;case`emoji`:z1(n,N1.emoji(),r.message,t);break;case`ulid`:z1(n,N1.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:R1(n,`binary`,r.message,t);break;case`contentEncoding:base64`:g1(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:z1(n,N1.base64,r.message,t);break}break;case`nanoid`:z1(n,N1.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(r)}return n}function F1(e,t){return t.patternStrategy===`escape`?L1(e):e}const I1=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function L1(e){let t=``;for(let n=0;n<e.length;n++)I1.has(e[n])||(t+=`\\`),t+=e[n];return t}function R1(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}}})):g1(e,`format`,t,n,r)}function z1(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:B1(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):g1(e,`pattern`,B1(t,r),n,r)}function B1(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
1229
1229
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
1230
1230
  ]))`;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 V1(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===Z.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:l0(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??v1(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===Z.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=P1(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===Z.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===Z.ZodBranded&&e.keyType._def.type._def.typeName===Z.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=S1(e.keyType._def,t);return{...n,propertyNames:i}}return n}function H1(e,t){return t.mapStrategy===`record`?V1(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[l0(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||v1(t),l0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||v1(t)],minItems:2,maxItems:2}}}function U1(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 W1(e){return e.target===`openAi`?void 0:{not:v1({...e,currentPath:[...e.currentPath,`not`]})}}function G1(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const K1={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function q1(e,t){if(t.target===`openApi3`)return J1(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in K1&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=K1[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return J1(e,t)}const J1=(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 Y1(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:K1[e.innerType._def.typeName],nullable:!0}:{type:[K1[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=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 X1(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`,h1(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?g1(n,`minimum`,r.value,r.message,t):g1(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),g1(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?g1(n,`maximum`,r.value,r.message,t):g1(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),g1(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:g1(n,`multipleOf`,r.value,r.message,t);break}return n}function Z1(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=$1(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=Q1(e,t);return o!==void 0&&(r.additionalProperties=o),r}function Q1(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 $1(e){try{return e.isOptional()}catch{return!0}}const e0=(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:v1(t)},n]}:v1(t)},t0=(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 n0(e,t){return l0(e.type._def,t)}function r0(e,t){let n={type:`array`,uniqueItems:!0,items:l0(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&g1(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&g1(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function i0(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 a0(e){return{not:v1(e)}}function o0(e){return v1(e)}const s0=(e,t)=>l0(e.innerType._def,t),c0=(e,t,n)=>{switch(t){case Z.ZodString:return P1(e,n);case Z.ZodNumber:return X1(e,n);case Z.ZodObject:return Z1(e,n);case Z.ZodBigInt:return b1(e,n);case Z.ZodBoolean:return x1();case Z.ZodDate:return w1(e,n);case Z.ZodUndefined:return a0(n);case Z.ZodNull:return G1(n);case Z.ZodArray:return y1(e,n);case Z.ZodUnion:case Z.ZodDiscriminatedUnion:return q1(e,n);case Z.ZodIntersection:return A1(e,n);case Z.ZodTuple:return i0(e,n);case Z.ZodRecord:return V1(e,n);case Z.ZodLiteral:return j1(e,n);case Z.ZodEnum:return O1(e);case Z.ZodNativeEnum:return U1(e);case Z.ZodNullable:return Y1(e,n);case Z.ZodOptional:return e0(e,n);case Z.ZodMap:return H1(e,n);case Z.ZodSet:return r0(e,n);case Z.ZodLazy:return()=>e.getter()._def;case Z.ZodPromise:return n0(e,n);case Z.ZodNaN:case Z.ZodNever:return W1(n);case Z.ZodEffects:return D1(e,n);case Z.ZodAny:return v1(n);case Z.ZodUnknown:return o0(n);case Z.ZodDefault:return E1(e,n);case Z.ZodBranded:return S1(e,n);case Z.ZodReadonly:return s0(e,n);case Z.ZodCatch:return C1(e,n);case Z.ZodPipeline:return t0(e,n);case Z.ZodFunction:case Z.ZodVoid:case Z.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!==d1)return i}if(r&&!n){let e=u0(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=c0(e,e.typeName,t),o=typeof a==`function`?l0(a(),t):a;if(o&&d0(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const u0=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:_1(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`),v1(t)):t.$refStrategy===`seen`?v1(t):void 0}},d0=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),f0=(e,t)=>{let n=m1(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)??v1(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)??v1(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 p0(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function m0(e,t){return pZ(e)?qa(e,{target:p0(t?.target),io:t?.pipeStrategy??`input`}):f0(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function h0(e){let t=_Z(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=SZ(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function g0(e,t){let n=hZ(e,t);if(!n.success)throw n.error;return n.data}var _0=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(QZ,e=>{this._oncancel(e)}),this.setNotificationHandler(gQ,e=>{this._onprogress(e)}),this.setRequestHandler(pQ,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(TQ,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new c1(KZ.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(DQ,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 c1(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 c1(KZ.InvalidParams,`Task not found: ${r}`);if(!u1(i.status))return await this._waitForTaskUpdate(r,t.signal),await n();if(u1(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r),{...e,_meta:{...e._meta,[TZ]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(OQ,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 c1(KZ.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(AQ,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new c1(KZ.InvalidParams,`Task not found: ${e.params.taskId}`);if(u1(n.status))throw new c1(KZ.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 c1(KZ.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof c1?e:new c1(KZ.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),c1.fromError(KZ.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),GZ(e)||JZ(e)?this._onresponse(e):VZ(e)?this._onrequest(e,t):UZ(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=c1.fromError(KZ.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?.[TZ]?.taskId;if(n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:KZ.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=PZ(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 c1(KZ.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:KZ.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),GZ(e)?n(e):n(new c1(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(GZ(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),GZ(e)?r(e):r(c1.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 c1?e:new c1(KZ.InternalError,String(e))}}return}let i;try{let r=await this.request(e,SQ,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new c1(KZ.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},u1(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new c1(KZ.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new c1(KZ.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 c1?e:new c1(KZ.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||{},[TZ]: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 c1?e:new c1(KZ.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=hZ(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(c1.fromError(KZ.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},EQ,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},kQ,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},jQ,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||{},[TZ]: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||{},[TZ]: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||{},[TZ]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=h0(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=g0(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=h0(e);this._notificationHandlers.set(n,n=>{let r=g0(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`&&VZ(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new c1(KZ.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 c1(KZ.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new c1(KZ.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 c1(KZ.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=wQ.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),u1(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 c1(KZ.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(u1(a.status))throw new c1(KZ.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=wQ.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),u1(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function v0(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function y0(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 b0=t(Tt(),1),x0=t(qe(),1);function S0(){let e=new b0.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,x0.default)(e),e}var C0=class{constructor(e){this._ajv=e??S0()}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)}}},w0=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},R$,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},X$,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 T0(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 E0(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 D0=class extends _0{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(T$.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 C0,this.setRequestHandler(sQ,e=>this._oninitialize(e)),this.setNotificationHandler(dQ,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(D$,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=T$.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new w0(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=y0(this._capabilities,e)}setRequestHandler(e,t){let n=_Z(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r;if(pZ(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=hZ(C$,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new c1(KZ.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=hZ(SQ,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new c1(KZ.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=hZ(x$,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new c1(KZ.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){E0(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&T0(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:wZ.includes(t)?t:CZ,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`},XZ)}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},z$,t):this.request({method:`sampling/createMessage`,params:e},R$,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},X$,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},X$,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new c1(KZ.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof c1?e:new c1(KZ.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this.request({method:`roots/list`,params:e},o1,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}};const O0=Symbol.for(`mcp.completable`);function k0(e){return!!e&&typeof e==`object`&&O0 in e}function A0(e){return e[O0]?.complete}var j0;(function(e){e.Completable=`McpCompletable`})(j0||={});const M0=/^[A-Za-z0-9._-]{1,128}$/;function N0(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`),!M0.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 P0(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 F0(e){let t=N0(e);return P0(e,t.warnings),t.isValid}var I0=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)}},L0=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 D0(e,t)}get experimental(){return this._experimental||={tasks:new I0(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(W0(y$)),this.server.assertCanSetRequestHandler(W0(C$)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(y$,()=>({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=vZ(t.inputSchema);return e?m0(e,{strictUnions:!0,pipeStrategy:`input`}):R0})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=vZ(t.outputSchema);e&&(n.outputSchema=m0(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(C$,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new c1(KZ.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new c1(KZ.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 c1(KZ.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new c1(KZ.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 c1&&e.code===KZ.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 gZ(vZ(e.inputSchema)??e.inputSchema,t);if(!r.success){let e=yZ(`error`in r?r.error:`Unknown error`);throw new c1(KZ.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 c1(KZ.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await gZ(vZ(e.outputSchema),t.structuredContent);if(!r.success){let e=yZ(`error`in r?r.error:`Unknown error`);throw new c1(KZ.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 c1(KZ.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(W0(e1)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(e1,async e=>{switch(e.params.ref.type){case`ref/prompt`:return t1(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return n1(e),this.handleResourceCompletion(e,e.params.ref);default:throw new c1(KZ.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new c1(KZ.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new c1(KZ.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return K0;let r=_Z(n.argsSchema)?.[e.params.argument.name];if(!k0(r))return K0;let i=A0(r);return i?G0(await i(e.params.argument.value,e.params.context)):K0}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 K0;throw new c1(KZ.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?G0(await r(e.params.argument.value,e.params.context)):K0}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(W0(BQ)),this.server.assertCanSetRequestHandler(W0(HQ)),this.server.assertCanSetRequestHandler(W0(KQ)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(BQ,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(HQ,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(KQ,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new c1(KZ.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 c1(KZ.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(W0(r$)),this.server.assertCanSetRequestHandler(W0(o$)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(r$,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?U0(t.argsSchema):void 0}))})),this.server.setRequestHandler(o$,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new c1(KZ.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new c1(KZ.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await gZ(vZ(n.argsSchema),e.params.arguments);if(!r.success){let t=yZ(`error`in r?r.error:`Unknown error`);throw new c1(KZ.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:mZ(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=mZ(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=>k0(e instanceof Wa?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){F0(e);let l={title:t,description:n,inputSchema:H0(r),outputSchema:H0(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`&&F0(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=mZ(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=mZ(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(V0(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!V0(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 R0={type:`object`,properties:{}};function z0(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function B0(e){return`_def`in e||`_zod`in e||z0(e)}function V0(e){return typeof e!=`object`||!e||B0(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(z0)}function H0(e){if(e){if(V0(e))return mZ(e);if(!B0(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function U0(e){let t=_Z(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:bZ(t),required:!xZ(t)})):[]}function W0(e){let t=_Z(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=SZ(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function G0(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const K0={completion:{values:[],hasMore:!1}};var q0=class extends Error{constructor(e,t){super(e,t),this.name=`RequestError`}},J0=e=>e instanceof q0?e:new q0(e.message,{cause:e}),Y0=global.Request,X0=class extends Y0{constructor(e,t){typeof e==`object`&&e2 in e&&(e=e[e2]()),t?.body?.getReader!==void 0&&(t.duplex??=`half`),super(e,t)}},Z0=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)},Q0=Symbol(`wrapBodyStream`),$0=(e,t,n,r,i)=>{let a={method:e,headers:n,signal:i.signal};if(e===`TRACE`){a.method=`GET`;let e=new X0(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[Q0]){let e;a.body=new ReadableStream({async pull(t){try{e||=mu.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=mu.toWeb(r);return new X0(t,a)},e2=Symbol(`getRequestCache`),t2=Symbol(`requestCache`),n2=Symbol(`incomingKey`),r2=Symbol(`urlKey`),i2=Symbol(`headersKey`),a2=Symbol(`abortControllerKey`),o2={get method(){return this[n2].method||`GET`},get url(){return this[r2]},get headers(){return this[i2]||=Z0(this[n2])},[Symbol(`getAbortController`)](){return this[e2](),this[a2]},[e2](){return this[a2]||=new AbortController,this[t2]||=$0(this.method,this[r2],this.headers,this[n2],this[a2])}};[`body`,`bodyUsed`,`cache`,`credentials`,`destination`,`integrity`,`mode`,`redirect`,`referrer`,`referrerPolicy`,`signal`,`keepalive`].forEach(e=>{Object.defineProperty(o2,e,{get(){return this[e2]()[e]}})}),[`arrayBuffer`,`blob`,`clone`,`formData`,`json`,`text`].forEach(e=>{Object.defineProperty(o2,e,{value:function(){return this[e2]()[e]()}})}),Object.defineProperty(o2,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[t2]},{...t,depth:e==null?null:e-1})}`}}),Object.setPrototypeOf(o2,X0.prototype);var s2=(e,t)=>{let n=Object.create(o2);n[n2]=e;let r=e.url||``;if(r[0]!==`/`&&(r.startsWith(`http://`)||r.startsWith(`https://`))){if(e instanceof yu)throw new q0(`Absolute URL for :path is not allowed in HTTP/2`);try{n[r2]=new URL(r).href}catch(e){throw new q0(`Invalid absolute URL`,{cause:e})}return n}let i=(e instanceof yu?e.authority:e.headers.host)||t;if(!i)throw new q0(`Missing host header`);let a;if(e instanceof yu){if(a=e.scheme,!(a===`http`||a===`https`))throw new q0(`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 q0(`Invalid host header`);return n[r2]=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 p2(e){return Promise.race([e,Promise.resolve().then(()=>Promise.resolve(void 0))])}function m2(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 h2(e,t){if(e.locked)throw TypeError(`ReadableStream is locked.`);return t.destroyed?void 0:m2(e.getReader(),t)}var g2=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},_2=`x-hono-already-sent`;global.crypto===void 0&&(global.crypto=Dee);var v2=Symbol(`outgoingEnded`),y2=Symbol(`incomingDraining`),b2=500,x2=64*1024*1024,S2=e=>{let t=e;if(e.destroyed||t[y2])return;if(t[y2]=!0,e instanceof yu){try{e.stream?.close?.(Lee.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,b2);a.unref?.();let o=e=>{n+=e.length,n>x2&&i()};e.on(`data`,o),e.on(`end`,r),e.on(`error`,r),e.resume()},C2=()=>new Response(null,{status:400}),w2=e=>new Response(null,{status:e instanceof Error&&(e.name===`TimeoutError`||e.constructor.name===`TimeoutError`)?504:500}),T2=(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))},E2=e=>{`flushHeaders`in e&&e.writable&&e.flushHeaders()},D2=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=g2(i);else if(Array.isArray(i)){let e=new Headers(i);a=e.has(`content-length`),i=g2(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())):(E2(t),await h2(r,t)?.catch(e=>T2(e,t))),t[v2]?.()},O2=e=>typeof e.then==`function`,k2=async(e,t,n={})=>{if(O2(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(w2);if(u2 in e)return D2(e,t);let r=g2(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 p2(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&&E2(t),await m2(n,t,o))}else r[_2]||(t.writeHead(e.status,r),t.end());t[v2]?.()},A2=(e,t={})=>{let n=t.autoCleanupIncoming??!0;return t.overrideGlobalObjects!==!1&&global.Request!==X0&&(Object.defineProperty(global,`Request`,{value:X0}),Object.defineProperty(global,`Response`,{value:f2})),async(r,i)=>{let a,o;try{o=s2(r,t.hostname);let s=!n||r.method===`GET`||r.method===`HEAD`;if(s||(r[Q0]=!0,r.on(`end`,()=>{s=!0}),r instanceof yu&&(i[v2]=()=>{s||setTimeout(()=>{s||setTimeout(()=>{S2(r)})})}),i.on(`finish`,()=>{s||S2(r)})),i.on(`close`,()=>{o[a2]&&(r.errored?o[a2].abort(r.errored.toString()):i.writableFinished||o[a2].abort(`Client connection prematurely closed.`)),s||setTimeout(()=>{s||setTimeout(()=>{S2(r)})})}),a=e(o,{incoming:r,outgoing:i}),u2 in a)return D2(a,i)}catch(e){if(a)return T2(e,i);if(t.errorHandler){if(a=await t.errorHandler(o?e:J0(e)),!a)return}else a=o?w2(e):C2()}try{return await k2(a,i,t)}catch(e){return T2(e,i)}}},j2=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
1231
1231
  `;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=>YZ.parse(e)):[YZ.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(cQ);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(VZ)){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=>cQ(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)VZ(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)VZ(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;VZ(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&&!wZ.includes(t))return this.onerror?.(Error(`Bad Request: Unsupported protocol version: ${t} (supported versions: ${wZ.join(`, `)})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${t} (supported versions: ${wZ.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((GZ(e)||JZ(e))&&(n=e.id),n===void 0){if(GZ(e)||JZ(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(GZ(e)||JZ(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)}}}},M2=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new j2(e),this._requestListener=A2(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 A2(async e=>this._webStandardTransport.handleRequest(e,{authInfo:r,parsedBody:n}),{overrideGlobalObjects:!1})(e,t)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}};const N2=`x-ok-connection-id`;function P2(e,t){let n=Array.from(e??``).map(e=>{let t=e.charCodeAt(0);return t<=31||t===127?` `:e}).join(``).replace(/\s+/g,` `).trim();return n?n.slice(0,128):t}function F2(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||!Sse(e.inputSchema))return n.call(this,e,t,r);let i=await e.inputSchema.safeParseAsync(t);if(i.success)return i.data;let a=eo(i.error);throw new c1(KZ.InvalidParams,`Input validation error: Invalid arguments for tool ${r}:\n${a}`)},t.__prettyZodErrorsInstalled=!0}function Sse(e){return typeof e!=`object`||!e?!1:typeof e.safeParseAsync==`function`}const I2=2e3,L2=2e3,Cse=[/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 R2(e){return Cse.some(t=>t.test(e))}function wse(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 bl(e)?e:null}catch{return null}}function Tse(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&&bl(a)?a:null}function Ese(e){let t=[];for(let n of e.split(`
@@ -3268,6 +3268,6 @@ native-divergence-injected
3268
3268
  `).split(`
3269
3269
  `),n=[],r=!1,i=``;for(let e of t){let t=/^\s{0,3}([`~]{3,})/.exec(e);if(t){r?RegExp(`^\\s{0,3}${i[0]==="`"?"`":`~`}{${i.length},}\\s*$`).test(e)&&(r=!1,i=``):(r=!0,i=t[1]);continue}if(r)continue;let a=J_e(e);for(y9.lastIndex=0;;){let e=y9.exec(a);if(e===null)break;let t=e[2];t&&n.push(t)}}return n}var x9=class{contentDir;contentFilter;projectDir;state=b9();fileMeta=new Map;initChain=Promise.resolve();closed=!1;constructor(e){this.contentDir=e.contentDir,this.contentFilter=e.contentFilter,this.projectDir=e.projectDir}snapshotPath(){return this.projectDir?z(zA(this.projectDir),`cache`,`tags.json`):null}enqueue(e){let t=this.initChain.then(e);return this.initChain=t.then(()=>void 0,e=>{v9.warn({err:e},`queued tag-index task failed (chain cleared for next task)`)}),t}close(){return this.closed=!0,this.initChain}updateDocumentFromMarkdown(e,t){if(!fC(e))try{let{frontmatter:n,body:r}=ea(t),i=Ze(n?Ft(n):``),a=Y_e(r),o=new Set([...i,...a]),s=new Set;for(let e of o)for(let t of Ii(e))s.add(t);this.applyDocSnapshot(e,o,s)}catch(t){v9.warn({docName:e,err:t},`Failed to scan ${e} for tag extraction`),this.deleteDocument(e)}}deleteDocument(e){if(fC(e))return;let t=this.state.byDoc.get(e);if(t){for(let n of t){let t=this.state.byTag.get(n);t&&(t.delete(e),t.size===0&&this.state.byTag.delete(n))}this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)}}renameDocument(e,t,n){this.deleteDocument(e),this.updateDocumentFromMarkdown(t,n)}getDocsForTag(e){let t=this.state.byTag.get(e);return t?[...t].sort((e,t)=>e.localeCompare(t)):[]}getDocsForTagWithMatches(e){let t=this.state.byTag.get(e);if(!t)return[];let n=[];for(let r of t){let t=this.state.byDocLiteral.get(r);if(!t)continue;let i=ri(t,e);n.push({docName:r,matchingTags:[...i].sort((e,t)=>e.localeCompare(t))})}return n.sort((e,t)=>e.docName.localeCompare(t.docName))}getAllTags(){let e=[...this.state.byTag.entries()],t=e.map(([e])=>e),n=new Set;for(let e of t){let t=e.indexOf(`/`);t>0&&n.add(e.slice(0,t));let r=t;for(;r>0;)n.add(e.slice(0,r)),r=e.indexOf(`/`,r+1)}return e.map(([e,t])=>({name:e,count:t.size,isLeaf:!n.has(e)})).sort((e,t)=>e.name.localeCompare(t.name))}init(){return this.enqueue(()=>yB(`tag`,`full`,()=>this.initOnce()))}async initOnce(){if(this.closed||(this.state=b9(),this.fileMeta=new Map,!B(this.contentDir)))return;let e=await this.listDocsWithPaths();for(let t=0;t<e.length;t+=50){let n=e.slice(t,t+50),r=await Promise.all(n.map(async({docName:e,filePath:t})=>{try{let[n,r]=await Promise.all([su(t),iu(t,`utf-8`)]);return{docName:e,markdown:r,mtimeMs:n.mtimeMs,size:n.size}}catch(t){return v9.warn({docName:e,err:t},`Failed to read ${e} during init`),null}}));for(let e of r)if(e)try{this.updateDocumentFromMarkdown(e.docName,e.markdown),this.fileMeta.set(e.docName,{mtimeMs:e.mtimeMs,size:e.size})}catch(t){v9.warn({docName:e.docName,err:t},`Failed to index ${e.docName} during init`)}}}loadFromDisk(){return this.enqueue(()=>this.loadOnce())}async loadOnce(){if(this.closed)return!1;let e=this.snapshotPath();if(!e||!B(e))return!1;let t;try{t=JSON.parse(await iu(e,`utf-8`))}catch(e){return v9.warn({err:e},`Failed to load tag snapshot; falling back to full rebuild`),!1}if(!q_e(t))return v9.warn({},`Tag snapshot failed validation; falling back to full rebuild`),!1;this.state=b9(),this.fileMeta=new Map(Object.entries(t.files));for(let[e,n]of Object.entries(t.docs)){if(fC(e))continue;let t=new Set(n),r=new Set;for(let e of t)for(let t of Ii(e))r.add(t);this.applyDocSnapshot(e,t,r)}return!0}saveToDisk(){return this.enqueue(()=>this.saveOnce())}async saveOnce(){if(this.closed)return;let e=this.snapshotPath();if(!e)return;let t={version:1,docs:Object.fromEntries([...this.state.byDocLiteral.entries()].map(([e,t])=>[e,[...t].sort((e,t)=>e.localeCompare(t))])),files:Object.fromEntries(this.fileMeta)};await Io(I(e),{recursive:!0}),await No(e,JSON.stringify(t,null,2),`utf-8`)}reconcileWithDisk(){return this.enqueue(()=>yB(`tag`,`reconcile`,()=>this.reconcileOnce(),e=>({"index.added":e.added,"index.updated":e.updated,"index.deleted":e.deleted})))}async reconcileOnce(){if(this.closed||!B(this.contentDir))return{added:0,updated:0,deleted:0};let e=await this.listDocsWithPaths(),t=new Set(e.map(e=>e.docName)),n=new Map,r=0,i=0,a=[],o=await Promise.allSettled(e.map(async({docName:e,filePath:t})=>{let n=await su(t);return{docName:e,filePath:t,meta:{mtimeMs:n.mtimeMs,size:n.size}}}));for(let e of o){if(e.status===`rejected`)continue;let{docName:t,filePath:r,meta:i}=e.value,o=this.fileMeta.get(t);if(o!==void 0&&o.mtimeMs===i.mtimeMs&&o.size===i.size){n.set(t,i);continue}a.push({docName:t,filePath:r,meta:i,isNew:o===void 0})}for(let e=0;e<a.length;e+=50){let t=a.slice(e,e+50),o=await Promise.allSettled(t.map(async({docName:e,meta:t,isNew:n,filePath:r})=>({docName:e,meta:t,isNew:n,markdown:await iu(r,`utf-8`)})));for(let e of o){if(e.status===`rejected`){v9.warn({err:e.reason},`Failed to reconcile file`);continue}let{docName:t,meta:a,isNew:o,markdown:s}=e.value;this.updateDocumentFromMarkdown(t,s),n.set(t,a),o?r++:i++}}let s=0,c=new Set([...this.fileMeta.keys(),...this.state.byDoc.keys()]);for(let e of c)t.has(e)||(this.deleteDocument(e),s++);return this.fileMeta=n,{added:r,updated:i,deleted:s}}applyDocSnapshot(e,t,n){let r=this.state.byDoc.get(e)??new Set;for(let t of r){if(n.has(t))continue;let r=this.state.byTag.get(t);r&&(r.delete(e),r.size===0&&this.state.byTag.delete(t))}for(let t of n){let n=this.state.byTag.get(t);n||(n=new Set,this.state.byTag.set(t,n)),n.add(e)}n.size===0?(this.state.byDoc.delete(e),this.state.byDocLiteral.delete(e)):(this.state.byDoc.set(e,n),this.state.byDocLiteral.set(e,t))}async listDocsWithPaths(){let e=[];await this.walkContentDir(this.contentDir,e),e.sort((e,t)=>e.docName===t.docName?t.filePath.localeCompare(e.filePath):e.docName.localeCompare(t.docName));let t=new Set;return e.filter(({docName:e})=>t.has(e)?!1:(t.add(e),!0))}async walkContentDir(e,t){let n;try{n=await au(e,{withFileTypes:!0})}catch(t){v9.warn({dir:e,err:t},`Failed to read directory ${e}`);return}for(let r of n){let n=L(e,r.name);if(r.isDirectory()){let e=Zk(R(this.contentDir,n));if(this.contentFilter&&e&&this.contentFilter.isDirExcluded(e))continue;await this.walkContentDir(n,t);continue}if(!r.isFile()||!hC(r.name))continue;let i=Zk(R(this.contentDir,n));this.contentFilter?.isExcluded(i)||t.push({docName:_C(i),filePath:n})}}};let S9=!1;function C9(){if(S9)return;let e=Bee;if(typeof e.getCACertificates!=`function`||typeof e.setDefaultCACertificates!=`function`){S9=!0;return}try{e.setDefaultCACertificates([...e.getCACertificates(`default`),...e.getCACertificates(`system`)]),S9=!0}catch(e){F(`trust-system-ca`).warn({err:e},`system CA setup failed; falling back to the bundled CA set`)}}const X_e=(()=>{let e=Object.freeze({origin:`park-snapshot`,paired:!0});return Object.freeze({source:`local`,skipStoreHooks:!1,context:e})})();function Z_e(e){return[`-c`,`credential.helper=!${(e&&e.length>0?e:[`open-knowledge`]).map(O8).join(` `)} auth git-credential`]}function Q_e(e,t,n,r){let i=new Map;if(!n)return i;let a;try{a=hl(`git`,[`-c`,`core.quotePath=false`,`log`,`${n}..${r}`,`--no-merges`,`--name-only`,`--format=C%x00%an%x00%ae`],OP({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(`
3270
3270
  `)){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(!eA(a,t))continue;let s=LV(a,t);i.has(s)||B(a)&&i.set(s,o)}return i}function w9(e){C9();let{contentDir:t,projectDir:n=t,quiet:r=!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 g7,S=()=>x.getActiveBranch(),C=e=>x.getReconciledBase(e),w=(e,t)=>x.setReconciledBase(e,t),ee=e=>x.deleteReconciledBase(e),te=e=>x.switchReconciledBaseScope(e),ne=e=>x.setBatchInProgress(e),re=()=>x.isBatchInProgress();function ie(){let e=Do({absPath:Ao(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});if(!e.valid){let t=uo(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 ae(){let e=Do({absPath:Ao(`project-local`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project-local config`)}),t=Ua(e.value.autoSync);if(t!==null)return{mode:t,source:`config`};e.valid||b.warn({},`[config] project-local autoSync.enabled unavailable (config invalid) — falling back to the committed project default`);let r=Do({absPath:Ao(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config`)});return r.valid||b.warn({},`[config] committed autoSync.default unavailable (project config invalid) — defaulting to disabled`),{mode:Aa(r.value.autoSync?.default)??`off`,source:`committed-default`}}function oe(){let e=Do({absPath:Ao(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for linter`)}).value.contentRules;return e?ut(e):zr}function se(){return Do({absPath:Ao(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for link validation`)}).value.validation?.links??`warning`}function ce(){return gP(n,{configHomedirOverride:u,onWarn:e=>b.warn({message:e},`[config] could not read project-local config`)})}function le(){let e=Do({absPath:Ao(`project-local`,n,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 ue(e){return`${YN(e.baseUrl)}|${e.model}|${e.dimensions??`auto`}`}function de(e){let t;if(e===`__config__/project`||e===`__local__/project`){let n=ae();t=n.mode,_t?.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=ce();Fe.applyConfig({enabled:n.enabled,providerFingerprint:ue(n)}),e===`__config__/project`&&ke?.signal(`lint-config`),b.info({docName:e,autoSyncMode:t,semanticEnabled:n.enabled},`[config] applied persisted config to in-process consumers`)}ts();let fe=fu(),pe=zA(n),me=new sd({localDir:pe,log:F(`acp-registry`)}),he=new $u(pe,F(`acp-permissions`));if(Ds(pe,{port:e.port??0,worktreeRoot:n,kind:e.lockKind??`interactive`,capabilities:[`http`,`ws`]}),!_)try{i9({lockDir:pe,shadowRepoDir:ku(n)})}catch(e){throw vs(pe),e}let ge=wi(),_e=(e,t)=>ge.resolveEmbed(e,t),ve=(e,n)=>{let r=ge.resolveEmbed(e,n);if(!r&&e.includes(`/`)&&(r=e.replace(/^\.?\//,``)),!r)return null;let i=z(t,r);if(!Qk(i,z(t)))return null;try{let e=Wl(i);return e.isFile()?e.size:null}catch{return null}},ye,be,xe,Se,Ce,we,Te,Ee,De,Oe,ke=null,Ae=null,je=null,Me=null,Ne=null,Pe=ce(),Fe=new DP({loadEmbedder:e.embedderLoader??(()=>{let t=ce();return tP({keyStore:e.embeddingsKeyStore??null,projectDir:n,config:{baseUrl:t.baseUrl,model:t.model,dimensions:t.dimensions}})}),cacheDir:L(zA(n),`embeddings`),enabled:Pe.enabled,providerFingerprint:ue(Pe)}),Ie=null,Le=new Set,Re=!1,ze=[],Be,Ve,He,Ue=new Promise((e,t)=>{Ve=e,He=t});function We(e){ke?.signal(e)}let Ge=null;function Ke(){Ge!==null&&clearTimeout(Ge),Ge=setTimeout(()=>{Ge=null,be.saveToDisk().catch(e=>{F(`backlinks`).warn({err:e},`Failed to persist debounced cache`)}),xe.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist debounced tag snapshot`)})},2e3)}let qe=null,Je=!1,Ye=()=>{try{Y7(n,Xe.entries())}catch(e){b.warn({err:e},`[removed-docs-journal] failed to persist removal journal`)}},Xe=new a_e(void 0,{onEviction:()=>Wre(),onSizeChange:e=>Gre(e),onMutate:()=>{!Je||qe!==null||(qe=setTimeout(()=>{qe=null,Ye()},2e3))}});for(let[e,r]of c_e(n))dC(e)||eY(e)&&([`.md`,`.mdx`].some(n=>{let r=z(t,`${e}${n}`);return Qk(r,z(t))&&B(r)})||Xe.restore(e,r));Je=!0;let Ze=(e,t)=>{dC(e)||Xe.setRenamed(e,t)},Qe=e=>{if(!dC(e)){if(Xe.peek(e)?.kind===`renamed`){console.info(JSON.stringify({event:`recently-removed-docs-unpaired-delete-suppressed`,docName:e,source:`watcher-delete`}));return}Xe.setDeleted(e)}},$e=e=>{dC(e)||Xe.delete(e)};try{ye=iI({projectDir:n,contentDir:t,singleDocRelPath:v,onAfterRebuild:()=>{be.rebuildFromDisk(S()).catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] backlink-index rebuild failed after onAfterRebuild`)}),xe.init().catch(e=>{F(`server-factory`).warn({err:e},`[content-filter] tag-index rebuild failed after onAfterRebuild`)}),oH(ht).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`)})}}),be=new YB({projectDir:n,contentDir:t,contentFilter:ye}),xe=new x9({projectDir:n,contentDir:t,contentFilter:ye}),(async()=>{await xe.loadFromDisk()?await xe.reconcileWithDisk():await xe.init()})().catch(e=>{F(`server-factory`).warn({err:e},`[server-factory] tag-index warm boot failed; continuing with empty index`)}),Se={current:f},Ce=s?Kge({getShadow:()=>Se.current??null,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,contentRoot:p??``,projectGitDir:Ou(n)??void 0,isWriterLive:e=>{if(!je&&!De)return F(`server-factory`).debug({writerId:e},`[server-factory] isWriterLive called before liveness deps populated — treating writer as dead`),!1;if(je?.getPresenceMap()[e])return!0;let t=e.startsWith(`agent-`)?e.slice(6):e;for(let e of De?.sessionsForConnection(t)??[])return!0;return!1}}):void 0,we=H7({contentDir:t,projectDir:n,gitEnabled:s,commitDebounceMs:c,wipRef:l,shadowRef:Se,ephemeral:y,contentRoot:p,backlinkIndex:be,configHomedirOverride:u,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,getPrincipal:()=>Ie,onAgentCommit:()=>ke?.signal(`session-activity`),onFlushCommit:()=>Ce?.noteFlushCommit(),onDiskFlush:(e,t,n,r)=>{ke?.emitDiskAck(e,t),!dC(e)&&TA(r,n)&&(Me?.(),We(`files`))},onConfigRejected:(e,t)=>ke?.emitConfigValidationRejected(e,t),onConfigPersisted:de,isRecentlyRemoved:e=>Xe.has(e),mdManager:e.mdManager,getLossRing:()=>Te,durabilityState:x}),Ee=new sge({quiet:r,debounce:a,maxDebounce:o,extensions:[we.extension]});let i=Ee;ze.push(bT(()=>i.documents.size),xT(()=>we.getQueueDepths()),CT(()=>{let e=0;for(let t of i.documents.values())e+=t.directConnectionsCount;return{websocket:i.getConnectionsCount()-e,direct:e}})),TT(),y||(Ne=r_e({getLoadedDocuments:()=>i.documents,forceStore:(e,t)=>we.forceStore(e,t),getBase:e=>x.getReconciledBase(e),isBatchActive:()=>x.isBatchInProgress(),peekInFlight:e=>x.peekInFlightFlush(e),readDiskBytes:e=>{let n=$k(e,t),r,i;try{r=Bl(n),i=Wl(r).size}catch(t){let n=As(t);if(n===`ENOENT`)return null;throw n===`ELOOP`?new W7(`symlink cycle at content path: ${e}`):t}if(!eA(r,t))throw new W7(`symlink-escape: ${n} resolves outside the content dir`);if(i>524288)throw new W7(`document exceeds the open byte limit: ${e}`);try{return V(r,`utf-8`)}catch(e){if(As(e)===`ENOENT`)return null;throw e}},graceMs:e.stalenessGraceMs,sweepIntervalMs:e.stalenessSweepIntervalMs}));let m=Ee.shouldUnloadDocument.bind(Ee);Ee.shouldUnloadDocument=e=>{if(Le.has(e)||Re&&m(e))return!0;let t=e.name;return dC(t)||C(t)!==void 0||e.getXmlFragment(`default`).length!==0||e.getText(`source`).length!==0?!1:m(e)},Be=async e=>{Le.add(e);try{await Ee.unloadDocument(e)}finally{Le.delete(e)}},ke=new mC(Ee),Ae=new zD(Ee),je=new BD(Ee),De=new vE(Ee);let _=De;ze.push(wT(()=>({active:_.liveSessionCount,limit:_.sessionLimit})));let w=b7({backlinkIndex:be,tagIndex:xe,signalChannel:We});Ee.configuration.extensions.push(w),Ee.configuration.extensions.push({__kind:`principal-auth`,async onAuthenticate(e){let t=e.token,n=fY(t),r=n?.expectedServerInstanceId;if(typeof r==`string`&&r.length>0&&r!==fe)throw new dY(`server-instance-mismatch`,`server instance mismatch: client claimed ${r}, this server is ${fe}`);let i=n?.expectedBranch,a=S();if(typeof i==`string`&&i.length>0&&i!==a)throw new dY(`branch-mismatch`,`branch mismatch: client claimed ${i}, server is on ${a}`);if(!n)return;let o=e.context;typeof n.principalId==`string`&&(Ie&&n.principalId===Ie.id?o.principalId=Ie.id:Ie?console.warn(JSON.stringify({event:`principal-token-mismatch`,claimed:n.principalId,loaded:Ie.id})):o.principalId=n.principalId),typeof n.tabSessionId==`string`&&(o.tabSessionId=n.tabSessionId),o.kind=`human`}}),Ee.configuration.extensions.push({__kind:`config-doc-admission-guard`,async onAuthenticate(t){if(!cC(t.documentName)&&!lC(t.documentName))return;let n=t.request,r=n.socket?.remoteAddress;if(r!==void 0&&!zk(r))throw Error(`config-doc admission requires loopback peer (peer=${r}, doc=${t.documentName})`);let i=t.requestHeaders,a=(i&&typeof i.get==`function`?i.get(`host`):null)??n.headers?.host??void 0,o=e.remotePublicHost!==void 0&&Gk(a,e.remotePublicHost);if(!Bk(a)&&!o)throw Error(`config-doc admission requires a loopback or remote Host header (host=${a??`<absent>`}, doc=${t.documentName})`)}});let ee=z(t);function te(e){if(!eY(e))return null;let t=z(ee,CC(e));return Qk(t,ee)?t:null}Ee.configuration.extensions.push({__kind:`removal-redirect-guard`,async onAuthenticate(e){await o_e(e.documentName,{recentlyRemovedDocs:Xe,resolveFilePath:te,fileExists:B})}}),Ee.configuration.extensions.push({__kind:`doc-lineage-guard`,async onAuthenticate(e){let t=fY(e.token);wge(e.documentName,t?.expectedDocLineageEpoch,{getLoadedDoc:e=>Ee.documents.get(e)})}}),Ee.configuration.extensions.push({__kind:`system-doc-broadcast-guard`,async beforeHandleMessage(e){if(e.documentName!==`__system__`)return;let t=new F5(e.update);if(t.readVarString(),t.readVarUint()===K5.BroadcastStateless)throw Error(`inbound BroadcastStateless on ${Kn} rejected — server-only channel`)}});let ne=nY({hocuspocus:Ee,durabilityState:x,remotePublicHost:e.remotePublicHost,sessionManager:De,contentDir:t,contentFilter:ye,serverInstanceId:fe,getFileIndex:()=>ht?ht.getFileIndex():new Map,getAttachmentFolderPath:ie,getAllFilesIndex:()=>ht?ht.getAllFilesIndex():new Map,getFileIndexGeneration:()=>ht?.getFileIndexGeneration()??0,mutateFileIndex:e=>ht?.mutateFileIndex(e),getFolderIndex:()=>ht?ht.getFolderIndex():new Map,getAliasMap:()=>ht?ht.getAliasMap():new Map,getFolderAliasIndex:()=>ht?ht.getFolderAliasIndex():new Map,rescanFiles:()=>ht?.rescanFromDisk(),enableTestRoutes:d,shadowRef:Se,flushGitCommit:()=>we.flushPendingGitCommit(),flushContributors:()=>we.flushContributors(),getCurrentBranch:()=>gt?.getLastKnownBranch()??null,getDiskAckSVs:()=>ke?.getLatestDiskAckSVsAsBase64()??{},contentRoot:p,backlinkIndex:be,tagIndex:xe,signalChannel:We,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,onAgentWrite:e.onAgentWrite,getSyncEngine:()=>_t,localOpCliArgs:h,authStreamHeartbeatMs:g,projectDir:n,resolveEmbed:_e,getBridgeLossReporter:()=>Oe,getPrincipal:()=>Ie,acpRegistry:me,loadAcpCustomAgents:()=>cd(pe,F(`acp-registry`)),homeDirOverride:u,forceUnloadDocument:Be,ready:Ue,recentlyRemovedDocs:Xe,serializeDoc:it,evictManagedArtifactLkg:e=>{we.managedArtifactCtx.lkgCache.delete(e)},semanticSearch:Fe,getSemanticSimilarityFloor:()=>ce().similarityFloor,getLinterBaseConfig:()=>oe(),getLinksValidationSetting:()=>se(),getLinkPreviewsEnabled:le,embeddingsSecretsFile:cP(u),readSemanticProviderConfig:ce,ephemeral:y,onReferencedAssetsCacheInvalidator:e=>{Me=e}});Ee.configuration.extensions.push(ne);let re=Do({absPath:Ao(`project`,n),sideline:!1,warn:e=>b.warn({message:e},`[config] could not read project config for bridge guards`)}),ae=re.value.bridge.deferGuard.enabled,ue=re.value.bridge.fixedPoint.enabled,he=re.value.bridge.preDrain.enabled;Te=re.value.lossCapture.enabled?new zne({projectDir:n,maxBytes:re.value.lossCapture.maxBytes}):void 0,re.value.bridge.lossDetector.enabled&&(Oe=iC({shadow:()=>Se.current,ring:Te,getBranch:()=>gt?.getLastKnownBranch()??`main`,contentRoot:p??``}),De.attachBridgeLossReporter(Oe)),Ee.configuration.extensions.push(Z7({mdManager:wo,schema:Co,shadowRef:Se,contentRoot:p,getCurrentBranch:()=>gt?.getLastKnownBranch()??null,resolveEmbed:_e,resolveSize:ve,deferGuardEnabled:ae,lossDetectorEnabled:re.value.bridge.lossDetector.enabled,fixedPointBackstopEnabled:ue,preDrainEnabled:he,lossRing:Te})),Ee.configuration.extensions.push(K_e()),Ee.configuration.extensions.push(Cge({getSyncEngine:()=>_t,projectDir:n,contentDir:t}))}catch(e){for(let e of ze.splice(0))e();throw Ne?.dispose(),Ne=null,vs(pe),e}let et=null,tt=new Map,nt=[];function rt(e,t){let n=z(e,`rescue`),r=z(n,CC(t));return Qk(r,n)?r:null}function it(e){let t=Ee.documents.get(e);return t?hV(t):null}let at=(e,t)=>fV(x,Ee,e,t,_e,ve,Oe);function ot(e){if(!RC(e)||_t?.getConflicts().some(r=>h7(r,e.name,n,t)))return;let r=e.getMap(`lifecycle`);r.delete(`status`),r.delete(`reason`)}let st=e=>{if(!e)return;let t=`[[${e}]]`;for(let[n]of Ee.documents){if(dC(n))continue;let r=Ee.documents.get(n);if(!r)continue;let i=r.getText(`source`).toString();if(i.includes(t))try{r.transact(()=>{iV(r,i,_e,n)},rV)}catch(t){b.error({err:t,docName:n,assetBasename:e},`[asset-event] failed to re-render ${n} for asset basename ${e}`)}}},ct=null,T=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 lt(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 yV(e)}}async function dt(e){try{switch(e.kind){case`create`:b.info({docName:e.docName},`[reconcile] create: ${e.docName}`),be.updateDocumentFromMarkdown(e.docName,e.content),Ke(),xe.updateDocumentFromMarkdown(e.docName,e.content),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),$e(e.docName);break;case`update`:{let{docName:t,content:n}=e,r=Ee.documents.get(t);if(!r){be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`);return}let i=C(t)??``,a=it(t)??i,o=cV({docName:t,base:i,ours:a,theirs:n}),s=EV(i).slice(0,6),c=EV(a).slice(0,6),l=EV(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),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`);break;case`clean`:try{at(t,o.newContent),w(t,o.newContent),fS(),ot(r),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply clean content to Y.Doc for ${t}`),w(t,n),ot(r)}break;case`merged`:try{at(t,o.newContent),w(t,n),fS(),ot(r),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}catch(e){b.error({err:e,docName:t},`[reconcile] failed to apply merged content to Y.Doc for ${t}`),w(t,n),ot(r)}break;case`conflicts`:try{at(t,o.newContent),w(t,o.newContent),fS(),pS(),be.updateDocumentFromMarkdown(t,n),Ke(),xe.updateDocumentFromMarkdown(t,n),We(`backlinks`),We(`graph`),We(`tags`)}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`)}break;case`refused`:{pS();let e=r.getMap(`lifecycle`);e.set(`status`,`conflict`),e.set(`reason`,o.reason);break}}break}case`delete`:{let{docName:t}=e,n=Ee.documents.get(t);if(!n){be.deleteDocument(t),Ke(),xe.deleteDocument(t),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),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&&Se.current){let e=Se.current,n=gt?.getLastKnownBranch()??`main`;queueMicrotask(()=>{QS(e,p??``,{kind:`external-change-rescue`,docName:t,contents:i,label:`External change recovered @ ${new Date().toISOString()}`,branch:n,metadata:{incomingDiskSha:``}}).then(()=>{hS(),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`),ee(t),be.deleteDocument(t),Ke(),xe.deleteDocument(t),b.info({docName:t,isDirty:a},`[reconcile] delete: ${t} (dirty=${a})`),Ee.closeConnections(t),await Be(n),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),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=Ee.documents.get(t);if(ee(t),w(n,r),be.renameDocument(t,n,r),Ke(),xe.renameDocument(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}`),We(`files`),We(`backlinks`),We(`graph`),We(`tags`),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=Ee.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`:ge.add(e.relativePath),We(`files`),T(_l(e.relativePath));break;case`asset-delete`:ge.remove(e.relativePath),We(`files`),T(_l(e.relativePath));break;case`folder-create`:case`folder-delete`:We(`files`);break;case`file-create`:case`file-update`:case`file-delete`:We(`files`);break;default:yV(e)}}catch(t){let n=lt(e);b.error({err:t,kind:e.kind,label:n},`[reconcile] failed to handle ${e.kind} for ${n}`)}}let ft=[];async function pt(e){if(re()){ft.push(e);return}await dt(e)}async function mt(){let e=ft.splice(0,ft.length);for(let t of e)await dt(t)}let ht=null,gt=null,_t=null,vt=null;async function yt(e){if(Ee.documents.size===0)return;let t=!1,n=new Promise(e=>{Ee.configuration.extensions.push({async afterUnloadDocument({instance:n}){!t&&n.getDocumentsCount()===0&&(t=!0,e())}})}),r=Array.from(Ee.documents.keys());Ee.closeConnections(),Ee.flushPendingStores();for(let e of Ee.documents.values())e.getConnectionsCount()===0&&Ee.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(Ee.documents.keys()),i=[],o=[];if(Se.current){for(let e of n)if(!dC(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(Se.current.gitDir,e);if(!n){b.warn({docName:e,gitDir:Se.current.gitDir},`[rescue] path-traversal guard rejected docName: ${e}`),o.push(e);continue}Nl(I(n),{recursive:!0}),Kl(n,t,`utf-8`),hS(),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 bt(){return vt||(vt=(async()=>{let e=Date.now(),t=[];Re=!0;for(let e of ze.splice(0))e();try{await Ne?.dispose()}catch(e){b.warn({err:e},`[server] staleness watchdog drain failed during destroy`)}Ne=null;try{Os(pe)}catch(e){b.warn({err:e},`[server] failed to mark server.lock draining`)}if(Ge!==null&&(clearTimeout(Ge),Ge=null),xe.close(),qe!==null&&(clearTimeout(qe),qe=null),Je)try{Y7(n,Xe.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 r,i=await Promise.race([Ue.then(()=>`completed`,e=>(b.debug({err:e},`[server] init incomplete during shutdown`),`failed`)),new Promise(e=>{r=setTimeout(()=>e(`timeout`),5e3)})]);r!==void 0&&clearTimeout(r),i===`timeout`&&b.warn({},`[server] init did not complete within 5s during shutdown`);let a=Ee.documents.size;Ce?.destroy();try{try{try{gt&&=(await gt.unsubscribe(),null),ht&&=(await ht.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{ke?.destroy(),je?.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 De.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 xw()}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 yt(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`)}let e;try{await Promise.race([(async()=>{await we.flushPendingGitCommit(),await we.waitForPendingCommits()})(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`L2 git flush timeout`)),m)})])}catch(e){t.push({phase:`git-commit-flush`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-4 git commit flush failed`)}finally{e!==void 0&&clearTimeout(e)}try{_t&&=(await _t.destroy(),null)}catch(e){t.push({phase:`sync-engine-stop`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown sync-engine-stop failed`)}}finally{if(Se.current){try{let e=(await ds({baseDir:n,timeout:{block:5e3}}).revparse(`HEAD`)).trim();e&&Kl(z(Se.current.gitDir,`last-known-head`),e,`utf-8`)}catch{}try{aie(Se.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 r=Date.now()-e;t.length===0?b.info({documentCount:a,durationMs:r},`[server] shutdown flushed ${a} documents in ${r}ms`):b.warn({documentCount:a,durationMs:r,phaseErrors:t},`[server] shutdown flushed ${a} documents in ${r}ms with ${t.length} phase error(s)`)}}finally{try{vs(pe,{deferUnlinkToExit:!0})}catch(e){t.push({phase:`server-lock-release`,error:e instanceof Error?e.message:String(e)}),b.error({err:e},`[server] shutdown phase-6 releaseServerLock failed`)}try{await es()}catch(e){t.push({phase:`telemetry-shutdown`,error:e instanceof Error?e.message:String(e)})}}})(),vt)}let xt=[];async function St(){try{Ie=await G7(n),b.info({principalId:Ie.id},`[server] principal loaded`)}catch(e){b.warn({err:e},`[server] principal load failed — browser writes will use SERVICE_WRITER`)}if(!Se.current)try{Se.current=await zS(n),b.info({gitDir:Se.current.gitDir},`[server] history repo initialized at ${Se.current.gitDir}`)}catch(e){b.error({err:e},`[server] history repo init failed`),xt.push(`shadow-repo`)}if(Se.current){let e=null;try{e=pG(Se.current.gitDir),IG(Se.current.gitDir,e),vG(Se.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([LG(Se.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 Ce?.runBootMaintenance()}catch(e){b.warn({err:e},`[shadow-maintenance] boot maintenance failed (non-fatal)`)}}if(Se.current)try{await LS(Se.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{Se.current=await zS(n)}catch(e){b.error({err:e},`[server] history repo reinit failed`),Se.current=void 0,xt.includes(`shadow-repo`)||xt.push(`shadow-repo`)}}else b.error({err:e},`[server] history repo check failed (transient?)`)}if(Se.current)try{let e=z(Se.current.gitDir,`last-known-head`),t=null;try{t=V(e,`utf-8`).trim()||null}catch{}let r=null;try{r=(await ds({baseDir:n,timeout:{block:1e4}}).revparse(`HEAD`)).trim()||null}catch{}if(r!==null){if(r!==t){let e=`main`;try{let t=(await ds({baseDir:n,timeout:{block:1e4}}).raw(`rev-parse`,`--abbrev-ref`,`HEAD`)).trim();t&&t!==`HEAD`&&(e=t)}catch{}b.info({lastKnownHead:t,currentHead:r,branch:e},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=import`);try{await YS(Se.current,p??``,t,r,e),mS()}catch(e){b.warn({err:e},`[head-drift] commitUpstreamImport failed — continuing`)}}else b.info({currentHead:r},`[head-drift] lastKnownHead=${t??`null`}, currentHead=${r}, action=noop`);try{Kl(e,r,`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=$W(t,n);if(e.recovered&&e.journal){let t=e.journal.version===2?e.journal.fromPath:e.journal.sourceDocName,n=e.journal.version===2?e.journal.toPath:e.journal.destinationDocName;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`),xt.push(`managed-rename-recovery`)}try{let e=mB(n);(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`),xt.push(`upload-tempfile-sweep`)}try{et=await Ee.openDirectConnection(Kn),ke?.emitServerInfo(fe,S())}catch(e){b.error({err:e},`[server] failed to open __system__ direct connection — CC1 push disabled`),xt.push(`cc1-push`)}let r=y?[]:i;for(let e of r)try{let t=await Ee.openDirectConnection(e);tt.set(e,t)}catch(t){b.error({err:t,docName:e},`[server] failed to open ${e} direct connection — config bind degraded`),xt.push(`config-doc:${e}`)}let a=new Map([[Bi,Ao(`project`,n)],[si,Ao(`project-local`,n)],[Ei,Ao(`user`,n,u)]]);for(let e of r){let t=a.get(e);if(t)try{b.info({docName:e,path:t},`[config-file-watcher] starting`);let n=await pge(t,t=>{let n=Ee.documents.get(e);b.info({docName:e,hasDocument:n!==void 0,contentLength:t.length},`[config-file-watcher] file changed`);let r=m7(n??null,e,t,we.configPersistenceCtx);b.info({docName:e,outcome:r},`[config-file-watcher] applyExternalConfigChange outcome`),de(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}`),xt.push(`config-file-watcher:${e}`)}}if(!y){let e=(e,t)=>{let n=AW(e,we.managedArtifactCtx);if(!n)return;let r=NW(Ee.documents.get(n)??null,n,t,we.managedArtifactCtx);b.info({docName:n,outcome:r},`[managed-artifact-watcher] external change`),Zn(n)&&be.ingestGlobalSkillBundles(EW(we.managedArtifactCtx),S()).then(()=>{We(`backlinks`),We(`graph`)}).catch(e=>{b.warn({err:e,docName:n},`[backlinks] global skill bundle re-ingest failed`)})};try{let t=EW(we.managedArtifactCtx),n=await M7(t,e);nt.push({docName:`__skill-files__`,cleanup:n}),b.info({roots:t},`[managed-artifact-watcher] skills started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] skills failed to start`),xt.push(`managed-artifact-watcher:skills`)}try{let t=new Set([``]);try{for(let e of Kj(n).templates)t.add(e.source_folder)}catch(e){b.warn({err:e},`[managed-artifact-watcher] template enumeration failed; root only`)}let r=[...t].map(e=>e?z(n,e,`.ok`,`templates`):z(n,`.ok`,`templates`)),i=await M7(r,e,Jge);nt.push({docName:`__template-files__`,cleanup:i}),b.info({rootCount:r.length},`[managed-artifact-watcher] templates started`)}catch(e){b.warn({err:e},`[managed-artifact-watcher] templates failed to start`),xt.push(`managed-artifact-watcher:templates`)}}try{let e=z(t,`.okignore`),r=z(n,`.gitignore`),i=null;try{let e=hl(`git`,[`rev-parse`,`--git-common-dir`],OP({cwd:n,encoding:`utf-8`,timeout:5e3}));if(e.status===0&&e.stdout){let t=L(z(n,e.stdout.trim()),`info`,`exclude`);B(I(t))&&(i=t)}}catch{}let a=i?[e,r,i]:[e,r],o=b;o.info({okignorePath:e,gitignorePath:r,gitInfoExcludePath:i,ephemeral:y},`[ignore-watcher] starting multi-path watcher for .okignore + .gitignore (+ .git/info/exclude when present)`);let s=y?null:await mge(a,(t,r)=>{(async()=>{if(t===e)try{let e=m7(Ee.documents.get(`__config__/okignore`)??null,nr,r,we.configPersistenceCtx);o.info({docName:nr,outcome:e},`[ignore-watcher] applyExternalConfigChange outcome`)}catch(e){o.error({err:e,changedPath:R(n,t)},`[ignore-watcher] applyExternalConfigChange failed; rebuild proceeds independently`)}let i=await ye.rebuildIgnorePatterns();if(i.ok)o.info({changedPath:R(n,t),patternCount:i.patternCount,nestedFileCount:i.nestedFileCount,durationMs:i.durationMs},`[ignore-watcher] rebuild succeeded — broadcasting files channel`),ke?.signal(`files`);else{let e=R(n,t)||`.`;o.warn({changedPath:e,error:i.error.message},`[ignore-watcher] rebuild failed — emitting config-ignore-nested-error`),ke?.emitConfigIgnoreNestedError(e,i.error.message)}})().catch(e=>{o.error({err:e,changedPath:R(n,t)||`.`},`[ignore-watcher] handler threw`)})});s&&(nt.push({docName:`__ignore-files__`,cleanup:s}),o.info({okignorePath:e,gitignorePath:r},`[ignore-watcher] multi-path watcher started`))}catch(e){b.warn({err:e,projectDir:n,contentDir:t},`[ignore-watcher] failed to start multi-path watcher`),xt.push(`ignore-files-watcher`)}let o=y7(n).branch??`main`;te(o),be.switchBranch(o);let s=performance.now();try{await Mo(`ok.boot.indexes`,void 0,async()=>{let e=S();try{if(await be.loadFromDisk(e)){let t=await be.reconcileWithDisk(e);(t.added>0||t.updated>0||t.deleted>0)&&b.info({added:t.added,updated:t.updated,deleted:t.deleted},`[backlinks] startup reconcile: offline changes applied`);let n=0;for(let e of t.deletedDocNames)dC(e)||Xe.peek(e)?.kind!==`renamed`&&(Xe.setDeleted(e),n++);n>0&&b.info({count:n},`[removal-guard] tombstoned docs deleted while the server was down`)}else await be.rebuildFromDisk(e);try{await be.ingestGlobalSkillBundles(EW(we.managedArtifactCtx),e)}catch(t){b.warn({err:t,branch:e},`[backlinks] global skill bundle ingest failed`)}be.saveToDisk().catch(t=>{F(`backlinks`).warn({branch:e,err:t},`Failed to persist startup cache for ${e}`)})}catch(t){b.error({err:t,branch:e},`[backlinks] startup init failed; index will populate incrementally via watcher`)}let n=performance.now();ht=await Mo(`ok.boot.seed-walk`,void 0,async()=>aH(t,pt,ye)),eV(`seedWalkMs`,Math.round(performance.now()-n));{let e=z(t),n=0;for(let[t]of Xe.entries()){if(!eY(t))continue;let r=z(e,`${t}${SC(t)}`);Qk(r,e)&&B(r)&&(Xe.delete(t),n++)}n>0&&b.info({count:n},`[removal-guard] dropped journaled removal entries whose file re-appeared while the server was down`)}try{let e=await xe.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[tag-index] startup reconcile: offline changes applied`),xe.saveToDisk().catch(e=>{F(`tag-index`).warn({err:e},`Failed to persist startup tag snapshot`)})}catch(e){b.error({err:e},`[tag-index] startup reconcile failed; tag index updates incrementally via watcher events`),xt.push(`tag-index`)}let r=0;try{v===void 0?await aY({contentDir:t,contentFilter:ye,basenameIndex:ge,onSkip:(e,t,n)=>{r++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during seed (${e}${t?` ${t}`:``})`)}}):iY({contentDir:t,basenameIndex:ge,onSkip:(e,t,n)=>{r++,b.warn({reason:e,code:t,path:n},`[basename-index] skipped entry during single-file seed (${e}${t?` ${t}`:``})`)}}),r>0&&(b.warn({count:r},`[basename-index] startup seed completed with ${r} skipped entries — embeds under inaccessible subtrees will not resolve`),xt.push(`basename-index-partial`))}catch(e){b.error({err:e},`[basename-index] startup seed failed`),xt.push(`basename-index`)}})}catch(e){b.error({err:e},`[server] disk bridge watcher failed to start`),xt.push(`file-watcher`)}finally{eV(`indexesMs`,Math.round(performance.now()-s)),ht&&tV(`fileCount`,ht.getFileIndex().size)}try{gt=await kge(n,async({trigger:e})=>{if(b.info({trigger:e},`[batch] begin trigger=${e}`),qne(),Ee.flushPendingStores(),await we.flushPendingGitCommit(),ne(!0),Se.current){let e=S(),t=y7(n).branch??e,r=[];for(let[e,t]of Ee.documents){if(dC(e))continue;let n=null;if(t.transact(()=>{n=it(e)},X_e),n===null)continue;let i=C(e)??n;r.push({docName:e,markdown:n,diskSnapshot:i})}if(r.length>0)try{let n=await hie(Se.current,e,qS.id,r,t);n&&(Xne(),b.info({count:r.length,branch:e,sha:n.slice(0,8)},`[history] parked ${r.length} docs on ${e} → ${n.slice(0,8)}`))}catch(e){b.error({err:e},`[shadow] park failed`)}}},async e=>{let r=ft.length,i=e.newBranch??`main`;if(b.info({kind:e.batchKind,headMoved:e.headMoved,docs:r,timeout:!!e.timeout},`[batch] end kind=${e.batchKind} headMoved=${e.headMoved} docs=${r}${e.timeout?` timeout`:``}`),e.batchKind===`within-branch`){if(ne(!1),await mt(),e.headMoved&&e.newHead){let r=Q_e(n,z(t),e.oldHead,e.newHead);if(r.size>0){lN(r.keys());for(let[e,t]of r)cN(e,Gee(t.email),t.name,t.email,Hu(e));await we.flushContributors()}}if(await we.flushDeferredStores(`within-branch`),_t!==null)try{await _t.reconcileConflictsFromGit()}catch(e){b.warn({err:e},`[head-watcher] sync engine conflict reconcile failed`)}}else{Yne(),ft.splice(0,ft.length),te(i),Ge!==null&&(clearTimeout(Ge),Ge=null),be.switchBranch(i),ye.rebuildDirCount();try{let e=0;ge.clear(),await aY({contentDir:t,contentFilter:ye,basenameIndex:ge,onSkip:(t,n,r)=>{e++,b.warn({reason:t,code:n,path:r,branch:i},`[basename-index] skipped entry during branch-switch reseed (${t}${n?` ${n}`:``})`)}}),e>0&&(b.warn({count:e,branch:i},`[basename-index] branch-switch reseed completed with ${e} skipped entries — embeds under inaccessible subtrees will not resolve on this branch`),xt.includes(`basename-index-partial`)||xt.push(`basename-index-partial`))}catch(e){b.error({err:e,branch:i},`[basename-index] branch-switch reseed failed`)}for(let[e,n]of Ee.documents)if(!dC(e))try{let r=$k(e,t);if(!B(r)){let t=C(e)??``,r=it(e)??``;if(r!==t&&Se.current){let t=Se.current;queueMicrotask(()=>{QS(t,p??``,{kind:`external-change-rescue`,docName:e,contents:r,label:`External change recovered @ ${new Date().toISOString()}`,branch:i,metadata:{incomingDiskSha:``}}).then(()=>{hS(),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}`)})})}n.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:Ee.documents.size},`[branch-switch] loaded branch ${i} (${Ee.documents.size} docs)`);try{if(await be.loadFromDisk(i)){let e=await be.reconcileWithDisk(i);(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[backlinks] branch-switch reconcile for ${i}`)}else await be.rebuildFromDisk(i);try{await be.ingestGlobalSkillBundles(EW(we.managedArtifactCtx),i)}catch(e){b.warn({err:e,branch:i},`[backlinks] branch-switch global skill bundle ingest failed`)}be.saveToDisk(i).catch(e=>{F(`backlinks`).warn({branch:i,err:e},`Failed to persist branch cache for ${i}`)})}catch(e){b.error({err:e,branch:i},`[backlinks] branch-switch rebuild failed; backlinks may be stale`)}try{let e=await xe.reconcileWithDisk();(e.added>0||e.updated>0||e.deleted>0)&&b.info(e,`[tag-index] branch-switch reconcile for ${i}`)}catch(e){b.warn({err:e,branch:i},`[tag-index] branch-switch reconcile failed; falling back to full rebuild`),await xe.init()}if(xe.saveToDisk().catch(e=>{F(`tag-index`).warn({branch:i,err:e},`Failed to persist tag snapshot after branch switch`)}),Se.current&&e.batchKind===`cross-branch`){let e=0;for(let[t]of Ee.documents)if(!dC(t))try{let n=await _ie(Se.current,i,qS.id,t);if(!n||n.markdown===n.diskSnapshot)continue;let r=C(t);if(!r)continue;let a=cV({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),pS(),e++;{let e=Ee.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-`)&&Se.current)try{let t=LS(Se.current),n=(await t.raw(`for-each-ref`,`refs/wip/${e.oldBranch}/`,`--format=%(refname)`)).trim();n&&(await NS(Se.current).withMutator(async()=>{for(let e of n.split(`
3271
- `))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`)}ne(!1),await we.flushDeferredStores(`discard-stale`),ke?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&Se.current&&r>0){let t=p??`.`;try{let n=await YS(Se.current,t,e.oldHead,e.newHead,i);mS(),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`),xt.push(`head-watcher`)}function c(e){for(let r of e)try{let e=Zk(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=_C(e),a=Ee.documents.get(i);if(!a)continue;let o=it(i);o===null?b.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function l(e){for(let r of e)try{let e=Zk(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Ee.documents.get(_C(e));i&&ot(i)}catch(e){b.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let d=Z_e(h),f=ae();f.mode!==`off`&&b.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{_t=new W_e({projectDir:n,contentDir:t,contentFilter:ye,contentRoot:p,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:d,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ne(e),e||we.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:c,onContentConflictsResolved:l,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Se.current;n&&await ZS(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Se.current;n&&await ZS(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:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:to(t.error),configPath:Ao(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await _t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),_t=null}We(`files`),We(`backlinks`),We(`graph`),We(`tags`);let m=$B();m!==void 0&&eV(`readyMs`,m)}return St().then(Ve,He),{hocuspocus:Ee,durabilityState:x,sessionManager:De,cc1Broadcaster:ke,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:Ce,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:bt,ready:Ue,degraded:xt,lockDir:pe,get syncEngine(){return _t},resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function T9(e){return e/1048576}function $_e(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:T9(e.rss),heapTotalMb:T9(e.heapTotal),heapUsedMb:T9(e.heapUsed),externalMb:T9(e.external),arrayBuffersMb:T9(e.arrayBuffers)}}}let E9=null,D9=null,O9=null;const k9=1e6;let A9=null,j9=null;jo(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function eve(){if(E9)return;let e=ns().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}=$_e();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`})}),E9=e}function tve(){if(!D9){let e=ns().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(!A9){A9=kee({resolution:20}),A9.enable();return}e.observe(A9.percentile(50)/k9,{stat:`p50`}),e.observe(A9.percentile(99)/k9,{stat:`p99`}),A9.reset()}),D9=e}if(!O9){let e=ns().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=j9;if(j9={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`}))}),O9=e}}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=zA(e);M9=new cs({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ma(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){ma(null),await M9?.drain(),M9=null,N9=!1}xo();const nve=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],rve=[`cache`,`tmp`];function ive(e){let t=z(e,io);if(!(()=>{if(!B(t))return!0;try{return Rl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of nve)B(z(e,t))&&n.push(t);for(let t of rve){let r=z(e,t);try{B(r)&&Wl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function ave(e){let t=Du(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 L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function ove(e){QB();let t=e.projectDir??e.contentDir,n=kY({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}`)}is.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}ts({localSink:n?.telemetry}),F9(t),eve(),tve();let{kind:r,gitdir:i}=ave(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Ko(i));let o=xY(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Mo(`ok.boot`,{attributes:a},async()=>sve(e)),l=()=>{if(s)try{let e=yo.extract(So.active(),{traceparent:s});return So.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 sve(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Hk(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new Vk("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-PrjHr5-L.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new i5(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??RR;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof FR||e instanceof IR){let t=e instanceof IR?e.detected:``,n=e instanceof IR?`too_old`:`not_available`;oW(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await es(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=ive(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${io}/.`);let v=w9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=v,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:Q8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:r}),oe=c();oe.headersTimeout=3e4,oe.requestTimeout=6e4;let se=e.serveContentAssets===!1?void 0:IA({contentFilter:v.contentFilter,contentSirv:Ns(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_o,assetExtensions:Na,blocklistExtensions:ka}),ce=!1;if(e.reactShellDistDir)try{eB(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ce=!0}catch(e){if(e instanceof $z)r.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 le=e.reactShellDistDir?Ns(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ue=e.ephemeral?null:new FD({contentDir:e.contentDir,localDir:C,globalDir:z(Xl(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:te,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:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>PD(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ue!==null&&await ue.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let de=e5({httpServer:oe,hocuspocus:y,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:se,reactShellMiddleware:le,ephemeral:e.ephemeral,acpThreadManager:ue}),fe=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},pe=null;a!==null&&(pe=SY({httpServer:oe,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await fe()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);oe.once(`error`,r),oe.listen(e.port,e.host,()=>{oe.removeListener(`error`,r),t()})})}catch(e){if(ce)try{rB(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let me=$B();me!==void 0&&eV(`httpListenMs`,me);let he=oe.address(),ge=typeof he==`object`&&he?he.port:e.port??0;if(ie=ge,d(C,ge),ce&&tB(C,ge),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let _e=!1,ve=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};fe=async()=>{if(_e)return;_e=!0;let e=[],t=async(t,n)=>{try{await ve(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),ce&&iB(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{pe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ue!==null&&await t(`acpThreads.destroy`,()=>ue.destroy()),await t(`mount.shutdown`,()=>de.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{de.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{oe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{oe.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ce&&await t(`releaseUiLock`,async()=>rB(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>es()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>is.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await Uz({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:oe,destroy:fe,lockDir:C,contentDir:e.contentDir,port:ge,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ue}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new hY(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=Ou(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=ps({baseDir:n,timeout:{block:5e3}});s=new Set(await dS(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=_C(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 cve=Ga;function lve(e={}){let t=e.home??Xl(),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 z9=t(ss(),1);const B9=L(Xl(),`.ok`,`logs`),uve=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function dve(){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 fve(e){Nl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function pve(e){try{if(Wl(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{Vl(n,r)}catch{}}try{Gl(`${e}.3`)}catch{}}function mve(e){try{let t=Date.now(),n=10080*60*1e3,r=Rl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Wl(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{Gl(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{Gl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function hve(e){fve(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);pve(n),(e._setTimeout??setTimeout)(()=>mve(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:dve(),name:e.name,redact:{paths:uve,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function gve(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function _ve(e){return L(B9,`${e}.${V9()}.log`)}function vve(){return B9}function yve(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 H9=vu(pl),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function bve(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],OP({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function xve(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!Wl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=RR()}catch(e){throw e instanceof FR||e instanceof IR?(oW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof IR?`too_old`:`not_available`,detectedVersion:e instanceof IR?e.detected:``},e instanceof IR?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await bve(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],OP({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,Sve=Ci.map(e=>e.replace(/\/$/,``));async function Cve(e){let t=Ou(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(Dve(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ms(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await fs(async()=>{let t=await wve(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await Tve(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=ms(e,{gitIndexFile:L($l(),`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 Eve(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await wH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;gs(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 \`${Ie}\` 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 Sve){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function wve(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 Tve(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function Eve(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function Dve(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 Ove(e,t){let n;try{n=fl(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 iu(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 kve=[{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 kve)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 Ave(e){if(!hC(e))throw new $9(e);let t;try{t=Bl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Wl(t).isFile())throw new Q9(e);let n=I(t),r=cH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:_C(R(jve(e),t).split(Cl).join(`/`)),canonicalFilePath:t}}let i=_l(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:_C(i)}}function jve(e){return z(e,Do({absPath:Ao(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Mve(e){let t=Pl(z($l(),`ok-ephemeral-`)),n=z(t,`.ok`);return Nl(n,{recursive:!0}),Kl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Kl(z(n,`.gitignore`),`local/
3271
+ `))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`)}ne(!1),await we.flushDeferredStores(`discard-stale`),ke?.emitBranchSwitched(i)}if(e.headMoved&&e.newHead&&Se.current&&r>0){let t=p??`.`;try{let n=await YS(Se.current,t,e.oldHead,e.newHead,i);mS(),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`),xt.push(`head-watcher`)}function c(e){for(let r of e)try{let e=Zk(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=_C(e),a=Ee.documents.get(i);if(!a)continue;let o=it(i);o===null?b.warn({docName:i,file:r},`[sync] content conflict: serializeDoc returned null; reconciledBase snapshot skipped`):w(i,o);let s=a.getMap(`lifecycle`);s.set(`status`,`conflict`),s.set(`reason`,`sync-merge-conflict`),b.info({docName:i,file:r},`[sync] marked loaded content conflict`)}catch(e){b.warn({err:e,file:r},`[sync] failed to mark loaded content conflict`)}}function l(e){for(let r of e)try{let e=Zk(R(t,L(n,r)));if(e.startsWith(`..`))continue;let i=Ee.documents.get(_C(e));i&&ot(i)}catch(e){b.warn({err:e,file:r},`[sync] failed to clear resolved content conflict`)}}let d=Z_e(h),f=ae();f.mode!==`off`&&b.info({mode:f.mode,source:f.source},`[sync] mode active at boot`);try{_t=new W_e({projectDir:n,contentDir:t,contentFilter:ye,contentRoot:p,mode:f.mode,pullIntervalSeconds:e.pullIntervalSeconds,pushIntervalSeconds:e.pushIntervalSeconds,credentialArgs:d,cc1Broadcaster:ke,detectGh:e.detectGh,tokenStore:e.tokenStore,checkPushPermissionFn:e.checkPushPermissionFn,setBatchInProgress:e=>{ne(e),e||we.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:c,onContentConflictsResolved:l,checkpointBeforeStrandedConversion:async({branch:e,ahead:t})=>{let n=Se.current;n&&await ZS(n,p??``,{action:`pull-only-stranded-conversion`,context:{ahead:t}},e)},checkpointBeforeOverlayRestore:async({branch:e,paths:t})=>{let n=Se.current;n&&await ZS(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:n,scope:`project-local`,patch:{autoSync:{enabled:!1}}});t.ok||b.error({result:t,reason:e,humanError:to(t.error),configPath:Ao(`project-local`,n)},`[sync] failed to persist auto-disable — next restart WILL re-enable sync and re-trigger the same failure. Check permissions on the config path.`)}}),await _t.start()}catch(e){b.warn({err:e},`[server] SyncEngine failed to start — sync disabled`),_t=null}We(`files`),We(`backlinks`),We(`graph`),We(`tags`);let m=$B();m!==void 0&&eV(`readyMs`,m)}return St().then(Ve,He),{hocuspocus:Ee,durabilityState:x,sessionManager:De,cc1Broadcaster:ke,agentFocusBroadcaster:Ae,agentPresenceBroadcaster:je,maintenanceCoordinator:Ce,contentFilter:ye,basenameIndex:ge,serverInstanceId:fe,destroy:bt,ready:Ue,degraded:xt,lockDir:pe,get syncEngine(){return _t},resolveEmbed:_e,acpRegistry:me,acpPermissions:he}}function T9(e){return e/1048576}function $_e(){let e=process.memoryUsage();return{schemaVersion:1,capturedAt:new Date().toISOString(),snapshot:{rssMb:T9(e.rss),heapTotalMb:T9(e.heapTotal),heapUsedMb:T9(e.heapUsed),externalMb:T9(e.external),arrayBuffersMb:T9(e.arrayBuffers)}}}let E9=null,D9=null,O9=null;const k9=1e6;let A9=null,j9=null;jo(()=>{E9=null,D9=null,O9=null,A9?.disable(),A9=null,j9=null});function eve(){if(E9)return;let e=ns().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}=$_e();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`})}),E9=e}function tve(){if(!D9){let e=ns().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(!A9){A9=kee({resolution:20}),A9.enable();return}e.observe(A9.percentile(50)/k9,{stat:`p50`}),e.observe(A9.percentile(99)/k9,{stat:`p99`}),A9.reset()}),D9=e}if(!O9){let e=ns().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=j9;if(j9={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`}))}),O9=e}}let M9=null,N9=!1;function P9(e=process.env){return e.OK_BRIDGE_TOLERANCE_TELEMETRY===`1`}function F9(e){if(!P9())return;let t=zA(e);M9=new cs({currentPath:z(t,`tolerance-telemetry.jsonl`),previousPath:z(t,`tolerance-telemetry.prev.jsonl`),maxBytes:8388608}),ma(e=>{let t={event:`bridge-tolerance-fire`,timestamp:e.timestamp,class:e.className,document:e.documentName??null,codeUnitPosition:e.codeUnitPosition,severity:e.severity};M9?.append(`${JSON.stringify(t)}\n`).catch(e=>{N9||(N9=!0,F(`tolerance-telemetry`).warn({err:e instanceof Error?e:Error(String(e))},`append failed; further failures are silent`))})})}async function I9(){ma(null),await M9?.drain(),M9=null,N9=!1}xo();const nve=[`server.lock`,`ui.lock`,`state.json`,`principal.json`,`sync-state.json`,`conflicts.json`,`last-spawn-error.log`],rve=[`cache`,`tmp`];function ive(e){let t=z(e,io);if(!(()=>{if(!B(t))return!0;try{return Rl(t).length===0}catch{return!0}})())return[];let n=[];for(let t of nve)B(z(e,t))&&n.push(t);for(let t of rve){let r=z(e,t);try{B(r)&&Wl(r).isDirectory()&&n.push(`${t}/`)}catch{}}return n}function ave(e){let t=Du(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 L9=Number(process.env.OK_DESTROY_STEP_TIMEOUT_MS)||5e3;async function ove(e){QB();let t=e.projectDir??e.contentDir,n=kY({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}`)}is.configure({pinoConfig:{fileSink:n.logs,redactPaths:t}})}ts({localSink:n?.telemetry}),F9(t),eve(),tve();let{kind:r,gitdir:i}=ave(e.projectDir??e.contentDir),a={"ok.worktree.kind":r};i!==null&&(a[`ok.worktree.gitdir`]=Ko(i));let o=xY(t),s=process.env.OK_STARTUP_TRACEPARENT,c=()=>Mo(`ok.boot`,{attributes:a},async()=>sve(e)),l=()=>{if(s)try{let e=yo.extract(So.active(),{traceparent:s});return So.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 sve(e){let t=e.skipAutoInit??!1,n=e.attachUiSibling??!0,r=e.log??F(`boot`),i=e.enableRemote===!0&&e.ephemeral!==!0?Hk(e.config):null;if(e.enableRemote===!0&&e.ephemeral!==!0&&i===null)throw new Vk("remote access was requested but remote.url is not set — pass a url (`ok start --remote <url>`) or set remote.url in .ok/config.yml.");let a=i===null?e.idleShutdownMs:null,o=process.env.OK_LOCK_KIND===`mcp-spawned`||process.env.OK_LOCK_KIND===`interactive`?process.env.OK_LOCK_KIND:void 0,s=e.lockKind??o??`interactive`,{createServer:c}=await import(`node:http`),{markServerLockDraining:l,releaseServerLock:u,updateServerLockPort:d}=await import(`./server-lock-CACUewto.mjs`),f=!1;if(!t&&e.autoInitFn)try{f=!!await e.autoInitFn()}catch(e){r.warn({err:e},`autoInitFn failed`)}let p=e.projectDir??e.contentDir,m=z(p,`.ok`);if(!B(z(m,`config.yml`)))throw new i5(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??RR;try{e.gitEnabled!==!1&&g()}catch(e){if(e instanceof FR||e instanceof IR){let t=e instanceof IR?e.detected:``,n=e instanceof IR?`too_old`:`not_available`;oW(e),r.warn({event:`git_preflight_fail`,platform:e.platform,reason:n,detectedVersion:t},n===`not_available`?`git binary not found`:`git binary too old`),process.stderr.write(`${e.message}\n`)}throw await es(),await Promise.race([I9(),new Promise(e=>setTimeout(e,L9))]),e}let _=ive(m);_.length>0&&F(`boot`).warn({files:_},`Found legacy runtime files at .ok/${_.join(`, `)}. Delete .ok/ and re-init — these files moved to .ok/${io}/.`);let v=w9({contentDir:e.contentDir,projectDir:e.projectDir,remotePublicHost:i?.publicHost,contentRoot:e.contentRoot,port:e.port,host:e.host,quiet:e.quiet??!1,debounce:e.debounce,maxDebounce:e.maxDebounce,gitEnabled:e.gitEnabled,commitDebounceMs:e.commitDebounceMs,wipRef:e.wipRef,enableTestRoutes:e.enableTestRoutes,shadowRepo:e.shadowRepo,destroyTimeoutMs:e.destroyTimeoutMs,localOpCliArgs:e.localOpCliArgs,authStreamHeartbeatMs:e.authStreamHeartbeatMs,onAgentWrite:e.onAgentWrite,lockKind:s,skipStateManifestCheck:e.skipStateManifestCheck,detectGh:e.detectGh,tokenStore:e.tokenStore,embeddingsKeyStore:e.embeddingsKeyStore,singleDocRelPath:e.singleDocRelPath,ephemeral:e.ephemeral}),{hocuspocus:y,destroy:b,ready:x,degraded:S,lockDir:C,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne}=v,re=(()=>{let t=e.host??`localhost`;return t===`0.0.0.0`||t===`::`?`localhost`:t.includes(`:`)&&!t.startsWith(`[`)?`[${t}]`:t})(),ie=e.port??0,ae=e.ephemeral?void 0:Q8({contentDir:e.contentDir,projectDir:e.projectDir??e.contentDir,config:e.config,getServerUrl:()=>`http://${re}:${ie}`,log:r}),oe=c();oe.headersTimeout=3e4,oe.requestTimeout=6e4;let se=e.serveContentAssets===!1?void 0:IA({contentFilter:v.contentFilter,contentSirv:Ns(e.contentDir,{dev:!0,dotfiles:!1}),inlineExtensions:_o,assetExtensions:Na,blocklistExtensions:ka}),ce=!1;if(e.reactShellDistDir)try{eB(C,{port:0,worktreeRoot:e.projectDir??e.contentDir}),ce=!0}catch(e){if(e instanceof $z)r.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 le=e.reactShellDistDir?Ns(e.reactShellDistDir,{single:!0,gzip:!0,immutable:!0}):void 0,ue=e.ephemeral?null:new FD({contentDir:e.contentDir,localDir:C,globalDir:z(Xl(),`.ok`),registry:v.acpRegistry,permissions:v.acpPermissions,sessionManager:w,agentPresenceBroadcaster:te,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:()=>`http://${re}:${ie}`,getMcpStdioCommand:()=>PD(e.localOpCliArgs,ie),probeHarnessManagedMcpEntry:e.probeHarnessManagedMcpEntry,log:r});ue!==null&&await ue.init(),i!==null&&r.info({url:i.url},`[remote] remote access enabled (trust-the-tunnel)`);let de=e5({httpServer:oe,hocuspocus:y,mcpHttpHandler:ae,remoteAccess:i,log:r,sessionManager:w,agentFocusBroadcaster:ee,agentPresenceBroadcaster:te,maintenanceCoordinator:ne,keepaliveGraceMs:e.keepaliveGraceMs,contentAssetMiddleware:se,reactShellMiddleware:le,ephemeral:e.ephemeral,acpThreadManager:ue}),fe=async()=>{throw Error(`bootServer: destroy() invoked before initialization — boot did not complete`)},pe=null;a!==null&&(pe=SY({httpServer:oe,thresholdMs:a??18e5,log:r,onShutdown:(e.idleShutdownHandler??(e=>async()=>{await e()}))(async()=>{await fe()})})),await R9({hocuspocus:y,projectDir:e.projectDir??e.contentDir,log:r});try{await new Promise((t,n)=>{let r=e=>n(e);oe.once(`error`,r),oe.listen(e.port,e.host,()=>{oe.removeListener(`error`,r),t()})})}catch(e){if(ce)try{rB(C)}catch(e){r.warn({err:e},`releaseUiLock failed during listen-error cleanup`)}throw await b().catch(()=>{}),u(C),e}let me=$B();me!==void 0&&eV(`httpListenMs`,me);let he=oe.address(),ge=typeof he==`object`&&he?he.port:e.port??0;if(ie=ge,d(C,ge),ce&&tB(C,ge),n&&e.spawnUiSiblingFn)try{await e.spawnUiSiblingFn({lockDir:C,log:r})}catch(e){r.warn({err:e},`spawnUiSiblingFn failed`)}let _e=!1,ve=async(e,t)=>{let n;try{await Promise.race([t(),new Promise((t,r)=>{n=setTimeout(()=>{r(Error(`${e} timed out after ${L9}ms`))},L9),n.unref?.()})])}finally{n!==void 0&&clearTimeout(n)}};fe=async()=>{if(_e)return;_e=!0;let e=[],t=async(t,n)=>{try{await ve(t,n)}catch(n){e.push(n),r.warn({err:n,step:t},`bootServer destroy step failed`)}};try{l(C),ce&&iB(C)}catch(e){r.warn({err:e,step:`markLocksDraining`},`bootServer destroy step failed`)}try{pe?.detach()}catch(t){e.push(t),r.warn({err:t,step:`idleHandle.detach`},`bootServer destroy step failed`)}if(ue!==null&&await t(`acpThreads.destroy`,()=>ue.destroy()),await t(`mount.shutdown`,()=>de.shutdown()),ae!==void 0&&await t(`mcpHttpHandler.close`,()=>ae.close()),await t(`mount.wss.close`,()=>new Promise((e,t)=>{de.wss.close(n=>n?t(n):e())})),await t(`httpServer.closeAllConnections`,async()=>{oe.closeAllConnections?.()}),await t(`httpServer.close`,()=>new Promise((e,t)=>{oe.close(n=>n&&n.code!==`ERR_SERVER_NOT_RUNNING`?t(n):e())})),await t(`destroyHocuspocus`,()=>b()),ce&&await t(`releaseUiLock`,async()=>rB(C,{deferUnlinkToExit:!0})),await t(`shutdownTelemetry`,()=>es()),await t(`teardownToleranceTelemetry`,()=>I9()),await t(`flushLogFileSinks`,()=>is.flushAllFileSinks()),e.length>0)throw AggregateError(e,`bootServer destroy completed with errors`)};try{let t=await Uz({projectDir:p,skillsRoot:z(e.contentDir,`.ok`,`skills`)}),n=t.healed.length+t.adopted.length+t.replaced.length+t.collided.length+t.orphansRemoved.length;n>0&&r.info?.({event:`installed-skills-reconciled`,healed:t.healed.length,adopted:t.adopted.length,replaced:t.replaced.length,collided:t.collided.length,orphansRemoved:t.orphansRemoved.length},`Reconciled ${n} editor skill entr${n===1?`y`:`ies`} to the symlink model.`)}catch(e){r.warn?.({event:`installed-skills-reconcile-failed`,err:e},`Installed-skills reconcile failed (non-fatal).`)}return{httpServer:oe,destroy:fe,lockDir:C,contentDir:e.contentDir,port:ge,ready:x,degraded:S,didAutoInit:f,serverInstance:v,acpThreadManager:ue}}async function R9(e){let{hocuspocus:t,projectDir:n,log:r}=e,i,a;try{i=new hY(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=Ou(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=ps({baseDir:n,timeout:{block:5e3}});s=new Set(await dS(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=_C(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 cve=Ga;function lve(e={}){let t=e.home??Xl(),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 z9=t(ss(),1);const B9=L(Xl(),`.ok`,`logs`),uve=[`authorization`,`password`,`token`,`apiKey`,`secret`,`*.authorization`,`*.password`,`*.token`,`*.apiKey`,`*.secret`];function dve(){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 fve(e){Nl(e,{recursive:!0})}function V9(){return new Date().toISOString().slice(0,10)}function pve(e){try{if(Wl(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{Vl(n,r)}catch{}}try{Gl(`${e}.3`)}catch{}}function mve(e){try{let t=Date.now(),n=10080*60*1e3,r=Rl(e).filter(e=>e.endsWith(`.log`)||/\.log\.\d+$/.test(e)).map(t=>{try{let n=Wl(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{Gl(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{Gl(L(e,t.name)),a-=t.size}catch{}}}catch{}}function hve(e){fve(B9);let t=V9(),n=e.filePath??L(B9,`${e.name}.${t}.log`);pve(n),(e._setTimeout??setTimeout)(()=>mve(B9),5e3).unref();let r=z9.default.destination({dest:n,append:!0,sync:!0});return(0,z9.default)({level:dve(),name:e.name,redact:{paths:uve,censor:`[REDACTED]`},base:{pid:process.pid,hostname:void 0,runtime:`cli`,project:e.project??`<no-project>`},timestamp:z9.default.stdTimeFunctions.isoTime,...e.additionalOptions},r)}function gve(e,t=250){return new Promise(n=>{if(!e){n();return}let r=e[z9.default.symbols.streamSym],i=!1,a=()=>{i||(i=!0,n())};if(!r||typeof r.flushSync!=`function`){a();return}let o=()=>{try{r.flushSync?.()}catch{}a()},s=setTimeout(a,t);typeof s.unref==`function`&&s.unref(),typeof r.fd==`number`&&r.fd>=0?(clearTimeout(s),o()):typeof r.once==`function`?r.once(`ready`,()=>{clearTimeout(s),o()}):(clearTimeout(s),o())})}function _ve(e){return L(B9,`${e}.${V9()}.log`)}function vve(){return B9}function yve(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 H9=vu(pl),U9=F(`project-git`);var W9=class extends Error{stderr;constructor(e,t=``,n){super(e,n),this.name=`ProjectGitInitError`,this.stderr=t}};async function bve(e,t){try{let{stdout:n}=await H9(e,[`rev-parse`,`--is-inside-work-tree`],OP({cwd:t,encoding:`utf-8`}));return n.trim()===`true`}catch{return!1}}async function xve(e){let t=z(e),n=z(t,`.git`),r=z(n,`HEAD`),i=!1;if(B(n)){if(!Wl(n).isDirectory()||B(r))return{didInit:!1};U9.info({},`detected partial .git/ — running git init to repair`),i=!0}let a;try{a=RR()}catch(e){throw e instanceof FR||e instanceof IR?(oW(e),U9.warn({event:`git_preflight_fail`,platform:e.platform,reason:e instanceof IR?`too_old`:`not_available`,detectedVersion:e instanceof IR?e.detected:``},e instanceof IR?`git binary too old`:`git binary not found`)):U9.warn({event:`git_preflight_unexpected_error`,err:e},`unexpected error during git preflight`),e}let o=a.resolvedPath;if(!i&&await bve(o,t))return{didInit:!1};let s=``;try{s=(await H9(o,[`init`,`--initial-branch=main`,t],OP({encoding:`utf-8`}))).stderr??``}catch(e){let n=typeof e==`object`&&e&&`stderr`in e?String(e.stderr??``):``;throw new W9(`git init failed at ${t}: ${e instanceof Error?e.message:String(e)}`,n,{cause:e})}if(!B(r))throw new W9(`git init reported success but ${n}/HEAD is missing (partial init detected)`,s);return i?(U9.info({path:t},`backfilled missing .git/HEAD`),{didInit:!0,repaired:!0}):(U9.info({path:t,branch:`main`},`initialized .git/`),{didInit:!0})}const G9=F(`project-skill-git`),K9=/^[0-9a-f]{40}$/,Sve=Ci.map(e=>e.replace(/\/$/,``));async function Cve(e){let t=Ou(e);if(t===null)return{kind:`skipped`,reason:`no-git`};if(Dve(t))return{kind:`skipped`,reason:`operation-in-progress`};let n=ms(e);if((await q9(n)).length===0)return{kind:`nothing-tracked`};try{return await fs(async()=>{let t=await wve(n);if(t===null)return{kind:`skipped`,reason:`detached-head`};let r=await Tve(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=ms(e,{gitIndexFile:L($l(),`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 Eve(n,r);if(s!==null&&s===o)return{kind:`nothing-tracked`};let c=await wH(e),l=c?.name??`OpenKnowledge`,u=c?.email??`sync@open-knowledge.local`;gs(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 \`${Ie}\` 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 Sve){let r=``;try{r=(await e.git.raw([`ls-files`,`--`,n])).trim()}catch{r=``}r.length>0&&t.push(n)}return t}async function wve(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 Tve(e){try{let t=(await e.git.raw([`rev-parse`,`--verify`,`HEAD`])).trim();return K9.test(t)?t:null}catch{return null}}async function Eve(e,t){try{let n=(await e.git.raw([`rev-parse`,`${t}^{tree}`])).trim();return K9.test(n)?n:null}catch{return null}}function Dve(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 Ove(e,t){let n;try{n=fl(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 iu(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 kve=[{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 kve)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 Ave(e){if(!hC(e))throw new $9(e);let t;try{t=Bl(z(e))}catch(t){throw t.code===`ENOENT`?new Z9(e):t}if(!Wl(t).isFile())throw new Q9(e);let n=I(t),r=cH(n);if(r){let e=r.rootPath;return{mode:`project`,projectRoot:e,docName:_C(R(jve(e),t).split(Cl).join(`/`)),canonicalFilePath:t}}let i=_l(t);return{mode:`ephemeral`,canonicalFilePath:t,contentDir:n,singleDocRelPath:i,docName:_C(i)}}function jve(e){return z(e,Do({absPath:Ao(`project`,e),sideline:!1,warn:()=>{}}).value.content?.dir??`.`)}function Mve(e){let t=Pl(z($l(),`ok-ephemeral-`)),n=z(t,`.ok`);return Nl(n,{recursive:!0}),Kl(z(n,`config.yml`),`# Ephemeral single-file session (\`ok <file>\`). Throwaway — safe to delete.\ncontent:\n dir: ${JSON.stringify(e)}\n`,`utf-8`),Kl(z(n,`.gitignore`),`local/
3272
3272
  `,`utf-8`),t}export{o4 as $,zS as $i,hR as $n,HN as $r,nW as $t,n9 as A,mE as Ai,rV as An,kI as Ar,nY as At,b7 as B,fC as Bi,NR as Bn,eF as Br,nK as Bt,w9 as C,FD as Ci,SV as Cn,zoe as Cr,uY as Ct,t9 as D,hE as Di,oV as Dn,jI as Dr,Kq as Dt,Q7 as E,$T as Ei,aV as En,NI as Er,qq as Et,E7 as F,IC as Fi,nB as Fn,kF as Fr,ZG as Ft,e5 as G,GS as Gi,BR as Gn,gP as Gr,sK as Gt,g7 as H,dC as Hi,tz as Hn,AP as Hr,pK as Ht,Hge as I,G as Ii,rB as In,QP as Ir,dK as It,Y8 as J,HS as Ji,kR as Jn,hP as Jr,JG as Jt,t5 as K,KS as Ki,MR as Kn,dP as Kr,rK as Kt,O7 as L,FC as Li,tB as Ln,ZP as Lr,lK as Lt,Z7 as M,OT as Mi,VB as Mn,iI as Mr,wK as Mt,G7 as N,kT as Ni,$z as Nn,voe as Nr,xK as Nt,i9 as O,vE as Oi,cV as On,Poe as Or,hJ as Ot,H7 as P,ZT as Pi,eB as Pn,AF as Pr,gK as Pt,t4 as Q,tC as Qi,CR as Qn,VN as Qr,oW as Qt,D7 as R,mC as Ri,FR as Rn,tF as Rr,fK as Rt,I9 as S,xu as Sa,RD as Si,UV as Sn,RI as Sr,cY as St,x9 as T,PD as Ti,pV as Tn,PI as Tr,aY as Tt,r5 as U,oC as Ui,LR as Un,LP as Ur,aK as Ut,y7 as V,lC as Vi,RR as Vn,YP as Vr,uK as Vt,i5 as W,eC as Wi,WR as Wn,OP as Wr,iK as Wt,$2 as X,BS as Xi,ER as Xn,mP as Xr,cW as Xt,z8 as Y,YS as Yi,jR as Yn,fP as Yr,uW as Yt,e4 as Z,WS as Zi,vR as Zn,pP as Zr,aW as Zt,cve as _,$u as _a,Hk as _i,HV as _n,gL as _r,pY as _t,Ave as a,AS as aa,cN as ai,MH as an,fR as ar,Ase as at,F9 as b,ku as ba,BD as bi,WV as bn,BI as br,oY as bt,Cve as c,yS as ca,zA as ci,AH as cn,tR as cr,N2 as ct,yve as d,Th as da,IA as di,sH as dn,QL as dr,YZ as dt,$S as ea,eP as ei,tW as en,dR as er,Hse as et,hve as f,Oh as fa,$k as fi,yV as fn,RL as fr,CZ as ft,lve as g,cd as ga,qk as gi,KV as gn,VL as gr,SY as gt,vve as h,ed as ha,Yk as hi,TV as hn,BL as hr,GZ as ht,Mve as i,LS as ia,fN as ii,LH as in,cR as ir,kse as it,r9 as j,aE as ji,YB as jn,Noe as jr,sJ as jt,$7 as k,pE as ki,sV as kn,AI as kr,gJ as kt,W9 as l,Qre as la,RA as li,zH as ln,$L as lr,P2 as lt,_ve as m,sd as ma,Vk as mi,EV as mn,FL as mr,VZ as mt,Z9 as n,QS as na,gN as ni,OH as nn,mR as nr,K2 as nt,X9 as o,OS as oa,dN as oi,VH as on,uR as or,jse as ot,gve as p,Dh as pa,Xk as pi,GV as pn,zL as pr,fQ as pt,Q8 as q,qS as qi,AR as qn,sP as qr,qG as qt,$9 as r,nC as ra,pN as ri,IH as rn,lR as rr,V2 as rt,Ove as s,ES as sa,uN as si,RH as sn,eR as sr,F2 as st,Q9 as t,ZS as ta,hN as ti,QU as tn,pR as tr,q2 as tt,xve as u,Eh as ua,BA as ui,cH as un,GL as ur,L0 as ut,ove as v,Mu as va,Bk as vi,LV as vn,QI as vr,sY as vt,C9 as w,Yie as wi,fV as wn,MI as wr,fY as wt,P9 as x,Su as xa,zD as xi,aH as xn,VI as xr,lY as xt,R9 as y,ju as ya,zk as yi,wV as yn,zI as yr,dY as yt,Age as z,cC as zi,IR as zn,$P as zr,tK as zt};
3273
- //# sourceMappingURL=src-CMWx7wd8.mjs.map
3273
+ //# sourceMappingURL=src-CepmZgB5.mjs.map